3
0

ash.c 305 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726
  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"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: Tha 'ash' shell adds about 60k in the default configuration and is
  24. //config: the most complete and most pedantically correct shell included with
  25. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  26. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  27. //config: (written by Kenneth Almquist) from NetBSD.
  28. //config:
  29. //config:# ash options
  30. //config:# note: Don't remove !NOMMU part in the next line; it would break
  31. //config:# menuconfig's indenting.
  32. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  33. //config:
  34. //config:config ASH_OPTIMIZE_FOR_SIZE
  35. //config: bool "Optimize for size instead of speed"
  36. //config: default y
  37. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  38. //config:
  39. //config:config ASH_INTERNAL_GLOB
  40. //config: bool "Use internal glob() implementation"
  41. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  42. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  43. //config: help
  44. //config: Do not use glob() function from libc, use internal implementation.
  45. //config: Use this if you are getting "glob.h: No such file or directory"
  46. //config: or similar build errors.
  47. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  48. //config: which would break ash if you select N here.
  49. //config:
  50. //config:config ASH_BASH_COMPAT
  51. //config: bool "bash-compatible extensions"
  52. //config: default y
  53. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  54. //config:
  55. //config:config ASH_JOB_CONTROL
  56. //config: bool "Job control"
  57. //config: default y
  58. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  59. //config:
  60. //config:config ASH_ALIAS
  61. //config: bool "Alias support"
  62. //config: default y
  63. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  64. //config:
  65. //config:config ASH_RANDOM_SUPPORT
  66. //config: bool "Pseudorandom generator and $RANDOM variable"
  67. //config: default y
  68. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  69. //config: help
  70. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  71. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  72. //config: You can reset the generator by using a specified start value.
  73. //config: After "unset RANDOM" the generator will switch off and this
  74. //config: variable will no longer have special treatment.
  75. //config:
  76. //config:config ASH_EXPAND_PRMT
  77. //config: bool "Expand prompt string"
  78. //config: default y
  79. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  80. //config: help
  81. //config: $PS# may contain volatile content, such as backquote commands.
  82. //config: This option recreates the prompt string from the environment
  83. //config: variable each time it is displayed.
  84. //config:
  85. //config:config ASH_IDLE_TIMEOUT
  86. //config: bool "Idle timeout variable $TMOUT"
  87. //config: default y
  88. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  89. //config: help
  90. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  91. //config:
  92. //config:config ASH_MAIL
  93. //config: bool "Check for new mail in interactive shell"
  94. //config: default y
  95. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  96. //config: help
  97. //config: Enable "check for new mail" function:
  98. //config: if set, $MAIL file and $MAILPATH list of files
  99. //config: are checked for mtime changes, and "you have mail"
  100. //config: message is printed if change is detected.
  101. //config:
  102. //config:config ASH_ECHO
  103. //config: bool "echo builtin"
  104. //config: default y
  105. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  106. //config:
  107. //config:config ASH_PRINTF
  108. //config: bool "printf builtin"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config:
  112. //config:config ASH_TEST
  113. //config: bool "test builtin"
  114. //config: default y
  115. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  116. //config:
  117. //config:config ASH_HELP
  118. //config: bool "help builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_GETOPTS
  123. //config: bool "getopts builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_CMDCMD
  128. //config: bool "command builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config: help
  132. //config: Enable support for the 'command' builtin, which allows
  133. //config: you to run the specified command or builtin,
  134. //config: even when there is a function with the same name.
  135. //config:
  136. //config:endif # ash options
  137. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  138. // APPLET_ODDNAME:name main location suid_type help
  139. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  140. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  141. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  142. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  143. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  144. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  145. /*
  146. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  147. * DEBUG=2 to compile in and turn on debugging.
  148. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  149. * debugging info is written to ./trace, quit signal generates core dump.
  150. */
  151. #define DEBUG 0
  152. /* Tweak debug output verbosity here */
  153. #define DEBUG_TIME 0
  154. #define DEBUG_PID 1
  155. #define DEBUG_SIG 1
  156. #define DEBUG_INTONOFF 0
  157. #define PROFILE 0
  158. #define JOBS ENABLE_ASH_JOB_CONTROL
  159. #include <setjmp.h>
  160. #include <fnmatch.h>
  161. #include <sys/times.h>
  162. #include <sys/utsname.h> /* for setting $HOSTNAME */
  163. #include "busybox.h" /* for applet_names */
  164. /* So far, all bash compat is controlled by one config option */
  165. /* Separate defines document which part of code implements what */
  166. /* function keyword */
  167. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  168. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  169. /* &>file */
  170. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  171. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  172. /* $'...' */
  173. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  174. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  175. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  176. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  177. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  178. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  179. /* [[ EXPR ]] */
  180. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  181. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  182. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  183. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  184. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  185. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  186. /* Bionic at least up to version 24 has no glob() */
  187. # undef ENABLE_ASH_INTERNAL_GLOB
  188. # define ENABLE_ASH_INTERNAL_GLOB 1
  189. #endif
  190. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  191. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  192. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  193. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  194. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  195. # error fails to match dirname, subsequently not expanding <pattern> in it.
  196. // Testcase:
  197. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  198. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  199. #endif
  200. #if !ENABLE_ASH_INTERNAL_GLOB
  201. # include <glob.h>
  202. #endif
  203. #include "unicode.h"
  204. #include "shell_common.h"
  205. #if ENABLE_FEATURE_SH_MATH
  206. # include "math.h"
  207. #endif
  208. #if ENABLE_ASH_RANDOM_SUPPORT
  209. # include "random.h"
  210. #else
  211. # define CLEAR_RANDOM_T(rnd) ((void)0)
  212. #endif
  213. #include "NUM_APPLETS.h"
  214. #if NUM_APPLETS == 1
  215. /* STANDALONE does not make sense, and won't compile */
  216. # undef CONFIG_FEATURE_SH_STANDALONE
  217. # undef ENABLE_FEATURE_SH_STANDALONE
  218. # undef IF_FEATURE_SH_STANDALONE
  219. # undef IF_NOT_FEATURE_SH_STANDALONE
  220. # define ENABLE_FEATURE_SH_STANDALONE 0
  221. # define IF_FEATURE_SH_STANDALONE(...)
  222. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  223. #endif
  224. #ifndef PIPE_BUF
  225. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  226. #endif
  227. #if !BB_MMU
  228. # error "Do not even bother, ash will not run on NOMMU machine"
  229. #endif
  230. /* ============ Hash table sizes. Configurable. */
  231. #define VTABSIZE 39
  232. #define ATABSIZE 39
  233. #define CMDTABLESIZE 31 /* should be prime */
  234. /* ============ Shell options */
  235. static const char *const optletters_optnames[] = {
  236. "e" "errexit",
  237. "f" "noglob",
  238. "I" "ignoreeof",
  239. "i" "interactive",
  240. "m" "monitor",
  241. "n" "noexec",
  242. "s" "stdin",
  243. "x" "xtrace",
  244. "v" "verbose",
  245. "C" "noclobber",
  246. "a" "allexport",
  247. "b" "notify",
  248. "u" "nounset",
  249. "\0" "vi"
  250. #if BASH_PIPEFAIL
  251. ,"\0" "pipefail"
  252. #endif
  253. #if DEBUG
  254. ,"\0" "nolog"
  255. ,"\0" "debug"
  256. #endif
  257. };
  258. #define optletters(n) optletters_optnames[n][0]
  259. #define optnames(n) (optletters_optnames[n] + 1)
  260. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  261. /* ============ Misc data */
  262. #define msg_illnum "Illegal number: %s"
  263. /*
  264. * We enclose jmp_buf in a structure so that we can declare pointers to
  265. * jump locations. The global variable handler contains the location to
  266. * jump to when an exception occurs, and the global variable exception_type
  267. * contains a code identifying the exception. To implement nested
  268. * exception handlers, the user should save the value of handler on entry
  269. * to an inner scope, set handler to point to a jmploc structure for the
  270. * inner scope, and restore handler on exit from the scope.
  271. */
  272. struct jmploc {
  273. jmp_buf loc;
  274. };
  275. struct globals_misc {
  276. uint8_t exitstatus; /* exit status of last command */
  277. uint8_t back_exitstatus;/* exit status of backquoted command */
  278. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  279. int rootpid; /* pid of main shell */
  280. /* shell level: 0 for the main shell, 1 for its children, and so on */
  281. int shlvl;
  282. #define rootshell (!shlvl)
  283. char *minusc; /* argument to -c option */
  284. char *curdir; // = nullstr; /* current working directory */
  285. char *physdir; // = nullstr; /* physical working directory */
  286. char *arg0; /* value of $0 */
  287. struct jmploc *exception_handler;
  288. volatile int suppress_int; /* counter */
  289. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  290. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  291. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  292. smallint exception_type; /* kind of exception (0..5) */
  293. /* exceptions */
  294. #define EXINT 0 /* SIGINT received */
  295. #define EXERROR 1 /* a generic error */
  296. #define EXEXIT 4 /* exit the shell */
  297. smallint isloginsh;
  298. char nullstr[1]; /* zero length string */
  299. char optlist[NOPTS];
  300. #define eflag optlist[0]
  301. #define fflag optlist[1]
  302. #define Iflag optlist[2]
  303. #define iflag optlist[3]
  304. #define mflag optlist[4]
  305. #define nflag optlist[5]
  306. #define sflag optlist[6]
  307. #define xflag optlist[7]
  308. #define vflag optlist[8]
  309. #define Cflag optlist[9]
  310. #define aflag optlist[10]
  311. #define bflag optlist[11]
  312. #define uflag optlist[12]
  313. #define viflag optlist[13]
  314. #if BASH_PIPEFAIL
  315. # define pipefail optlist[14]
  316. #else
  317. # define pipefail 0
  318. #endif
  319. #if DEBUG
  320. # define nolog optlist[14 + BASH_PIPEFAIL]
  321. # define debug optlist[15 + BASH_PIPEFAIL]
  322. #endif
  323. /* trap handler commands */
  324. /*
  325. * Sigmode records the current value of the signal handlers for the various
  326. * modes. A value of zero means that the current handler is not known.
  327. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  328. */
  329. char sigmode[NSIG - 1];
  330. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  331. #define S_CATCH 2 /* signal is caught */
  332. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  333. #define S_HARD_IGN 4 /* signal is ignored permanently */
  334. /* indicates specified signal received */
  335. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  336. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  337. char *trap[NSIG];
  338. char **trap_ptr; /* used only by "trap hack" */
  339. /* Rarely referenced stuff */
  340. #if ENABLE_ASH_RANDOM_SUPPORT
  341. random_t random_gen;
  342. #endif
  343. pid_t backgndpid; /* pid of last background process */
  344. };
  345. extern struct globals_misc *const ash_ptr_to_globals_misc;
  346. #define G_misc (*ash_ptr_to_globals_misc)
  347. #define exitstatus (G_misc.exitstatus )
  348. #define back_exitstatus (G_misc.back_exitstatus )
  349. #define job_warning (G_misc.job_warning)
  350. #define rootpid (G_misc.rootpid )
  351. #define shlvl (G_misc.shlvl )
  352. #define minusc (G_misc.minusc )
  353. #define curdir (G_misc.curdir )
  354. #define physdir (G_misc.physdir )
  355. #define arg0 (G_misc.arg0 )
  356. #define exception_handler (G_misc.exception_handler)
  357. #define exception_type (G_misc.exception_type )
  358. #define suppress_int (G_misc.suppress_int )
  359. #define pending_int (G_misc.pending_int )
  360. #define got_sigchld (G_misc.got_sigchld )
  361. #define pending_sig (G_misc.pending_sig )
  362. #define isloginsh (G_misc.isloginsh )
  363. #define nullstr (G_misc.nullstr )
  364. #define optlist (G_misc.optlist )
  365. #define sigmode (G_misc.sigmode )
  366. #define gotsig (G_misc.gotsig )
  367. #define may_have_traps (G_misc.may_have_traps )
  368. #define trap (G_misc.trap )
  369. #define trap_ptr (G_misc.trap_ptr )
  370. #define random_gen (G_misc.random_gen )
  371. #define backgndpid (G_misc.backgndpid )
  372. #define INIT_G_misc() do { \
  373. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  374. barrier(); \
  375. curdir = nullstr; \
  376. physdir = nullstr; \
  377. trap_ptr = trap; \
  378. } while (0)
  379. /* ============ DEBUG */
  380. #if DEBUG
  381. static void trace_printf(const char *fmt, ...);
  382. static void trace_vprintf(const char *fmt, va_list va);
  383. # define TRACE(param) trace_printf param
  384. # define TRACEV(param) trace_vprintf param
  385. # define close(fd) do { \
  386. int dfd = (fd); \
  387. if (close(dfd) < 0) \
  388. bb_error_msg("bug on %d: closing %d(0x%x)", \
  389. __LINE__, dfd, dfd); \
  390. } while (0)
  391. #else
  392. # define TRACE(param)
  393. # define TRACEV(param)
  394. #endif
  395. /* ============ Utility functions */
  396. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  397. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  398. static int
  399. isdigit_str9(const char *str)
  400. {
  401. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  402. while (--maxlen && isdigit(*str))
  403. str++;
  404. return (*str == '\0');
  405. }
  406. static const char *
  407. var_end(const char *var)
  408. {
  409. while (*var)
  410. if (*var++ == '=')
  411. break;
  412. return var;
  413. }
  414. /* ============ Interrupts / exceptions */
  415. static void exitshell(void) NORETURN;
  416. /*
  417. * These macros allow the user to suspend the handling of interrupt signals
  418. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  419. * much more efficient and portable. (But hacking the kernel is so much
  420. * more fun than worrying about efficiency and portability. :-))
  421. */
  422. #if DEBUG_INTONOFF
  423. # define INT_OFF do { \
  424. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  425. suppress_int++; \
  426. barrier(); \
  427. } while (0)
  428. #else
  429. # define INT_OFF do { \
  430. suppress_int++; \
  431. barrier(); \
  432. } while (0)
  433. #endif
  434. /*
  435. * Called to raise an exception. Since C doesn't include exceptions, we
  436. * just do a longjmp to the exception handler. The type of exception is
  437. * stored in the global variable "exception_type".
  438. */
  439. static void raise_exception(int) NORETURN;
  440. static void
  441. raise_exception(int e)
  442. {
  443. #if DEBUG
  444. if (exception_handler == NULL)
  445. abort();
  446. #endif
  447. INT_OFF;
  448. exception_type = e;
  449. longjmp(exception_handler->loc, 1);
  450. }
  451. #if DEBUG
  452. #define raise_exception(e) do { \
  453. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  454. raise_exception(e); \
  455. } while (0)
  456. #endif
  457. /*
  458. * Called when a SIGINT is received. (If the user specifies
  459. * that SIGINT is to be trapped or ignored using the trap builtin, then
  460. * this routine is not called.) Suppressint is nonzero when interrupts
  461. * are held using the INT_OFF macro. (The test for iflag is just
  462. * defensive programming.)
  463. */
  464. static void raise_interrupt(void) NORETURN;
  465. static void
  466. raise_interrupt(void)
  467. {
  468. pending_int = 0;
  469. /* Signal is not automatically unmasked after it is raised,
  470. * do it ourself - unmask all signals */
  471. sigprocmask_allsigs(SIG_UNBLOCK);
  472. /* pending_sig = 0; - now done in signal_handler() */
  473. if (!(rootshell && iflag)) {
  474. /* Kill ourself with SIGINT */
  475. signal(SIGINT, SIG_DFL);
  476. raise(SIGINT);
  477. }
  478. /* bash: ^C even on empty command line sets $? */
  479. exitstatus = SIGINT + 128;
  480. raise_exception(EXINT);
  481. /* NOTREACHED */
  482. }
  483. #if DEBUG
  484. #define raise_interrupt() do { \
  485. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  486. raise_interrupt(); \
  487. } while (0)
  488. #endif
  489. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  490. int_on(void)
  491. {
  492. barrier();
  493. if (--suppress_int == 0 && pending_int) {
  494. raise_interrupt();
  495. }
  496. }
  497. #if DEBUG_INTONOFF
  498. # define INT_ON do { \
  499. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  500. int_on(); \
  501. } while (0)
  502. #else
  503. # define INT_ON int_on()
  504. #endif
  505. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  506. force_int_on(void)
  507. {
  508. barrier();
  509. suppress_int = 0;
  510. if (pending_int)
  511. raise_interrupt();
  512. }
  513. #define FORCE_INT_ON force_int_on()
  514. #define SAVE_INT(v) ((v) = suppress_int)
  515. #define RESTORE_INT(v) do { \
  516. barrier(); \
  517. suppress_int = (v); \
  518. if (suppress_int == 0 && pending_int) \
  519. raise_interrupt(); \
  520. } while (0)
  521. /* ============ Stdout/stderr output */
  522. static void
  523. outstr(const char *p, FILE *file)
  524. {
  525. INT_OFF;
  526. fputs(p, file);
  527. INT_ON;
  528. }
  529. static void
  530. flush_stdout_stderr(void)
  531. {
  532. INT_OFF;
  533. fflush_all();
  534. INT_ON;
  535. }
  536. /* Was called outcslow(c,FILE*), but c was always '\n' */
  537. static void
  538. newline_and_flush(FILE *dest)
  539. {
  540. INT_OFF;
  541. putc('\n', dest);
  542. fflush(dest);
  543. INT_ON;
  544. }
  545. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  546. static int
  547. out1fmt(const char *fmt, ...)
  548. {
  549. va_list ap;
  550. int r;
  551. INT_OFF;
  552. va_start(ap, fmt);
  553. r = vprintf(fmt, ap);
  554. va_end(ap);
  555. INT_ON;
  556. return r;
  557. }
  558. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  559. static int
  560. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  561. {
  562. va_list ap;
  563. int ret;
  564. va_start(ap, fmt);
  565. INT_OFF;
  566. ret = vsnprintf(outbuf, length, fmt, ap);
  567. va_end(ap);
  568. INT_ON;
  569. return ret;
  570. }
  571. static void
  572. out1str(const char *p)
  573. {
  574. outstr(p, stdout);
  575. }
  576. static void
  577. out2str(const char *p)
  578. {
  579. outstr(p, stderr);
  580. flush_stdout_stderr();
  581. }
  582. /* ============ Parser structures */
  583. /* control characters in argument strings */
  584. #define CTL_FIRST CTLESC
  585. #define CTLESC ((unsigned char)'\201') /* escape next character */
  586. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  587. #define CTLENDVAR ((unsigned char)'\203')
  588. #define CTLBACKQ ((unsigned char)'\204')
  589. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  590. #define CTLENDARI ((unsigned char)'\207')
  591. #define CTLQUOTEMARK ((unsigned char)'\210')
  592. #define CTL_LAST CTLQUOTEMARK
  593. /* variable substitution byte (follows CTLVAR) */
  594. #define VSTYPE 0x0f /* type of variable substitution */
  595. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  596. /* values of VSTYPE field */
  597. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  598. #define VSMINUS 0x2 /* ${var-text} */
  599. #define VSPLUS 0x3 /* ${var+text} */
  600. #define VSQUESTION 0x4 /* ${var?message} */
  601. #define VSASSIGN 0x5 /* ${var=text} */
  602. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  603. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  604. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  605. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  606. #define VSLENGTH 0xa /* ${#var} */
  607. #if BASH_SUBSTR
  608. #define VSSUBSTR 0xc /* ${var:position:length} */
  609. #endif
  610. #if BASH_PATTERN_SUBST
  611. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  612. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  613. #endif
  614. static const char dolatstr[] ALIGN1 = {
  615. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  616. };
  617. #define DOLATSTRLEN 6
  618. #define NCMD 0
  619. #define NPIPE 1
  620. #define NREDIR 2
  621. #define NBACKGND 3
  622. #define NSUBSHELL 4
  623. #define NAND 5
  624. #define NOR 6
  625. #define NSEMI 7
  626. #define NIF 8
  627. #define NWHILE 9
  628. #define NUNTIL 10
  629. #define NFOR 11
  630. #define NCASE 12
  631. #define NCLIST 13
  632. #define NDEFUN 14
  633. #define NARG 15
  634. #define NTO 16
  635. #if BASH_REDIR_OUTPUT
  636. #define NTO2 17
  637. #endif
  638. #define NCLOBBER 18
  639. #define NFROM 19
  640. #define NFROMTO 20
  641. #define NAPPEND 21
  642. #define NTOFD 22
  643. #define NFROMFD 23
  644. #define NHERE 24
  645. #define NXHERE 25
  646. #define NNOT 26
  647. #define N_NUMBER 27
  648. union node;
  649. struct ncmd {
  650. smallint type; /* Nxxxx */
  651. union node *assign;
  652. union node *args;
  653. union node *redirect;
  654. };
  655. struct npipe {
  656. smallint type;
  657. smallint pipe_backgnd;
  658. struct nodelist *cmdlist;
  659. };
  660. struct nredir {
  661. smallint type;
  662. union node *n;
  663. union node *redirect;
  664. };
  665. struct nbinary {
  666. smallint type;
  667. union node *ch1;
  668. union node *ch2;
  669. };
  670. struct nif {
  671. smallint type;
  672. union node *test;
  673. union node *ifpart;
  674. union node *elsepart;
  675. };
  676. struct nfor {
  677. smallint type;
  678. union node *args;
  679. union node *body;
  680. char *var;
  681. };
  682. struct ncase {
  683. smallint type;
  684. union node *expr;
  685. union node *cases;
  686. };
  687. struct nclist {
  688. smallint type;
  689. union node *next;
  690. union node *pattern;
  691. union node *body;
  692. };
  693. struct narg {
  694. smallint type;
  695. union node *next;
  696. char *text;
  697. struct nodelist *backquote;
  698. };
  699. /* nfile and ndup layout must match!
  700. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  701. * that it is actually NTO2 (>&file), and change its type.
  702. */
  703. struct nfile {
  704. smallint type;
  705. union node *next;
  706. int fd;
  707. int _unused_dupfd;
  708. union node *fname;
  709. char *expfname;
  710. };
  711. struct ndup {
  712. smallint type;
  713. union node *next;
  714. int fd;
  715. int dupfd;
  716. union node *vname;
  717. char *_unused_expfname;
  718. };
  719. struct nhere {
  720. smallint type;
  721. union node *next;
  722. int fd;
  723. union node *doc;
  724. };
  725. struct nnot {
  726. smallint type;
  727. union node *com;
  728. };
  729. union node {
  730. smallint type;
  731. struct ncmd ncmd;
  732. struct npipe npipe;
  733. struct nredir nredir;
  734. struct nbinary nbinary;
  735. struct nif nif;
  736. struct nfor nfor;
  737. struct ncase ncase;
  738. struct nclist nclist;
  739. struct narg narg;
  740. struct nfile nfile;
  741. struct ndup ndup;
  742. struct nhere nhere;
  743. struct nnot nnot;
  744. };
  745. /*
  746. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  747. * It must be distinct from NULL.
  748. */
  749. #define NODE_EOF ((union node *) -1L)
  750. struct nodelist {
  751. struct nodelist *next;
  752. union node *n;
  753. };
  754. struct funcnode {
  755. int count;
  756. union node n;
  757. };
  758. /*
  759. * Free a parse tree.
  760. */
  761. static void
  762. freefunc(struct funcnode *f)
  763. {
  764. if (f && --f->count < 0)
  765. free(f);
  766. }
  767. /* ============ Debugging output */
  768. #if DEBUG
  769. static FILE *tracefile;
  770. static void
  771. trace_printf(const char *fmt, ...)
  772. {
  773. va_list va;
  774. if (debug != 1)
  775. return;
  776. if (DEBUG_TIME)
  777. fprintf(tracefile, "%u ", (int) time(NULL));
  778. if (DEBUG_PID)
  779. fprintf(tracefile, "[%u] ", (int) getpid());
  780. if (DEBUG_SIG)
  781. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  782. va_start(va, fmt);
  783. vfprintf(tracefile, fmt, va);
  784. va_end(va);
  785. }
  786. static void
  787. trace_vprintf(const char *fmt, va_list va)
  788. {
  789. if (debug != 1)
  790. return;
  791. vfprintf(tracefile, fmt, va);
  792. fprintf(tracefile, "\n");
  793. }
  794. static void
  795. trace_puts(const char *s)
  796. {
  797. if (debug != 1)
  798. return;
  799. fputs(s, tracefile);
  800. }
  801. static void
  802. trace_puts_quoted(char *s)
  803. {
  804. char *p;
  805. char c;
  806. if (debug != 1)
  807. return;
  808. putc('"', tracefile);
  809. for (p = s; *p; p++) {
  810. switch ((unsigned char)*p) {
  811. case '\n': c = 'n'; goto backslash;
  812. case '\t': c = 't'; goto backslash;
  813. case '\r': c = 'r'; goto backslash;
  814. case '\"': c = '\"'; goto backslash;
  815. case '\\': c = '\\'; goto backslash;
  816. case CTLESC: c = 'e'; goto backslash;
  817. case CTLVAR: c = 'v'; goto backslash;
  818. case CTLBACKQ: c = 'q'; goto backslash;
  819. backslash:
  820. putc('\\', tracefile);
  821. putc(c, tracefile);
  822. break;
  823. default:
  824. if (*p >= ' ' && *p <= '~')
  825. putc(*p, tracefile);
  826. else {
  827. putc('\\', tracefile);
  828. putc((*p >> 6) & 03, tracefile);
  829. putc((*p >> 3) & 07, tracefile);
  830. putc(*p & 07, tracefile);
  831. }
  832. break;
  833. }
  834. }
  835. putc('"', tracefile);
  836. }
  837. static void
  838. trace_puts_args(char **ap)
  839. {
  840. if (debug != 1)
  841. return;
  842. if (!*ap)
  843. return;
  844. while (1) {
  845. trace_puts_quoted(*ap);
  846. if (!*++ap) {
  847. putc('\n', tracefile);
  848. break;
  849. }
  850. putc(' ', tracefile);
  851. }
  852. }
  853. static void
  854. opentrace(void)
  855. {
  856. char s[100];
  857. #ifdef O_APPEND
  858. int flags;
  859. #endif
  860. if (debug != 1) {
  861. if (tracefile)
  862. fflush(tracefile);
  863. /* leave open because libedit might be using it */
  864. return;
  865. }
  866. strcpy(s, "./trace");
  867. if (tracefile) {
  868. if (!freopen(s, "a", tracefile)) {
  869. fprintf(stderr, "Can't re-open %s\n", s);
  870. debug = 0;
  871. return;
  872. }
  873. } else {
  874. tracefile = fopen(s, "a");
  875. if (tracefile == NULL) {
  876. fprintf(stderr, "Can't open %s\n", s);
  877. debug = 0;
  878. return;
  879. }
  880. }
  881. #ifdef O_APPEND
  882. flags = fcntl(fileno(tracefile), F_GETFL);
  883. if (flags >= 0)
  884. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  885. #endif
  886. setlinebuf(tracefile);
  887. fputs("\nTracing started.\n", tracefile);
  888. }
  889. static void
  890. indent(int amount, char *pfx, FILE *fp)
  891. {
  892. int i;
  893. for (i = 0; i < amount; i++) {
  894. if (pfx && i == amount - 1)
  895. fputs(pfx, fp);
  896. putc('\t', fp);
  897. }
  898. }
  899. /* little circular references here... */
  900. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  901. static void
  902. sharg(union node *arg, FILE *fp)
  903. {
  904. char *p;
  905. struct nodelist *bqlist;
  906. unsigned char subtype;
  907. if (arg->type != NARG) {
  908. out1fmt("<node type %d>\n", arg->type);
  909. abort();
  910. }
  911. bqlist = arg->narg.backquote;
  912. for (p = arg->narg.text; *p; p++) {
  913. switch ((unsigned char)*p) {
  914. case CTLESC:
  915. p++;
  916. putc(*p, fp);
  917. break;
  918. case CTLVAR:
  919. putc('$', fp);
  920. putc('{', fp);
  921. subtype = *++p;
  922. if (subtype == VSLENGTH)
  923. putc('#', fp);
  924. while (*p != '=') {
  925. putc(*p, fp);
  926. p++;
  927. }
  928. if (subtype & VSNUL)
  929. putc(':', fp);
  930. switch (subtype & VSTYPE) {
  931. case VSNORMAL:
  932. putc('}', fp);
  933. break;
  934. case VSMINUS:
  935. putc('-', fp);
  936. break;
  937. case VSPLUS:
  938. putc('+', fp);
  939. break;
  940. case VSQUESTION:
  941. putc('?', fp);
  942. break;
  943. case VSASSIGN:
  944. putc('=', fp);
  945. break;
  946. case VSTRIMLEFT:
  947. putc('#', fp);
  948. break;
  949. case VSTRIMLEFTMAX:
  950. putc('#', fp);
  951. putc('#', fp);
  952. break;
  953. case VSTRIMRIGHT:
  954. putc('%', fp);
  955. break;
  956. case VSTRIMRIGHTMAX:
  957. putc('%', fp);
  958. putc('%', fp);
  959. break;
  960. case VSLENGTH:
  961. break;
  962. default:
  963. out1fmt("<subtype %d>", subtype);
  964. }
  965. break;
  966. case CTLENDVAR:
  967. putc('}', fp);
  968. break;
  969. case CTLBACKQ:
  970. putc('$', fp);
  971. putc('(', fp);
  972. shtree(bqlist->n, -1, NULL, fp);
  973. putc(')', fp);
  974. break;
  975. default:
  976. putc(*p, fp);
  977. break;
  978. }
  979. }
  980. }
  981. static void
  982. shcmd(union node *cmd, FILE *fp)
  983. {
  984. union node *np;
  985. int first;
  986. const char *s;
  987. int dftfd;
  988. first = 1;
  989. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  990. if (!first)
  991. putc(' ', fp);
  992. sharg(np, fp);
  993. first = 0;
  994. }
  995. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  996. if (!first)
  997. putc(' ', fp);
  998. dftfd = 0;
  999. switch (np->nfile.type) {
  1000. case NTO: s = ">>"+1; dftfd = 1; break;
  1001. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1002. case NAPPEND: s = ">>"; dftfd = 1; break;
  1003. #if BASH_REDIR_OUTPUT
  1004. case NTO2:
  1005. #endif
  1006. case NTOFD: s = ">&"; dftfd = 1; break;
  1007. case NFROM: s = "<"; break;
  1008. case NFROMFD: s = "<&"; break;
  1009. case NFROMTO: s = "<>"; break;
  1010. default: s = "*error*"; break;
  1011. }
  1012. if (np->nfile.fd != dftfd)
  1013. fprintf(fp, "%d", np->nfile.fd);
  1014. fputs(s, fp);
  1015. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1016. fprintf(fp, "%d", np->ndup.dupfd);
  1017. } else {
  1018. sharg(np->nfile.fname, fp);
  1019. }
  1020. first = 0;
  1021. }
  1022. }
  1023. static void
  1024. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1025. {
  1026. struct nodelist *lp;
  1027. const char *s;
  1028. if (n == NULL)
  1029. return;
  1030. indent(ind, pfx, fp);
  1031. if (n == NODE_EOF) {
  1032. fputs("<EOF>", fp);
  1033. return;
  1034. }
  1035. switch (n->type) {
  1036. case NSEMI:
  1037. s = "; ";
  1038. goto binop;
  1039. case NAND:
  1040. s = " && ";
  1041. goto binop;
  1042. case NOR:
  1043. s = " || ";
  1044. binop:
  1045. shtree(n->nbinary.ch1, ind, NULL, fp);
  1046. /* if (ind < 0) */
  1047. fputs(s, fp);
  1048. shtree(n->nbinary.ch2, ind, NULL, fp);
  1049. break;
  1050. case NCMD:
  1051. shcmd(n, fp);
  1052. if (ind >= 0)
  1053. putc('\n', fp);
  1054. break;
  1055. case NPIPE:
  1056. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1057. shtree(lp->n, 0, NULL, fp);
  1058. if (lp->next)
  1059. fputs(" | ", fp);
  1060. }
  1061. if (n->npipe.pipe_backgnd)
  1062. fputs(" &", fp);
  1063. if (ind >= 0)
  1064. putc('\n', fp);
  1065. break;
  1066. default:
  1067. fprintf(fp, "<node type %d>", n->type);
  1068. if (ind >= 0)
  1069. putc('\n', fp);
  1070. break;
  1071. }
  1072. }
  1073. static void
  1074. showtree(union node *n)
  1075. {
  1076. trace_puts("showtree called\n");
  1077. shtree(n, 1, NULL, stderr);
  1078. }
  1079. #endif /* DEBUG */
  1080. /* ============ Parser data */
  1081. /*
  1082. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1083. */
  1084. struct strlist {
  1085. struct strlist *next;
  1086. char *text;
  1087. };
  1088. struct alias;
  1089. struct strpush {
  1090. struct strpush *prev; /* preceding string on stack */
  1091. char *prev_string;
  1092. int prev_left_in_line;
  1093. #if ENABLE_ASH_ALIAS
  1094. struct alias *ap; /* if push was associated with an alias */
  1095. #endif
  1096. char *string; /* remember the string since it may change */
  1097. /* Remember last two characters for pungetc. */
  1098. int lastc[2];
  1099. /* Number of outstanding calls to pungetc. */
  1100. int unget;
  1101. };
  1102. struct parsefile {
  1103. struct parsefile *prev; /* preceding file on stack */
  1104. int linno; /* current line */
  1105. int pf_fd; /* file descriptor (or -1 if string) */
  1106. int left_in_line; /* number of chars left in this line */
  1107. int left_in_buffer; /* number of chars left in this buffer past the line */
  1108. char *next_to_pgetc; /* next char in buffer */
  1109. char *buf; /* input buffer */
  1110. struct strpush *strpush; /* for pushing strings at this level */
  1111. struct strpush basestrpush; /* so pushing one is fast */
  1112. /* Remember last two characters for pungetc. */
  1113. int lastc[2];
  1114. /* Number of outstanding calls to pungetc. */
  1115. int unget;
  1116. };
  1117. static struct parsefile basepf; /* top level input file */
  1118. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1119. static int startlinno; /* line # where last token started */
  1120. static char *commandname; /* currently executing command */
  1121. static struct strlist *cmdenviron; /* environment for builtin command */
  1122. /* ============ Message printing */
  1123. static void
  1124. ash_vmsg(const char *msg, va_list ap)
  1125. {
  1126. fprintf(stderr, "%s: ", arg0);
  1127. if (commandname) {
  1128. if (strcmp(arg0, commandname))
  1129. fprintf(stderr, "%s: ", commandname);
  1130. if (!iflag || g_parsefile->pf_fd > 0)
  1131. fprintf(stderr, "line %d: ", startlinno);
  1132. }
  1133. vfprintf(stderr, msg, ap);
  1134. newline_and_flush(stderr);
  1135. }
  1136. /*
  1137. * Exverror is called to raise the error exception. If the second argument
  1138. * is not NULL then error prints an error message using printf style
  1139. * formatting. It then raises the error exception.
  1140. */
  1141. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1142. static void
  1143. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1144. {
  1145. #if DEBUG
  1146. if (msg) {
  1147. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1148. TRACEV((msg, ap));
  1149. } else
  1150. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1151. if (msg)
  1152. #endif
  1153. ash_vmsg(msg, ap);
  1154. flush_stdout_stderr();
  1155. raise_exception(cond);
  1156. /* NOTREACHED */
  1157. }
  1158. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1159. static void
  1160. ash_msg_and_raise_error(const char *msg, ...)
  1161. {
  1162. va_list ap;
  1163. exitstatus = 2;
  1164. va_start(ap, msg);
  1165. ash_vmsg_and_raise(EXERROR, msg, ap);
  1166. /* NOTREACHED */
  1167. va_end(ap);
  1168. }
  1169. static void raise_error_syntax(const char *) NORETURN;
  1170. static void
  1171. raise_error_syntax(const char *msg)
  1172. {
  1173. ash_msg_and_raise_error("syntax error: %s", msg);
  1174. /* NOTREACHED */
  1175. }
  1176. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1177. static void
  1178. ash_msg_and_raise(int cond, const char *msg, ...)
  1179. {
  1180. va_list ap;
  1181. va_start(ap, msg);
  1182. ash_vmsg_and_raise(cond, msg, ap);
  1183. /* NOTREACHED */
  1184. va_end(ap);
  1185. }
  1186. /*
  1187. * error/warning routines for external builtins
  1188. */
  1189. static void
  1190. ash_msg(const char *fmt, ...)
  1191. {
  1192. va_list ap;
  1193. va_start(ap, fmt);
  1194. ash_vmsg(fmt, ap);
  1195. va_end(ap);
  1196. }
  1197. /*
  1198. * Return a string describing an error. The returned string may be a
  1199. * pointer to a static buffer that will be overwritten on the next call.
  1200. * Action describes the operation that got the error.
  1201. */
  1202. static const char *
  1203. errmsg(int e, const char *em)
  1204. {
  1205. if (e == ENOENT || e == ENOTDIR) {
  1206. return em;
  1207. }
  1208. return strerror(e);
  1209. }
  1210. /* ============ Memory allocation */
  1211. #if 0
  1212. /* I consider these wrappers nearly useless:
  1213. * ok, they return you to nearest exception handler, but
  1214. * how much memory do you leak in the process, making
  1215. * memory starvation worse?
  1216. */
  1217. static void *
  1218. ckrealloc(void * p, size_t nbytes)
  1219. {
  1220. p = realloc(p, nbytes);
  1221. if (!p)
  1222. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1223. return p;
  1224. }
  1225. static void *
  1226. ckmalloc(size_t nbytes)
  1227. {
  1228. return ckrealloc(NULL, nbytes);
  1229. }
  1230. static void *
  1231. ckzalloc(size_t nbytes)
  1232. {
  1233. return memset(ckmalloc(nbytes), 0, nbytes);
  1234. }
  1235. static char *
  1236. ckstrdup(const char *s)
  1237. {
  1238. char *p = strdup(s);
  1239. if (!p)
  1240. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1241. return p;
  1242. }
  1243. #else
  1244. /* Using bbox equivalents. They exit if out of memory */
  1245. # define ckrealloc xrealloc
  1246. # define ckmalloc xmalloc
  1247. # define ckzalloc xzalloc
  1248. # define ckstrdup xstrdup
  1249. #endif
  1250. /*
  1251. * It appears that grabstackstr() will barf with such alignments
  1252. * because stalloc() will return a string allocated in a new stackblock.
  1253. */
  1254. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1255. enum {
  1256. /* Most machines require the value returned from malloc to be aligned
  1257. * in some way. The following macro will get this right
  1258. * on many machines. */
  1259. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1260. /* Minimum size of a block */
  1261. MINSIZE = SHELL_ALIGN(504),
  1262. };
  1263. struct stack_block {
  1264. struct stack_block *prev;
  1265. char space[MINSIZE];
  1266. };
  1267. struct stackmark {
  1268. struct stack_block *stackp;
  1269. char *stacknxt;
  1270. size_t stacknleft;
  1271. };
  1272. struct globals_memstack {
  1273. struct stack_block *g_stackp; // = &stackbase;
  1274. char *g_stacknxt; // = stackbase.space;
  1275. char *sstrend; // = stackbase.space + MINSIZE;
  1276. size_t g_stacknleft; // = MINSIZE;
  1277. struct stack_block stackbase;
  1278. };
  1279. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1280. #define G_memstack (*ash_ptr_to_globals_memstack)
  1281. #define g_stackp (G_memstack.g_stackp )
  1282. #define g_stacknxt (G_memstack.g_stacknxt )
  1283. #define sstrend (G_memstack.sstrend )
  1284. #define g_stacknleft (G_memstack.g_stacknleft)
  1285. #define stackbase (G_memstack.stackbase )
  1286. #define INIT_G_memstack() do { \
  1287. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1288. barrier(); \
  1289. g_stackp = &stackbase; \
  1290. g_stacknxt = stackbase.space; \
  1291. g_stacknleft = MINSIZE; \
  1292. sstrend = stackbase.space + MINSIZE; \
  1293. } while (0)
  1294. #define stackblock() ((void *)g_stacknxt)
  1295. #define stackblocksize() g_stacknleft
  1296. /*
  1297. * Parse trees for commands are allocated in lifo order, so we use a stack
  1298. * to make this more efficient, and also to avoid all sorts of exception
  1299. * handling code to handle interrupts in the middle of a parse.
  1300. *
  1301. * The size 504 was chosen because the Ultrix malloc handles that size
  1302. * well.
  1303. */
  1304. static void *
  1305. stalloc(size_t nbytes)
  1306. {
  1307. char *p;
  1308. size_t aligned;
  1309. aligned = SHELL_ALIGN(nbytes);
  1310. if (aligned > g_stacknleft) {
  1311. size_t len;
  1312. size_t blocksize;
  1313. struct stack_block *sp;
  1314. blocksize = aligned;
  1315. if (blocksize < MINSIZE)
  1316. blocksize = MINSIZE;
  1317. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1318. if (len < blocksize)
  1319. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1320. INT_OFF;
  1321. sp = ckmalloc(len);
  1322. sp->prev = g_stackp;
  1323. g_stacknxt = sp->space;
  1324. g_stacknleft = blocksize;
  1325. sstrend = g_stacknxt + blocksize;
  1326. g_stackp = sp;
  1327. INT_ON;
  1328. }
  1329. p = g_stacknxt;
  1330. g_stacknxt += aligned;
  1331. g_stacknleft -= aligned;
  1332. return p;
  1333. }
  1334. static void *
  1335. stzalloc(size_t nbytes)
  1336. {
  1337. return memset(stalloc(nbytes), 0, nbytes);
  1338. }
  1339. static void
  1340. stunalloc(void *p)
  1341. {
  1342. #if DEBUG
  1343. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1344. write(STDERR_FILENO, "stunalloc\n", 10);
  1345. abort();
  1346. }
  1347. #endif
  1348. g_stacknleft += g_stacknxt - (char *)p;
  1349. g_stacknxt = p;
  1350. }
  1351. /*
  1352. * Like strdup but works with the ash stack.
  1353. */
  1354. static char *
  1355. sstrdup(const char *p)
  1356. {
  1357. size_t len = strlen(p) + 1;
  1358. return memcpy(stalloc(len), p, len);
  1359. }
  1360. static inline void
  1361. grabstackblock(size_t len)
  1362. {
  1363. stalloc(len);
  1364. }
  1365. static void
  1366. pushstackmark(struct stackmark *mark, size_t len)
  1367. {
  1368. mark->stackp = g_stackp;
  1369. mark->stacknxt = g_stacknxt;
  1370. mark->stacknleft = g_stacknleft;
  1371. grabstackblock(len);
  1372. }
  1373. static void
  1374. setstackmark(struct stackmark *mark)
  1375. {
  1376. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1377. }
  1378. static void
  1379. popstackmark(struct stackmark *mark)
  1380. {
  1381. struct stack_block *sp;
  1382. if (!mark->stackp)
  1383. return;
  1384. INT_OFF;
  1385. while (g_stackp != mark->stackp) {
  1386. sp = g_stackp;
  1387. g_stackp = sp->prev;
  1388. free(sp);
  1389. }
  1390. g_stacknxt = mark->stacknxt;
  1391. g_stacknleft = mark->stacknleft;
  1392. sstrend = mark->stacknxt + mark->stacknleft;
  1393. INT_ON;
  1394. }
  1395. /*
  1396. * When the parser reads in a string, it wants to stick the string on the
  1397. * stack and only adjust the stack pointer when it knows how big the
  1398. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1399. * of space on top of the stack and stackblocklen returns the length of
  1400. * this block. Growstackblock will grow this space by at least one byte,
  1401. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1402. * part of the block that has been used.
  1403. */
  1404. static void
  1405. growstackblock(void)
  1406. {
  1407. size_t newlen;
  1408. newlen = g_stacknleft * 2;
  1409. if (newlen < g_stacknleft)
  1410. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1411. if (newlen < 128)
  1412. newlen += 128;
  1413. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1414. struct stack_block *sp;
  1415. struct stack_block *prevstackp;
  1416. size_t grosslen;
  1417. INT_OFF;
  1418. sp = g_stackp;
  1419. prevstackp = sp->prev;
  1420. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1421. sp = ckrealloc(sp, grosslen);
  1422. sp->prev = prevstackp;
  1423. g_stackp = sp;
  1424. g_stacknxt = sp->space;
  1425. g_stacknleft = newlen;
  1426. sstrend = sp->space + newlen;
  1427. INT_ON;
  1428. } else {
  1429. char *oldspace = g_stacknxt;
  1430. size_t oldlen = g_stacknleft;
  1431. char *p = stalloc(newlen);
  1432. /* free the space we just allocated */
  1433. g_stacknxt = memcpy(p, oldspace, oldlen);
  1434. g_stacknleft += newlen;
  1435. }
  1436. }
  1437. /*
  1438. * The following routines are somewhat easier to use than the above.
  1439. * The user declares a variable of type STACKSTR, which may be declared
  1440. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1441. * the user uses the macro STPUTC to add characters to the string. In
  1442. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1443. * grown as necessary. When the user is done, she can just leave the
  1444. * string there and refer to it using stackblock(). Or she can allocate
  1445. * the space for it using grabstackstr(). If it is necessary to allow
  1446. * someone else to use the stack temporarily and then continue to grow
  1447. * the string, the user should use grabstack to allocate the space, and
  1448. * then call ungrabstr(p) to return to the previous mode of operation.
  1449. *
  1450. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1451. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1452. * is space for at least one character.
  1453. */
  1454. static void *
  1455. growstackstr(void)
  1456. {
  1457. size_t len = stackblocksize();
  1458. growstackblock();
  1459. return (char *)stackblock() + len;
  1460. }
  1461. /*
  1462. * Called from CHECKSTRSPACE.
  1463. */
  1464. static char *
  1465. makestrspace(size_t newlen, char *p)
  1466. {
  1467. size_t len = p - g_stacknxt;
  1468. size_t size;
  1469. for (;;) {
  1470. size_t nleft;
  1471. size = stackblocksize();
  1472. nleft = size - len;
  1473. if (nleft >= newlen)
  1474. break;
  1475. growstackblock();
  1476. }
  1477. return (char *)stackblock() + len;
  1478. }
  1479. static char *
  1480. stack_nputstr(const char *s, size_t n, char *p)
  1481. {
  1482. p = makestrspace(n, p);
  1483. p = (char *)memcpy(p, s, n) + n;
  1484. return p;
  1485. }
  1486. static char *
  1487. stack_putstr(const char *s, char *p)
  1488. {
  1489. return stack_nputstr(s, strlen(s), p);
  1490. }
  1491. static char *
  1492. _STPUTC(int c, char *p)
  1493. {
  1494. if (p == sstrend)
  1495. p = growstackstr();
  1496. *p++ = c;
  1497. return p;
  1498. }
  1499. #define STARTSTACKSTR(p) ((p) = stackblock())
  1500. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1501. #define CHECKSTRSPACE(n, p) do { \
  1502. char *q = (p); \
  1503. size_t l = (n); \
  1504. size_t m = sstrend - q; \
  1505. if (l > m) \
  1506. (p) = makestrspace(l, q); \
  1507. } while (0)
  1508. #define USTPUTC(c, p) (*(p)++ = (c))
  1509. #define STACKSTRNUL(p) do { \
  1510. if ((p) == sstrend) \
  1511. (p) = growstackstr(); \
  1512. *(p) = '\0'; \
  1513. } while (0)
  1514. #define STUNPUTC(p) (--(p))
  1515. #define STTOPC(p) ((p)[-1])
  1516. #define STADJUST(amount, p) ((p) += (amount))
  1517. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1518. #define ungrabstackstr(s, p) stunalloc(s)
  1519. #define stackstrend() ((void *)sstrend)
  1520. /* ============ String helpers */
  1521. /*
  1522. * prefix -- see if pfx is a prefix of string.
  1523. */
  1524. static char *
  1525. prefix(const char *string, const char *pfx)
  1526. {
  1527. while (*pfx) {
  1528. if (*pfx++ != *string++)
  1529. return NULL;
  1530. }
  1531. return (char *) string;
  1532. }
  1533. /*
  1534. * Check for a valid number. This should be elsewhere.
  1535. */
  1536. static int
  1537. is_number(const char *p)
  1538. {
  1539. do {
  1540. if (!isdigit(*p))
  1541. return 0;
  1542. } while (*++p != '\0');
  1543. return 1;
  1544. }
  1545. /*
  1546. * Convert a string of digits to an integer, printing an error message on
  1547. * failure.
  1548. */
  1549. static int
  1550. number(const char *s)
  1551. {
  1552. if (!is_number(s))
  1553. ash_msg_and_raise_error(msg_illnum, s);
  1554. return atoi(s);
  1555. }
  1556. /*
  1557. * Produce a possibly single quoted string suitable as input to the shell.
  1558. * The return string is allocated on the stack.
  1559. */
  1560. static char *
  1561. single_quote(const char *s)
  1562. {
  1563. char *p;
  1564. STARTSTACKSTR(p);
  1565. do {
  1566. char *q;
  1567. size_t len;
  1568. len = strchrnul(s, '\'') - s;
  1569. q = p = makestrspace(len + 3, p);
  1570. *q++ = '\'';
  1571. q = (char *)memcpy(q, s, len) + len;
  1572. *q++ = '\'';
  1573. s += len;
  1574. STADJUST(q - p, p);
  1575. if (*s != '\'')
  1576. break;
  1577. len = 0;
  1578. do len++; while (*++s == '\'');
  1579. q = p = makestrspace(len + 3, p);
  1580. *q++ = '"';
  1581. q = (char *)memcpy(q, s - len, len) + len;
  1582. *q++ = '"';
  1583. STADJUST(q - p, p);
  1584. } while (*s);
  1585. USTPUTC('\0', p);
  1586. return stackblock();
  1587. }
  1588. /* ============ nextopt */
  1589. static char **argptr; /* argument list for builtin commands */
  1590. static char *optionarg; /* set by nextopt (like getopt) */
  1591. static char *optptr; /* used by nextopt */
  1592. /*
  1593. * XXX - should get rid of. Have all builtins use getopt(3).
  1594. * The library getopt must have the BSD extension static variable
  1595. * "optreset", otherwise it can't be used within the shell safely.
  1596. *
  1597. * Standard option processing (a la getopt) for builtin routines.
  1598. * The only argument that is passed to nextopt is the option string;
  1599. * the other arguments are unnecessary. It returns the character,
  1600. * or '\0' on end of input.
  1601. */
  1602. static int
  1603. nextopt(const char *optstring)
  1604. {
  1605. char *p;
  1606. const char *q;
  1607. char c;
  1608. p = optptr;
  1609. if (p == NULL || *p == '\0') {
  1610. /* We ate entire "-param", take next one */
  1611. p = *argptr;
  1612. if (p == NULL)
  1613. return '\0';
  1614. if (*p != '-')
  1615. return '\0';
  1616. if (*++p == '\0') /* just "-" ? */
  1617. return '\0';
  1618. argptr++;
  1619. if (LONE_DASH(p)) /* "--" ? */
  1620. return '\0';
  1621. /* p => next "-param" */
  1622. }
  1623. /* p => some option char in the middle of a "-param" */
  1624. c = *p++;
  1625. for (q = optstring; *q != c;) {
  1626. if (*q == '\0')
  1627. ash_msg_and_raise_error("illegal option -%c", c);
  1628. if (*++q == ':')
  1629. q++;
  1630. }
  1631. if (*++q == ':') {
  1632. if (*p == '\0') {
  1633. p = *argptr++;
  1634. if (p == NULL)
  1635. ash_msg_and_raise_error("no arg for -%c option", c);
  1636. }
  1637. optionarg = p;
  1638. p = NULL;
  1639. }
  1640. optptr = p;
  1641. return c;
  1642. }
  1643. /* ============ Shell variables */
  1644. /*
  1645. * The parsefile structure pointed to by the global variable parsefile
  1646. * contains information about the current file being read.
  1647. */
  1648. struct shparam {
  1649. int nparam; /* # of positional parameters (without $0) */
  1650. #if ENABLE_ASH_GETOPTS
  1651. int optind; /* next parameter to be processed by getopts */
  1652. int optoff; /* used by getopts */
  1653. #endif
  1654. unsigned char malloced; /* if parameter list dynamically allocated */
  1655. char **p; /* parameter list */
  1656. };
  1657. /*
  1658. * Free the list of positional parameters.
  1659. */
  1660. static void
  1661. freeparam(volatile struct shparam *param)
  1662. {
  1663. if (param->malloced) {
  1664. char **ap, **ap1;
  1665. ap = ap1 = param->p;
  1666. while (*ap)
  1667. free(*ap++);
  1668. free(ap1);
  1669. }
  1670. }
  1671. #if ENABLE_ASH_GETOPTS
  1672. static void FAST_FUNC getoptsreset(const char *value);
  1673. #endif
  1674. struct var {
  1675. struct var *next; /* next entry in hash list */
  1676. int flags; /* flags are defined above */
  1677. const char *var_text; /* name=value */
  1678. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1679. /* the variable gets set/unset */
  1680. };
  1681. struct localvar {
  1682. struct localvar *next; /* next local variable in list */
  1683. struct var *vp; /* the variable that was made local */
  1684. int flags; /* saved flags */
  1685. const char *text; /* saved text */
  1686. };
  1687. /* flags */
  1688. #define VEXPORT 0x01 /* variable is exported */
  1689. #define VREADONLY 0x02 /* variable cannot be modified */
  1690. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1691. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1692. #define VSTACK 0x10 /* text is allocated on the stack */
  1693. #define VUNSET 0x20 /* the variable is not set */
  1694. #define VNOFUNC 0x40 /* don't call the callback function */
  1695. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1696. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1697. #if ENABLE_ASH_RANDOM_SUPPORT
  1698. # define VDYNAMIC 0x200 /* dynamic variable */
  1699. #else
  1700. # define VDYNAMIC 0
  1701. #endif
  1702. /* Need to be before varinit_data[] */
  1703. #if ENABLE_LOCALE_SUPPORT
  1704. static void FAST_FUNC
  1705. change_lc_all(const char *value)
  1706. {
  1707. if (value && *value != '\0')
  1708. setlocale(LC_ALL, value);
  1709. }
  1710. static void FAST_FUNC
  1711. change_lc_ctype(const char *value)
  1712. {
  1713. if (value && *value != '\0')
  1714. setlocale(LC_CTYPE, value);
  1715. }
  1716. #endif
  1717. #if ENABLE_ASH_MAIL
  1718. static void chkmail(void);
  1719. static void changemail(const char *var_value) FAST_FUNC;
  1720. #else
  1721. # define chkmail() ((void)0)
  1722. #endif
  1723. static void changepath(const char *) FAST_FUNC;
  1724. #if ENABLE_ASH_RANDOM_SUPPORT
  1725. static void change_random(const char *) FAST_FUNC;
  1726. #endif
  1727. static const struct {
  1728. int flags;
  1729. const char *var_text;
  1730. void (*var_func)(const char *) FAST_FUNC;
  1731. } varinit_data[] = {
  1732. /*
  1733. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1734. * some environment strings may be constant.
  1735. */
  1736. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1737. #if ENABLE_ASH_MAIL
  1738. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1739. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1740. #endif
  1741. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1742. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1743. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1744. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1745. #if ENABLE_ASH_GETOPTS
  1746. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1747. #endif
  1748. #if ENABLE_ASH_RANDOM_SUPPORT
  1749. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1750. #endif
  1751. #if ENABLE_LOCALE_SUPPORT
  1752. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1753. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1754. #endif
  1755. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1756. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1757. #endif
  1758. };
  1759. struct redirtab;
  1760. struct globals_var {
  1761. struct shparam shellparam; /* $@ current positional parameters */
  1762. struct redirtab *redirlist;
  1763. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1764. struct var *vartab[VTABSIZE];
  1765. struct var varinit[ARRAY_SIZE(varinit_data)];
  1766. };
  1767. extern struct globals_var *const ash_ptr_to_globals_var;
  1768. #define G_var (*ash_ptr_to_globals_var)
  1769. #define shellparam (G_var.shellparam )
  1770. //#define redirlist (G_var.redirlist )
  1771. #define preverrout_fd (G_var.preverrout_fd)
  1772. #define vartab (G_var.vartab )
  1773. #define varinit (G_var.varinit )
  1774. #define INIT_G_var() do { \
  1775. unsigned i; \
  1776. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1777. barrier(); \
  1778. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1779. varinit[i].flags = varinit_data[i].flags; \
  1780. varinit[i].var_text = varinit_data[i].var_text; \
  1781. varinit[i].var_func = varinit_data[i].var_func; \
  1782. } \
  1783. } while (0)
  1784. #define vifs varinit[0]
  1785. #if ENABLE_ASH_MAIL
  1786. # define vmail (&vifs)[1]
  1787. # define vmpath (&vmail)[1]
  1788. # define vpath (&vmpath)[1]
  1789. #else
  1790. # define vpath (&vifs)[1]
  1791. #endif
  1792. #define vps1 (&vpath)[1]
  1793. #define vps2 (&vps1)[1]
  1794. #define vps4 (&vps2)[1]
  1795. #if ENABLE_ASH_GETOPTS
  1796. # define voptind (&vps4)[1]
  1797. # if ENABLE_ASH_RANDOM_SUPPORT
  1798. # define vrandom (&voptind)[1]
  1799. # endif
  1800. #else
  1801. # if ENABLE_ASH_RANDOM_SUPPORT
  1802. # define vrandom (&vps4)[1]
  1803. # endif
  1804. #endif
  1805. /*
  1806. * The following macros access the values of the above variables.
  1807. * They have to skip over the name. They return the null string
  1808. * for unset variables.
  1809. */
  1810. #define ifsval() (vifs.var_text + 4)
  1811. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1812. #if ENABLE_ASH_MAIL
  1813. # define mailval() (vmail.var_text + 5)
  1814. # define mpathval() (vmpath.var_text + 9)
  1815. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1816. #endif
  1817. #define pathval() (vpath.var_text + 5)
  1818. #define ps1val() (vps1.var_text + 4)
  1819. #define ps2val() (vps2.var_text + 4)
  1820. #define ps4val() (vps4.var_text + 4)
  1821. #if ENABLE_ASH_GETOPTS
  1822. # define optindval() (voptind.var_text + 7)
  1823. #endif
  1824. #if ENABLE_ASH_GETOPTS
  1825. static void FAST_FUNC
  1826. getoptsreset(const char *value)
  1827. {
  1828. shellparam.optind = number(value) ?: 1;
  1829. shellparam.optoff = -1;
  1830. }
  1831. #endif
  1832. /*
  1833. * Compares two strings up to the first = or '\0'. The first
  1834. * string must be terminated by '='; the second may be terminated by
  1835. * either '=' or '\0'.
  1836. */
  1837. static int
  1838. varcmp(const char *p, const char *q)
  1839. {
  1840. int c, d;
  1841. while ((c = *p) == (d = *q)) {
  1842. if (c == '\0' || c == '=')
  1843. goto out;
  1844. p++;
  1845. q++;
  1846. }
  1847. if (c == '=')
  1848. c = '\0';
  1849. if (d == '=')
  1850. d = '\0';
  1851. out:
  1852. return c - d;
  1853. }
  1854. /*
  1855. * Find the appropriate entry in the hash table from the name.
  1856. */
  1857. static struct var **
  1858. hashvar(const char *p)
  1859. {
  1860. unsigned hashval;
  1861. hashval = ((unsigned char) *p) << 4;
  1862. while (*p && *p != '=')
  1863. hashval += (unsigned char) *p++;
  1864. return &vartab[hashval % VTABSIZE];
  1865. }
  1866. static int
  1867. vpcmp(const void *a, const void *b)
  1868. {
  1869. return varcmp(*(const char **)a, *(const char **)b);
  1870. }
  1871. /*
  1872. * This routine initializes the builtin variables.
  1873. */
  1874. static void
  1875. initvar(void)
  1876. {
  1877. struct var *vp;
  1878. struct var *end;
  1879. struct var **vpp;
  1880. /*
  1881. * PS1 depends on uid
  1882. */
  1883. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1884. vps1.var_text = "PS1=\\w \\$ ";
  1885. #else
  1886. if (!geteuid())
  1887. vps1.var_text = "PS1=# ";
  1888. #endif
  1889. vp = varinit;
  1890. end = vp + ARRAY_SIZE(varinit);
  1891. do {
  1892. vpp = hashvar(vp->var_text);
  1893. vp->next = *vpp;
  1894. *vpp = vp;
  1895. } while (++vp < end);
  1896. }
  1897. static struct var **
  1898. findvar(struct var **vpp, const char *name)
  1899. {
  1900. for (; *vpp; vpp = &(*vpp)->next) {
  1901. if (varcmp((*vpp)->var_text, name) == 0) {
  1902. break;
  1903. }
  1904. }
  1905. return vpp;
  1906. }
  1907. /*
  1908. * Find the value of a variable. Returns NULL if not set.
  1909. */
  1910. static const char* FAST_FUNC
  1911. lookupvar(const char *name)
  1912. {
  1913. struct var *v;
  1914. v = *findvar(hashvar(name), name);
  1915. if (v) {
  1916. #if ENABLE_ASH_RANDOM_SUPPORT
  1917. /*
  1918. * Dynamic variables are implemented roughly the same way they are
  1919. * in bash. Namely, they're "special" so long as they aren't unset.
  1920. * As soon as they're unset, they're no longer dynamic, and dynamic
  1921. * lookup will no longer happen at that point. -- PFM.
  1922. */
  1923. if (v->flags & VDYNAMIC)
  1924. v->var_func(NULL);
  1925. #endif
  1926. if (!(v->flags & VUNSET))
  1927. return var_end(v->var_text);
  1928. }
  1929. return NULL;
  1930. }
  1931. #if ENABLE_UNICODE_SUPPORT
  1932. static void
  1933. reinit_unicode_for_ash(void)
  1934. {
  1935. /* Unicode support should be activated even if LANG is set
  1936. * _during_ shell execution, not only if it was set when
  1937. * shell was started. Therefore, re-check LANG every time:
  1938. */
  1939. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1940. || ENABLE_UNICODE_USING_LOCALE
  1941. ) {
  1942. const char *s = lookupvar("LC_ALL");
  1943. if (!s) s = lookupvar("LC_CTYPE");
  1944. if (!s) s = lookupvar("LANG");
  1945. reinit_unicode(s);
  1946. }
  1947. }
  1948. #else
  1949. # define reinit_unicode_for_ash() ((void)0)
  1950. #endif
  1951. /*
  1952. * Search the environment of a builtin command.
  1953. */
  1954. static const char *
  1955. bltinlookup(const char *name)
  1956. {
  1957. struct strlist *sp;
  1958. for (sp = cmdenviron; sp; sp = sp->next) {
  1959. if (varcmp(sp->text, name) == 0)
  1960. return var_end(sp->text);
  1961. }
  1962. return lookupvar(name);
  1963. }
  1964. /*
  1965. * Same as setvar except that the variable and value are passed in
  1966. * the first argument as name=value. Since the first argument will
  1967. * be actually stored in the table, it should not be a string that
  1968. * will go away.
  1969. * Called with interrupts off.
  1970. */
  1971. static void
  1972. setvareq(char *s, int flags)
  1973. {
  1974. struct var *vp, **vpp;
  1975. vpp = hashvar(s);
  1976. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1977. vp = *findvar(vpp, s);
  1978. if (vp) {
  1979. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1980. const char *n;
  1981. if (flags & VNOSAVE)
  1982. free(s);
  1983. n = vp->var_text;
  1984. exitstatus = 1;
  1985. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1986. }
  1987. if (flags & VNOSET)
  1988. return;
  1989. if (vp->var_func && !(flags & VNOFUNC))
  1990. vp->var_func(var_end(s));
  1991. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  1992. free((char*)vp->var_text);
  1993. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1994. } else {
  1995. /* variable s is not found */
  1996. if (flags & VNOSET)
  1997. return;
  1998. vp = ckzalloc(sizeof(*vp));
  1999. vp->next = *vpp;
  2000. /*vp->func = NULL; - ckzalloc did it */
  2001. *vpp = vp;
  2002. }
  2003. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2004. s = ckstrdup(s);
  2005. vp->var_text = s;
  2006. vp->flags = flags;
  2007. }
  2008. /*
  2009. * Set the value of a variable. The flags argument is ored with the
  2010. * flags of the variable. If val is NULL, the variable is unset.
  2011. */
  2012. static void
  2013. setvar(const char *name, const char *val, int flags)
  2014. {
  2015. const char *q;
  2016. char *p;
  2017. char *nameeq;
  2018. size_t namelen;
  2019. size_t vallen;
  2020. q = endofname(name);
  2021. p = strchrnul(q, '=');
  2022. namelen = p - name;
  2023. if (!namelen || p != q)
  2024. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2025. vallen = 0;
  2026. if (val == NULL) {
  2027. flags |= VUNSET;
  2028. } else {
  2029. vallen = strlen(val);
  2030. }
  2031. INT_OFF;
  2032. nameeq = ckmalloc(namelen + vallen + 2);
  2033. p = memcpy(nameeq, name, namelen) + namelen;
  2034. if (val) {
  2035. *p++ = '=';
  2036. p = memcpy(p, val, vallen) + vallen;
  2037. }
  2038. *p = '\0';
  2039. setvareq(nameeq, flags | VNOSAVE);
  2040. INT_ON;
  2041. }
  2042. static void FAST_FUNC
  2043. setvar0(const char *name, const char *val)
  2044. {
  2045. setvar(name, val, 0);
  2046. }
  2047. /*
  2048. * Unset the specified variable.
  2049. */
  2050. static int
  2051. unsetvar(const char *s)
  2052. {
  2053. struct var **vpp;
  2054. struct var *vp;
  2055. int retval;
  2056. vpp = findvar(hashvar(s), s);
  2057. vp = *vpp;
  2058. retval = 2;
  2059. if (vp) {
  2060. int flags = vp->flags;
  2061. retval = 1;
  2062. if (flags & VREADONLY)
  2063. goto out;
  2064. #if ENABLE_ASH_RANDOM_SUPPORT
  2065. vp->flags &= ~VDYNAMIC;
  2066. #endif
  2067. if (flags & VUNSET)
  2068. goto ok;
  2069. if ((flags & VSTRFIXED) == 0) {
  2070. INT_OFF;
  2071. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  2072. free((char*)vp->var_text);
  2073. *vpp = vp->next;
  2074. free(vp);
  2075. INT_ON;
  2076. } else {
  2077. setvar0(s, NULL);
  2078. vp->flags &= ~VEXPORT;
  2079. }
  2080. ok:
  2081. retval = 0;
  2082. }
  2083. out:
  2084. return retval;
  2085. }
  2086. /*
  2087. * Process a linked list of variable assignments.
  2088. */
  2089. static void
  2090. listsetvar(struct strlist *list_set_var, int flags)
  2091. {
  2092. struct strlist *lp = list_set_var;
  2093. if (!lp)
  2094. return;
  2095. INT_OFF;
  2096. do {
  2097. setvareq(lp->text, flags);
  2098. lp = lp->next;
  2099. } while (lp);
  2100. INT_ON;
  2101. }
  2102. /*
  2103. * Generate a list of variables satisfying the given conditions.
  2104. */
  2105. static char **
  2106. listvars(int on, int off, char ***end)
  2107. {
  2108. struct var **vpp;
  2109. struct var *vp;
  2110. char **ep;
  2111. int mask;
  2112. STARTSTACKSTR(ep);
  2113. vpp = vartab;
  2114. mask = on | off;
  2115. do {
  2116. for (vp = *vpp; vp; vp = vp->next) {
  2117. if ((vp->flags & mask) == on) {
  2118. if (ep == stackstrend())
  2119. ep = growstackstr();
  2120. *ep++ = (char*)vp->var_text;
  2121. }
  2122. }
  2123. } while (++vpp < vartab + VTABSIZE);
  2124. if (ep == stackstrend())
  2125. ep = growstackstr();
  2126. if (end)
  2127. *end = ep;
  2128. *ep++ = NULL;
  2129. return grabstackstr(ep);
  2130. }
  2131. /* ============ Path search helper
  2132. *
  2133. * The variable path (passed by reference) should be set to the start
  2134. * of the path before the first call; path_advance will update
  2135. * this value as it proceeds. Successive calls to path_advance will return
  2136. * the possible path expansions in sequence. If an option (indicated by
  2137. * a percent sign) appears in the path entry then the global variable
  2138. * pathopt will be set to point to it; otherwise pathopt will be set to
  2139. * NULL.
  2140. */
  2141. static const char *pathopt; /* set by path_advance */
  2142. static char *
  2143. path_advance(const char **path, const char *name)
  2144. {
  2145. const char *p;
  2146. char *q;
  2147. const char *start;
  2148. size_t len;
  2149. if (*path == NULL)
  2150. return NULL;
  2151. start = *path;
  2152. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2153. continue;
  2154. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2155. while (stackblocksize() < len)
  2156. growstackblock();
  2157. q = stackblock();
  2158. if (p != start) {
  2159. memcpy(q, start, p - start);
  2160. q += p - start;
  2161. *q++ = '/';
  2162. }
  2163. strcpy(q, name);
  2164. pathopt = NULL;
  2165. if (*p == '%') {
  2166. pathopt = ++p;
  2167. while (*p && *p != ':')
  2168. p++;
  2169. }
  2170. if (*p == ':')
  2171. *path = p + 1;
  2172. else
  2173. *path = NULL;
  2174. return stalloc(len);
  2175. }
  2176. /* ============ Prompt */
  2177. static smallint doprompt; /* if set, prompt the user */
  2178. static smallint needprompt; /* true if interactive and at start of line */
  2179. #if ENABLE_FEATURE_EDITING
  2180. static line_input_t *line_input_state;
  2181. static const char *cmdedit_prompt;
  2182. static void
  2183. putprompt(const char *s)
  2184. {
  2185. if (ENABLE_ASH_EXPAND_PRMT) {
  2186. free((char*)cmdedit_prompt);
  2187. cmdedit_prompt = ckstrdup(s);
  2188. return;
  2189. }
  2190. cmdedit_prompt = s;
  2191. }
  2192. #else
  2193. static void
  2194. putprompt(const char *s)
  2195. {
  2196. out2str(s);
  2197. }
  2198. #endif
  2199. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2200. static const char *expandstr(const char *ps);
  2201. static void
  2202. setprompt_if(smallint do_set, int whichprompt)
  2203. {
  2204. const char *prompt;
  2205. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2206. if (!do_set)
  2207. return;
  2208. needprompt = 0;
  2209. switch (whichprompt) {
  2210. case 1:
  2211. prompt = ps1val();
  2212. break;
  2213. case 2:
  2214. prompt = ps2val();
  2215. break;
  2216. default: /* 0 */
  2217. prompt = nullstr;
  2218. }
  2219. #if ENABLE_ASH_EXPAND_PRMT
  2220. pushstackmark(&smark, stackblocksize());
  2221. putprompt(expandstr(prompt));
  2222. popstackmark(&smark);
  2223. #else
  2224. putprompt(prompt);
  2225. #endif
  2226. }
  2227. /* ============ The cd and pwd commands */
  2228. #define CD_PHYSICAL 1
  2229. #define CD_PRINT 2
  2230. static int
  2231. cdopt(void)
  2232. {
  2233. int flags = 0;
  2234. int i, j;
  2235. j = 'L';
  2236. while ((i = nextopt("LP")) != '\0') {
  2237. if (i != j) {
  2238. flags ^= CD_PHYSICAL;
  2239. j = i;
  2240. }
  2241. }
  2242. return flags;
  2243. }
  2244. /*
  2245. * Update curdir (the name of the current directory) in response to a
  2246. * cd command.
  2247. */
  2248. static const char *
  2249. updatepwd(const char *dir)
  2250. {
  2251. char *new;
  2252. char *p;
  2253. char *cdcomppath;
  2254. const char *lim;
  2255. cdcomppath = sstrdup(dir);
  2256. STARTSTACKSTR(new);
  2257. if (*dir != '/') {
  2258. if (curdir == nullstr)
  2259. return 0;
  2260. new = stack_putstr(curdir, new);
  2261. }
  2262. new = makestrspace(strlen(dir) + 2, new);
  2263. lim = (char *)stackblock() + 1;
  2264. if (*dir != '/') {
  2265. if (new[-1] != '/')
  2266. USTPUTC('/', new);
  2267. if (new > lim && *lim == '/')
  2268. lim++;
  2269. } else {
  2270. USTPUTC('/', new);
  2271. cdcomppath++;
  2272. if (dir[1] == '/' && dir[2] != '/') {
  2273. USTPUTC('/', new);
  2274. cdcomppath++;
  2275. lim++;
  2276. }
  2277. }
  2278. p = strtok(cdcomppath, "/");
  2279. while (p) {
  2280. switch (*p) {
  2281. case '.':
  2282. if (p[1] == '.' && p[2] == '\0') {
  2283. while (new > lim) {
  2284. STUNPUTC(new);
  2285. if (new[-1] == '/')
  2286. break;
  2287. }
  2288. break;
  2289. }
  2290. if (p[1] == '\0')
  2291. break;
  2292. /* fall through */
  2293. default:
  2294. new = stack_putstr(p, new);
  2295. USTPUTC('/', new);
  2296. }
  2297. p = strtok(NULL, "/");
  2298. }
  2299. if (new > lim)
  2300. STUNPUTC(new);
  2301. *new = 0;
  2302. return stackblock();
  2303. }
  2304. /*
  2305. * Find out what the current directory is. If we already know the current
  2306. * directory, this routine returns immediately.
  2307. */
  2308. static char *
  2309. getpwd(void)
  2310. {
  2311. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2312. return dir ? dir : nullstr;
  2313. }
  2314. static void
  2315. setpwd(const char *val, int setold)
  2316. {
  2317. char *oldcur, *dir;
  2318. oldcur = dir = curdir;
  2319. if (setold) {
  2320. setvar("OLDPWD", oldcur, VEXPORT);
  2321. }
  2322. INT_OFF;
  2323. if (physdir != nullstr) {
  2324. if (physdir != oldcur)
  2325. free(physdir);
  2326. physdir = nullstr;
  2327. }
  2328. if (oldcur == val || !val) {
  2329. char *s = getpwd();
  2330. physdir = s;
  2331. if (!val)
  2332. dir = s;
  2333. } else
  2334. dir = ckstrdup(val);
  2335. if (oldcur != dir && oldcur != nullstr) {
  2336. free(oldcur);
  2337. }
  2338. curdir = dir;
  2339. INT_ON;
  2340. setvar("PWD", dir, VEXPORT);
  2341. }
  2342. static void hashcd(void);
  2343. /*
  2344. * Actually do the chdir. We also call hashcd to let other routines
  2345. * know that the current directory has changed.
  2346. */
  2347. static int
  2348. docd(const char *dest, int flags)
  2349. {
  2350. const char *dir = NULL;
  2351. int err;
  2352. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2353. INT_OFF;
  2354. if (!(flags & CD_PHYSICAL)) {
  2355. dir = updatepwd(dest);
  2356. if (dir)
  2357. dest = dir;
  2358. }
  2359. err = chdir(dest);
  2360. if (err)
  2361. goto out;
  2362. setpwd(dir, 1);
  2363. hashcd();
  2364. out:
  2365. INT_ON;
  2366. return err;
  2367. }
  2368. static int FAST_FUNC
  2369. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2370. {
  2371. const char *dest;
  2372. const char *path;
  2373. const char *p;
  2374. char c;
  2375. struct stat statb;
  2376. int flags;
  2377. flags = cdopt();
  2378. dest = *argptr;
  2379. if (!dest)
  2380. dest = bltinlookup("HOME");
  2381. else if (LONE_DASH(dest)) {
  2382. dest = bltinlookup("OLDPWD");
  2383. flags |= CD_PRINT;
  2384. }
  2385. if (!dest)
  2386. dest = nullstr;
  2387. if (*dest == '/')
  2388. goto step6;
  2389. if (*dest == '.') {
  2390. c = dest[1];
  2391. dotdot:
  2392. switch (c) {
  2393. case '\0':
  2394. case '/':
  2395. goto step6;
  2396. case '.':
  2397. c = dest[2];
  2398. if (c != '.')
  2399. goto dotdot;
  2400. }
  2401. }
  2402. if (!*dest)
  2403. dest = ".";
  2404. path = bltinlookup("CDPATH");
  2405. while (path) {
  2406. c = *path;
  2407. p = path_advance(&path, dest);
  2408. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2409. if (c && c != ':')
  2410. flags |= CD_PRINT;
  2411. docd:
  2412. if (!docd(p, flags))
  2413. goto out;
  2414. goto err;
  2415. }
  2416. }
  2417. step6:
  2418. p = dest;
  2419. goto docd;
  2420. err:
  2421. ash_msg_and_raise_error("can't cd to %s", dest);
  2422. /* NOTREACHED */
  2423. out:
  2424. if (flags & CD_PRINT)
  2425. out1fmt("%s\n", curdir);
  2426. return 0;
  2427. }
  2428. static int FAST_FUNC
  2429. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2430. {
  2431. int flags;
  2432. const char *dir = curdir;
  2433. flags = cdopt();
  2434. if (flags) {
  2435. if (physdir == nullstr)
  2436. setpwd(dir, 0);
  2437. dir = physdir;
  2438. }
  2439. out1fmt("%s\n", dir);
  2440. return 0;
  2441. }
  2442. /* ============ ... */
  2443. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2444. /* Syntax classes */
  2445. #define CWORD 0 /* character is nothing special */
  2446. #define CNL 1 /* newline character */
  2447. #define CBACK 2 /* a backslash character */
  2448. #define CSQUOTE 3 /* single quote */
  2449. #define CDQUOTE 4 /* double quote */
  2450. #define CENDQUOTE 5 /* a terminating quote */
  2451. #define CBQUOTE 6 /* backwards single quote */
  2452. #define CVAR 7 /* a dollar sign */
  2453. #define CENDVAR 8 /* a '}' character */
  2454. #define CLP 9 /* a left paren in arithmetic */
  2455. #define CRP 10 /* a right paren in arithmetic */
  2456. #define CENDFILE 11 /* end of file */
  2457. #define CCTL 12 /* like CWORD, except it must be escaped */
  2458. #define CSPCL 13 /* these terminate a word */
  2459. #define CIGN 14 /* character should be ignored */
  2460. #define PEOF 256
  2461. #if ENABLE_ASH_ALIAS
  2462. # define PEOA 257
  2463. #endif
  2464. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2465. #if ENABLE_FEATURE_SH_MATH
  2466. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2467. #else
  2468. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2469. #endif
  2470. static const uint16_t S_I_T[] ALIGN2 = {
  2471. #if ENABLE_ASH_ALIAS
  2472. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2473. #endif
  2474. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2475. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2476. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2477. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2478. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2479. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2480. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2481. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2482. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2483. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2484. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2485. #if !USE_SIT_FUNCTION
  2486. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2487. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2488. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2489. #endif
  2490. #undef SIT_ITEM
  2491. };
  2492. /* Constants below must match table above */
  2493. enum {
  2494. #if ENABLE_ASH_ALIAS
  2495. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2496. #endif
  2497. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2498. CNL_CNL_CNL_CNL , /* 2 */
  2499. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2500. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2501. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2502. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2503. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2504. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2505. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2506. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2507. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2508. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2509. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2510. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2511. };
  2512. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2513. * caller must ensure proper cast on it if c is *char_ptr!
  2514. */
  2515. /* Values for syntax param */
  2516. #define BASESYNTAX 0 /* not in quotes */
  2517. #define DQSYNTAX 1 /* in double quotes */
  2518. #define SQSYNTAX 2 /* in single quotes */
  2519. #define ARISYNTAX 3 /* in arithmetic */
  2520. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2521. #if USE_SIT_FUNCTION
  2522. static int
  2523. SIT(int c, int syntax)
  2524. {
  2525. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2526. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2527. /*
  2528. * This causes '/' to be prepended with CTLESC in dquoted string,
  2529. * making "./file"* treated incorrectly because we feed
  2530. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2531. * The "homegrown" glob implementation is okay with that,
  2532. * but glibc one isn't. With '/' always treated as CWORD,
  2533. * both work fine.
  2534. */
  2535. # if ENABLE_ASH_ALIAS
  2536. static const uint8_t syntax_index_table[] ALIGN1 = {
  2537. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2538. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2539. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2540. 11, 3 /* "}~" */
  2541. };
  2542. # else
  2543. static const uint8_t syntax_index_table[] ALIGN1 = {
  2544. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2545. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2546. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2547. 10, 2 /* "}~" */
  2548. };
  2549. # endif
  2550. const char *s;
  2551. int indx;
  2552. if (c == PEOF)
  2553. return CENDFILE;
  2554. # if ENABLE_ASH_ALIAS
  2555. if (c == PEOA)
  2556. indx = 0;
  2557. else
  2558. # endif
  2559. {
  2560. /* Cast is purely for paranoia here,
  2561. * just in case someone passed signed char to us */
  2562. if ((unsigned char)c >= CTL_FIRST
  2563. && (unsigned char)c <= CTL_LAST
  2564. ) {
  2565. return CCTL;
  2566. }
  2567. s = strchrnul(spec_symbls, c);
  2568. if (*s == '\0')
  2569. return CWORD;
  2570. indx = syntax_index_table[s - spec_symbls];
  2571. }
  2572. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2573. }
  2574. #else /* !USE_SIT_FUNCTION */
  2575. static const uint8_t syntax_index_table[] ALIGN1 = {
  2576. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2577. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2587. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2588. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2601. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2602. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2603. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2610. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2611. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2612. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2614. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2616. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2617. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2618. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2619. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2620. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2623. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2624. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2625. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2637. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2638. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2639. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2640. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2641. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2642. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2670. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2671. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2672. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2675. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2693. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2694. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2695. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2696. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2697. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2698. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2703. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2704. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2705. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2708. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2709. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2710. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2711. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2712. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2713. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2714. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2715. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2834. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2835. # if ENABLE_ASH_ALIAS
  2836. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2837. # endif
  2838. };
  2839. #if 1
  2840. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2841. #else /* debug version, caught one signed char bug */
  2842. # define SIT(c, syntax) \
  2843. ({ \
  2844. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2845. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2846. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2847. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2848. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2849. })
  2850. #endif
  2851. #endif /* !USE_SIT_FUNCTION */
  2852. /* ============ Alias handling */
  2853. #if ENABLE_ASH_ALIAS
  2854. #define ALIASINUSE 1
  2855. #define ALIASDEAD 2
  2856. struct alias {
  2857. struct alias *next;
  2858. char *name;
  2859. char *val;
  2860. int flag;
  2861. };
  2862. static struct alias **atab; // [ATABSIZE];
  2863. #define INIT_G_alias() do { \
  2864. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2865. } while (0)
  2866. static struct alias **
  2867. __lookupalias(const char *name)
  2868. {
  2869. unsigned int hashval;
  2870. struct alias **app;
  2871. const char *p;
  2872. unsigned int ch;
  2873. p = name;
  2874. ch = (unsigned char)*p;
  2875. hashval = ch << 4;
  2876. while (ch) {
  2877. hashval += ch;
  2878. ch = (unsigned char)*++p;
  2879. }
  2880. app = &atab[hashval % ATABSIZE];
  2881. for (; *app; app = &(*app)->next) {
  2882. if (strcmp(name, (*app)->name) == 0) {
  2883. break;
  2884. }
  2885. }
  2886. return app;
  2887. }
  2888. static struct alias *
  2889. lookupalias(const char *name, int check)
  2890. {
  2891. struct alias *ap = *__lookupalias(name);
  2892. if (check && ap && (ap->flag & ALIASINUSE))
  2893. return NULL;
  2894. return ap;
  2895. }
  2896. static struct alias *
  2897. freealias(struct alias *ap)
  2898. {
  2899. struct alias *next;
  2900. if (ap->flag & ALIASINUSE) {
  2901. ap->flag |= ALIASDEAD;
  2902. return ap;
  2903. }
  2904. next = ap->next;
  2905. free(ap->name);
  2906. free(ap->val);
  2907. free(ap);
  2908. return next;
  2909. }
  2910. static void
  2911. setalias(const char *name, const char *val)
  2912. {
  2913. struct alias *ap, **app;
  2914. app = __lookupalias(name);
  2915. ap = *app;
  2916. INT_OFF;
  2917. if (ap) {
  2918. if (!(ap->flag & ALIASINUSE)) {
  2919. free(ap->val);
  2920. }
  2921. ap->val = ckstrdup(val);
  2922. ap->flag &= ~ALIASDEAD;
  2923. } else {
  2924. /* not found */
  2925. ap = ckzalloc(sizeof(struct alias));
  2926. ap->name = ckstrdup(name);
  2927. ap->val = ckstrdup(val);
  2928. /*ap->flag = 0; - ckzalloc did it */
  2929. /*ap->next = NULL;*/
  2930. *app = ap;
  2931. }
  2932. INT_ON;
  2933. }
  2934. static int
  2935. unalias(const char *name)
  2936. {
  2937. struct alias **app;
  2938. app = __lookupalias(name);
  2939. if (*app) {
  2940. INT_OFF;
  2941. *app = freealias(*app);
  2942. INT_ON;
  2943. return 0;
  2944. }
  2945. return 1;
  2946. }
  2947. static void
  2948. rmaliases(void)
  2949. {
  2950. struct alias *ap, **app;
  2951. int i;
  2952. INT_OFF;
  2953. for (i = 0; i < ATABSIZE; i++) {
  2954. app = &atab[i];
  2955. for (ap = *app; ap; ap = *app) {
  2956. *app = freealias(*app);
  2957. if (ap == *app) {
  2958. app = &ap->next;
  2959. }
  2960. }
  2961. }
  2962. INT_ON;
  2963. }
  2964. static void
  2965. printalias(const struct alias *ap)
  2966. {
  2967. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2968. }
  2969. /*
  2970. * TODO - sort output
  2971. */
  2972. static int FAST_FUNC
  2973. aliascmd(int argc UNUSED_PARAM, char **argv)
  2974. {
  2975. char *n, *v;
  2976. int ret = 0;
  2977. struct alias *ap;
  2978. if (!argv[1]) {
  2979. int i;
  2980. for (i = 0; i < ATABSIZE; i++) {
  2981. for (ap = atab[i]; ap; ap = ap->next) {
  2982. printalias(ap);
  2983. }
  2984. }
  2985. return 0;
  2986. }
  2987. while ((n = *++argv) != NULL) {
  2988. v = strchr(n+1, '=');
  2989. if (v == NULL) { /* n+1: funny ksh stuff */
  2990. ap = *__lookupalias(n);
  2991. if (ap == NULL) {
  2992. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2993. ret = 1;
  2994. } else
  2995. printalias(ap);
  2996. } else {
  2997. *v++ = '\0';
  2998. setalias(n, v);
  2999. }
  3000. }
  3001. return ret;
  3002. }
  3003. static int FAST_FUNC
  3004. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3005. {
  3006. int i;
  3007. while (nextopt("a") != '\0') {
  3008. rmaliases();
  3009. return 0;
  3010. }
  3011. for (i = 0; *argptr; argptr++) {
  3012. if (unalias(*argptr)) {
  3013. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3014. i = 1;
  3015. }
  3016. }
  3017. return i;
  3018. }
  3019. #endif /* ASH_ALIAS */
  3020. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3021. #define FORK_FG 0
  3022. #define FORK_BG 1
  3023. #define FORK_NOJOB 2
  3024. /* mode flags for showjob(s) */
  3025. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3026. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3027. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3028. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3029. /*
  3030. * A job structure contains information about a job. A job is either a
  3031. * single process or a set of processes contained in a pipeline. In the
  3032. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3033. * array of pids.
  3034. */
  3035. struct procstat {
  3036. pid_t ps_pid; /* process id */
  3037. int ps_status; /* last process status from wait() */
  3038. char *ps_cmd; /* text of command being run */
  3039. };
  3040. struct job {
  3041. struct procstat ps0; /* status of process */
  3042. struct procstat *ps; /* status or processes when more than one */
  3043. #if JOBS
  3044. int stopstatus; /* status of a stopped job */
  3045. #endif
  3046. unsigned nprocs; /* number of processes */
  3047. #define JOBRUNNING 0 /* at least one proc running */
  3048. #define JOBSTOPPED 1 /* all procs are stopped */
  3049. #define JOBDONE 2 /* all procs are completed */
  3050. unsigned
  3051. state: 8,
  3052. #if JOBS
  3053. sigint: 1, /* job was killed by SIGINT */
  3054. jobctl: 1, /* job running under job control */
  3055. #endif
  3056. waited: 1, /* true if this entry has been waited for */
  3057. used: 1, /* true if this entry is in used */
  3058. changed: 1; /* true if status has changed */
  3059. struct job *prev_job; /* previous job */
  3060. };
  3061. static struct job *makejob(/*union node *,*/ int);
  3062. static int forkshell(struct job *, union node *, int);
  3063. static int waitforjob(struct job *);
  3064. #if !JOBS
  3065. enum { doing_jobctl = 0 };
  3066. #define setjobctl(on) do {} while (0)
  3067. #else
  3068. static smallint doing_jobctl; //references:8
  3069. static void setjobctl(int);
  3070. #endif
  3071. /*
  3072. * Ignore a signal.
  3073. */
  3074. static void
  3075. ignoresig(int signo)
  3076. {
  3077. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3078. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3079. /* No, need to do it */
  3080. signal(signo, SIG_IGN);
  3081. }
  3082. sigmode[signo - 1] = S_HARD_IGN;
  3083. }
  3084. /*
  3085. * Only one usage site - in setsignal()
  3086. */
  3087. static void
  3088. signal_handler(int signo)
  3089. {
  3090. if (signo == SIGCHLD) {
  3091. got_sigchld = 1;
  3092. if (!trap[SIGCHLD])
  3093. return;
  3094. }
  3095. gotsig[signo - 1] = 1;
  3096. pending_sig = signo;
  3097. if (signo == SIGINT && !trap[SIGINT]) {
  3098. if (!suppress_int) {
  3099. pending_sig = 0;
  3100. raise_interrupt(); /* does not return */
  3101. }
  3102. pending_int = 1;
  3103. }
  3104. }
  3105. /*
  3106. * Set the signal handler for the specified signal. The routine figures
  3107. * out what it should be set to.
  3108. */
  3109. static void
  3110. setsignal(int signo)
  3111. {
  3112. char *t;
  3113. char cur_act, new_act;
  3114. struct sigaction act;
  3115. t = trap[signo];
  3116. new_act = S_DFL;
  3117. if (t != NULL) { /* trap for this sig is set */
  3118. new_act = S_CATCH;
  3119. if (t[0] == '\0') /* trap is "": ignore this sig */
  3120. new_act = S_IGN;
  3121. }
  3122. if (rootshell && new_act == S_DFL) {
  3123. switch (signo) {
  3124. case SIGINT:
  3125. if (iflag || minusc || sflag == 0)
  3126. new_act = S_CATCH;
  3127. break;
  3128. case SIGQUIT:
  3129. #if DEBUG
  3130. if (debug)
  3131. break;
  3132. #endif
  3133. /* man bash:
  3134. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3135. * commands run by bash have signal handlers
  3136. * set to the values inherited by the shell
  3137. * from its parent". */
  3138. new_act = S_IGN;
  3139. break;
  3140. case SIGTERM:
  3141. if (iflag)
  3142. new_act = S_IGN;
  3143. break;
  3144. #if JOBS
  3145. case SIGTSTP:
  3146. case SIGTTOU:
  3147. if (mflag)
  3148. new_act = S_IGN;
  3149. break;
  3150. #endif
  3151. }
  3152. }
  3153. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3154. //whereas we have to restore it to what shell got on entry
  3155. //from the parent. See comment above
  3156. if (signo == SIGCHLD)
  3157. new_act = S_CATCH;
  3158. t = &sigmode[signo - 1];
  3159. cur_act = *t;
  3160. if (cur_act == 0) {
  3161. /* current setting is not yet known */
  3162. if (sigaction(signo, NULL, &act)) {
  3163. /* pretend it worked; maybe we should give a warning,
  3164. * but other shells don't. We don't alter sigmode,
  3165. * so we retry every time.
  3166. * btw, in Linux it never fails. --vda */
  3167. return;
  3168. }
  3169. if (act.sa_handler == SIG_IGN) {
  3170. cur_act = S_HARD_IGN;
  3171. if (mflag
  3172. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3173. ) {
  3174. cur_act = S_IGN; /* don't hard ignore these */
  3175. }
  3176. }
  3177. }
  3178. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3179. return;
  3180. act.sa_handler = SIG_DFL;
  3181. switch (new_act) {
  3182. case S_CATCH:
  3183. act.sa_handler = signal_handler;
  3184. break;
  3185. case S_IGN:
  3186. act.sa_handler = SIG_IGN;
  3187. break;
  3188. }
  3189. /* flags and mask matter only if !DFL and !IGN, but we do it
  3190. * for all cases for more deterministic behavior:
  3191. */
  3192. act.sa_flags = 0;
  3193. sigfillset(&act.sa_mask);
  3194. sigaction_set(signo, &act);
  3195. *t = new_act;
  3196. }
  3197. /* mode flags for set_curjob */
  3198. #define CUR_DELETE 2
  3199. #define CUR_RUNNING 1
  3200. #define CUR_STOPPED 0
  3201. #if JOBS
  3202. /* pgrp of shell on invocation */
  3203. static int initialpgrp; //references:2
  3204. static int ttyfd = -1; //5
  3205. #endif
  3206. /* array of jobs */
  3207. static struct job *jobtab; //5
  3208. /* size of array */
  3209. static unsigned njobs; //4
  3210. /* current job */
  3211. static struct job *curjob; //lots
  3212. /* number of presumed living untracked jobs */
  3213. static int jobless; //4
  3214. #if 0
  3215. /* Bash has a feature: it restores termios after a successful wait for
  3216. * a foreground job which had at least one stopped or sigkilled member.
  3217. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3218. * properly restoring tty state. Should we do this too?
  3219. * A reproducer: ^Z an interactive python:
  3220. *
  3221. * # python
  3222. * Python 2.7.12 (...)
  3223. * >>> ^Z
  3224. * { python leaves tty in -icanon -echo state. We do survive that... }
  3225. * [1]+ Stopped python
  3226. * { ...however, next program (python #2) does not survive it well: }
  3227. * # python
  3228. * Python 2.7.12 (...)
  3229. * >>> Traceback (most recent call last):
  3230. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3231. * File "<stdin>", line 1, in <module>
  3232. * NameError: name 'qwerty' is not defined
  3233. *
  3234. * The implementation below is modeled on bash code and seems to work.
  3235. * However, I'm not sure we should do this. For one: what if I'd fg
  3236. * the stopped python instead? It'll be confused by "restored" tty state.
  3237. */
  3238. static struct termios shell_tty_info;
  3239. static void
  3240. get_tty_state(void)
  3241. {
  3242. if (rootshell && ttyfd >= 0)
  3243. tcgetattr(ttyfd, &shell_tty_info);
  3244. }
  3245. static void
  3246. set_tty_state(void)
  3247. {
  3248. /* if (rootshell) - caller ensures this */
  3249. if (ttyfd >= 0)
  3250. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3251. }
  3252. static int
  3253. job_signal_status(struct job *jp)
  3254. {
  3255. int status;
  3256. unsigned i;
  3257. struct procstat *ps = jp->ps;
  3258. for (i = 0; i < jp->nprocs; i++) {
  3259. status = ps[i].ps_status;
  3260. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3261. return status;
  3262. }
  3263. return 0;
  3264. }
  3265. static void
  3266. restore_tty_if_stopped_or_signaled(struct job *jp)
  3267. {
  3268. //TODO: check what happens if we come from waitforjob() in expbackq()
  3269. if (rootshell) {
  3270. int s = job_signal_status(jp);
  3271. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3272. set_tty_state();
  3273. }
  3274. }
  3275. #else
  3276. # define get_tty_state() ((void)0)
  3277. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3278. #endif
  3279. static void
  3280. set_curjob(struct job *jp, unsigned mode)
  3281. {
  3282. struct job *jp1;
  3283. struct job **jpp, **curp;
  3284. /* first remove from list */
  3285. jpp = curp = &curjob;
  3286. while (1) {
  3287. jp1 = *jpp;
  3288. if (jp1 == jp)
  3289. break;
  3290. jpp = &jp1->prev_job;
  3291. }
  3292. *jpp = jp1->prev_job;
  3293. /* Then re-insert in correct position */
  3294. jpp = curp;
  3295. switch (mode) {
  3296. default:
  3297. #if DEBUG
  3298. abort();
  3299. #endif
  3300. case CUR_DELETE:
  3301. /* job being deleted */
  3302. break;
  3303. case CUR_RUNNING:
  3304. /* newly created job or backgrounded job,
  3305. * put after all stopped jobs.
  3306. */
  3307. while (1) {
  3308. jp1 = *jpp;
  3309. #if JOBS
  3310. if (!jp1 || jp1->state != JOBSTOPPED)
  3311. #endif
  3312. break;
  3313. jpp = &jp1->prev_job;
  3314. }
  3315. /* FALLTHROUGH */
  3316. #if JOBS
  3317. case CUR_STOPPED:
  3318. #endif
  3319. /* newly stopped job - becomes curjob */
  3320. jp->prev_job = *jpp;
  3321. *jpp = jp;
  3322. break;
  3323. }
  3324. }
  3325. #if JOBS || DEBUG
  3326. static int
  3327. jobno(const struct job *jp)
  3328. {
  3329. return jp - jobtab + 1;
  3330. }
  3331. #endif
  3332. /*
  3333. * Convert a job name to a job structure.
  3334. */
  3335. #if !JOBS
  3336. #define getjob(name, getctl) getjob(name)
  3337. #endif
  3338. static struct job *
  3339. getjob(const char *name, int getctl)
  3340. {
  3341. struct job *jp;
  3342. struct job *found;
  3343. const char *err_msg = "%s: no such job";
  3344. unsigned num;
  3345. int c;
  3346. const char *p;
  3347. char *(*match)(const char *, const char *);
  3348. jp = curjob;
  3349. p = name;
  3350. if (!p)
  3351. goto currentjob;
  3352. if (*p != '%')
  3353. goto err;
  3354. c = *++p;
  3355. if (!c)
  3356. goto currentjob;
  3357. if (!p[1]) {
  3358. if (c == '+' || c == '%') {
  3359. currentjob:
  3360. err_msg = "No current job";
  3361. goto check;
  3362. }
  3363. if (c == '-') {
  3364. if (jp)
  3365. jp = jp->prev_job;
  3366. err_msg = "No previous job";
  3367. check:
  3368. if (!jp)
  3369. goto err;
  3370. goto gotit;
  3371. }
  3372. }
  3373. if (is_number(p)) {
  3374. num = atoi(p);
  3375. if (num > 0 && num <= njobs) {
  3376. jp = jobtab + num - 1;
  3377. if (jp->used)
  3378. goto gotit;
  3379. goto err;
  3380. }
  3381. }
  3382. match = prefix;
  3383. if (*p == '?') {
  3384. match = strstr;
  3385. p++;
  3386. }
  3387. found = NULL;
  3388. while (jp) {
  3389. if (match(jp->ps[0].ps_cmd, p)) {
  3390. if (found)
  3391. goto err;
  3392. found = jp;
  3393. err_msg = "%s: ambiguous";
  3394. }
  3395. jp = jp->prev_job;
  3396. }
  3397. if (!found)
  3398. goto err;
  3399. jp = found;
  3400. gotit:
  3401. #if JOBS
  3402. err_msg = "job %s not created under job control";
  3403. if (getctl && jp->jobctl == 0)
  3404. goto err;
  3405. #endif
  3406. return jp;
  3407. err:
  3408. ash_msg_and_raise_error(err_msg, name);
  3409. }
  3410. /*
  3411. * Mark a job structure as unused.
  3412. */
  3413. static void
  3414. freejob(struct job *jp)
  3415. {
  3416. struct procstat *ps;
  3417. int i;
  3418. INT_OFF;
  3419. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3420. if (ps->ps_cmd != nullstr)
  3421. free(ps->ps_cmd);
  3422. }
  3423. if (jp->ps != &jp->ps0)
  3424. free(jp->ps);
  3425. jp->used = 0;
  3426. set_curjob(jp, CUR_DELETE);
  3427. INT_ON;
  3428. }
  3429. #if JOBS
  3430. static void
  3431. xtcsetpgrp(int fd, pid_t pgrp)
  3432. {
  3433. if (tcsetpgrp(fd, pgrp))
  3434. ash_msg_and_raise_error("can't set tty process group (%m)");
  3435. }
  3436. /*
  3437. * Turn job control on and off.
  3438. *
  3439. * Note: This code assumes that the third arg to ioctl is a character
  3440. * pointer, which is true on Berkeley systems but not System V. Since
  3441. * System V doesn't have job control yet, this isn't a problem now.
  3442. *
  3443. * Called with interrupts off.
  3444. */
  3445. static void
  3446. setjobctl(int on)
  3447. {
  3448. int fd;
  3449. int pgrp;
  3450. if (on == doing_jobctl || rootshell == 0)
  3451. return;
  3452. if (on) {
  3453. int ofd;
  3454. ofd = fd = open(_PATH_TTY, O_RDWR);
  3455. if (fd < 0) {
  3456. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3457. * That sometimes helps to acquire controlling tty.
  3458. * Obviously, a workaround for bugs when someone
  3459. * failed to provide a controlling tty to bash! :) */
  3460. fd = 2;
  3461. while (!isatty(fd))
  3462. if (--fd < 0)
  3463. goto out;
  3464. }
  3465. /* fd is a tty at this point */
  3466. fd = fcntl(fd, F_DUPFD, 10);
  3467. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3468. close(ofd);
  3469. if (fd < 0)
  3470. goto out; /* F_DUPFD failed */
  3471. close_on_exec_on(fd);
  3472. while (1) { /* while we are in the background */
  3473. pgrp = tcgetpgrp(fd);
  3474. if (pgrp < 0) {
  3475. out:
  3476. ash_msg("can't access tty; job control turned off");
  3477. mflag = on = 0;
  3478. goto close;
  3479. }
  3480. if (pgrp == getpgrp())
  3481. break;
  3482. killpg(0, SIGTTIN);
  3483. }
  3484. initialpgrp = pgrp;
  3485. setsignal(SIGTSTP);
  3486. setsignal(SIGTTOU);
  3487. setsignal(SIGTTIN);
  3488. pgrp = rootpid;
  3489. setpgid(0, pgrp);
  3490. xtcsetpgrp(fd, pgrp);
  3491. } else {
  3492. /* turning job control off */
  3493. fd = ttyfd;
  3494. pgrp = initialpgrp;
  3495. /* was xtcsetpgrp, but this can make exiting ash
  3496. * loop forever if pty is already deleted */
  3497. tcsetpgrp(fd, pgrp);
  3498. setpgid(0, pgrp);
  3499. setsignal(SIGTSTP);
  3500. setsignal(SIGTTOU);
  3501. setsignal(SIGTTIN);
  3502. close:
  3503. if (fd >= 0)
  3504. close(fd);
  3505. fd = -1;
  3506. }
  3507. ttyfd = fd;
  3508. doing_jobctl = on;
  3509. }
  3510. static int FAST_FUNC
  3511. killcmd(int argc, char **argv)
  3512. {
  3513. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3514. int i = 1;
  3515. do {
  3516. if (argv[i][0] == '%') {
  3517. /*
  3518. * "kill %N" - job kill
  3519. * Converting to pgrp / pid kill
  3520. */
  3521. struct job *jp;
  3522. char *dst;
  3523. int j, n;
  3524. jp = getjob(argv[i], 0);
  3525. /*
  3526. * In jobs started under job control, we signal
  3527. * entire process group by kill -PGRP_ID.
  3528. * This happens, f.e., in interactive shell.
  3529. *
  3530. * Otherwise, we signal each child via
  3531. * kill PID1 PID2 PID3.
  3532. * Testcases:
  3533. * sh -c 'sleep 1|sleep 1 & kill %1'
  3534. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3535. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3536. */
  3537. n = jp->nprocs; /* can't be 0 (I hope) */
  3538. if (jp->jobctl)
  3539. n = 1;
  3540. dst = alloca(n * sizeof(int)*4);
  3541. argv[i] = dst;
  3542. for (j = 0; j < n; j++) {
  3543. struct procstat *ps = &jp->ps[j];
  3544. /* Skip non-running and not-stopped members
  3545. * (i.e. dead members) of the job
  3546. */
  3547. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3548. continue;
  3549. /*
  3550. * kill_main has matching code to expect
  3551. * leading space. Needed to not confuse
  3552. * negative pids with "kill -SIGNAL_NO" syntax
  3553. */
  3554. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3555. }
  3556. *dst = '\0';
  3557. }
  3558. } while (argv[++i]);
  3559. }
  3560. return kill_main(argc, argv);
  3561. }
  3562. static void
  3563. showpipe(struct job *jp /*, FILE *out*/)
  3564. {
  3565. struct procstat *ps;
  3566. struct procstat *psend;
  3567. psend = jp->ps + jp->nprocs;
  3568. for (ps = jp->ps + 1; ps < psend; ps++)
  3569. printf(" | %s", ps->ps_cmd);
  3570. newline_and_flush(stdout);
  3571. flush_stdout_stderr();
  3572. }
  3573. static int
  3574. restartjob(struct job *jp, int mode)
  3575. {
  3576. struct procstat *ps;
  3577. int i;
  3578. int status;
  3579. pid_t pgid;
  3580. INT_OFF;
  3581. if (jp->state == JOBDONE)
  3582. goto out;
  3583. jp->state = JOBRUNNING;
  3584. pgid = jp->ps[0].ps_pid;
  3585. if (mode == FORK_FG) {
  3586. get_tty_state();
  3587. xtcsetpgrp(ttyfd, pgid);
  3588. }
  3589. killpg(pgid, SIGCONT);
  3590. ps = jp->ps;
  3591. i = jp->nprocs;
  3592. do {
  3593. if (WIFSTOPPED(ps->ps_status)) {
  3594. ps->ps_status = -1;
  3595. }
  3596. ps++;
  3597. } while (--i);
  3598. out:
  3599. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3600. INT_ON;
  3601. return status;
  3602. }
  3603. static int FAST_FUNC
  3604. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3605. {
  3606. struct job *jp;
  3607. int mode;
  3608. int retval;
  3609. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3610. nextopt(nullstr);
  3611. argv = argptr;
  3612. do {
  3613. jp = getjob(*argv, 1);
  3614. if (mode == FORK_BG) {
  3615. set_curjob(jp, CUR_RUNNING);
  3616. printf("[%d] ", jobno(jp));
  3617. }
  3618. out1str(jp->ps[0].ps_cmd);
  3619. showpipe(jp /*, stdout*/);
  3620. retval = restartjob(jp, mode);
  3621. } while (*argv && *++argv);
  3622. return retval;
  3623. }
  3624. #endif
  3625. static int
  3626. sprint_status48(char *s, int status, int sigonly)
  3627. {
  3628. int col;
  3629. int st;
  3630. col = 0;
  3631. if (!WIFEXITED(status)) {
  3632. #if JOBS
  3633. if (WIFSTOPPED(status))
  3634. st = WSTOPSIG(status);
  3635. else
  3636. #endif
  3637. st = WTERMSIG(status);
  3638. if (sigonly) {
  3639. if (st == SIGINT || st == SIGPIPE)
  3640. goto out;
  3641. #if JOBS
  3642. if (WIFSTOPPED(status))
  3643. goto out;
  3644. #endif
  3645. }
  3646. st &= 0x7f;
  3647. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3648. col = fmtstr(s, 32, strsignal(st));
  3649. if (WCOREDUMP(status)) {
  3650. strcpy(s + col, " (core dumped)");
  3651. col += sizeof(" (core dumped)")-1;
  3652. }
  3653. } else if (!sigonly) {
  3654. st = WEXITSTATUS(status);
  3655. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3656. }
  3657. out:
  3658. return col;
  3659. }
  3660. static int
  3661. wait_block_or_sig(int *status)
  3662. {
  3663. int pid;
  3664. do {
  3665. sigset_t mask;
  3666. /* Poll all children for changes in their state */
  3667. got_sigchld = 0;
  3668. /* if job control is active, accept stopped processes too */
  3669. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3670. if (pid != 0)
  3671. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3672. /* Children exist, but none are ready. Sleep until interesting signal */
  3673. #if 1
  3674. sigfillset(&mask);
  3675. sigprocmask(SIG_SETMASK, &mask, &mask);
  3676. while (!got_sigchld && !pending_sig)
  3677. sigsuspend(&mask);
  3678. sigprocmask(SIG_SETMASK, &mask, NULL);
  3679. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3680. while (!got_sigchld && !pending_sig)
  3681. pause();
  3682. #endif
  3683. /* If it was SIGCHLD, poll children again */
  3684. } while (got_sigchld);
  3685. return pid;
  3686. }
  3687. #define DOWAIT_NONBLOCK 0
  3688. #define DOWAIT_BLOCK 1
  3689. #define DOWAIT_BLOCK_OR_SIG 2
  3690. static int
  3691. dowait(int block, struct job *job)
  3692. {
  3693. int pid;
  3694. int status;
  3695. struct job *jp;
  3696. struct job *thisjob = NULL;
  3697. TRACE(("dowait(0x%x) called\n", block));
  3698. /* It's wrong to call waitpid() outside of INT_OFF region:
  3699. * signal can arrive just after syscall return and handler can
  3700. * longjmp away, losing stop/exit notification processing.
  3701. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3702. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3703. *
  3704. * However, for "wait" builtin it is wrong to simply call waitpid()
  3705. * in INT_OFF region: "wait" needs to wait for any running job
  3706. * to change state, but should exit on any trap too.
  3707. * In INT_OFF region, a signal just before syscall entry can set
  3708. * pending_sig variables, but we can't check them, and we would
  3709. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3710. *
  3711. * Because of this, we run inside INT_OFF, but use a special routine
  3712. * which combines waitpid() and sigsuspend().
  3713. * This is the reason why we need to have a handler for SIGCHLD:
  3714. * SIG_DFL handler does not wake sigsuspend().
  3715. */
  3716. INT_OFF;
  3717. if (block == DOWAIT_BLOCK_OR_SIG) {
  3718. pid = wait_block_or_sig(&status);
  3719. } else {
  3720. int wait_flags = 0;
  3721. if (block == DOWAIT_NONBLOCK)
  3722. wait_flags = WNOHANG;
  3723. /* if job control is active, accept stopped processes too */
  3724. if (doing_jobctl)
  3725. wait_flags |= WUNTRACED;
  3726. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3727. pid = waitpid(-1, &status, wait_flags);
  3728. }
  3729. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3730. pid, status, errno, strerror(errno)));
  3731. if (pid <= 0)
  3732. goto out;
  3733. thisjob = NULL;
  3734. for (jp = curjob; jp; jp = jp->prev_job) {
  3735. int jobstate;
  3736. struct procstat *ps;
  3737. struct procstat *psend;
  3738. if (jp->state == JOBDONE)
  3739. continue;
  3740. jobstate = JOBDONE;
  3741. ps = jp->ps;
  3742. psend = ps + jp->nprocs;
  3743. do {
  3744. if (ps->ps_pid == pid) {
  3745. TRACE(("Job %d: changing status of proc %d "
  3746. "from 0x%x to 0x%x\n",
  3747. jobno(jp), pid, ps->ps_status, status));
  3748. ps->ps_status = status;
  3749. thisjob = jp;
  3750. }
  3751. if (ps->ps_status == -1)
  3752. jobstate = JOBRUNNING;
  3753. #if JOBS
  3754. if (jobstate == JOBRUNNING)
  3755. continue;
  3756. if (WIFSTOPPED(ps->ps_status)) {
  3757. jp->stopstatus = ps->ps_status;
  3758. jobstate = JOBSTOPPED;
  3759. }
  3760. #endif
  3761. } while (++ps < psend);
  3762. if (!thisjob)
  3763. continue;
  3764. /* Found the job where one of its processes changed its state.
  3765. * Is there at least one live and running process in this job? */
  3766. if (jobstate != JOBRUNNING) {
  3767. /* No. All live processes in the job are stopped
  3768. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3769. */
  3770. thisjob->changed = 1;
  3771. if (thisjob->state != jobstate) {
  3772. TRACE(("Job %d: changing state from %d to %d\n",
  3773. jobno(thisjob), thisjob->state, jobstate));
  3774. thisjob->state = jobstate;
  3775. #if JOBS
  3776. if (jobstate == JOBSTOPPED)
  3777. set_curjob(thisjob, CUR_STOPPED);
  3778. #endif
  3779. }
  3780. }
  3781. goto out;
  3782. }
  3783. /* The process wasn't found in job list */
  3784. #if JOBS
  3785. if (!WIFSTOPPED(status))
  3786. jobless--;
  3787. #endif
  3788. out:
  3789. INT_ON;
  3790. if (thisjob && thisjob == job) {
  3791. char s[48 + 1];
  3792. int len;
  3793. len = sprint_status48(s, status, 1);
  3794. if (len) {
  3795. s[len] = '\n';
  3796. s[len + 1] = '\0';
  3797. out2str(s);
  3798. }
  3799. }
  3800. return pid;
  3801. }
  3802. #if JOBS
  3803. static void
  3804. showjob(struct job *jp, int mode)
  3805. {
  3806. struct procstat *ps;
  3807. struct procstat *psend;
  3808. int col;
  3809. int indent_col;
  3810. char s[16 + 16 + 48];
  3811. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3812. ps = jp->ps;
  3813. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3814. /* just output process (group) id of pipeline */
  3815. fprintf(out, "%d\n", ps->ps_pid);
  3816. return;
  3817. }
  3818. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3819. indent_col = col;
  3820. if (jp == curjob)
  3821. s[col - 3] = '+';
  3822. else if (curjob && jp == curjob->prev_job)
  3823. s[col - 3] = '-';
  3824. if (mode & SHOW_PIDS)
  3825. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3826. psend = ps + jp->nprocs;
  3827. if (jp->state == JOBRUNNING) {
  3828. strcpy(s + col, "Running");
  3829. col += sizeof("Running") - 1;
  3830. } else {
  3831. int status = psend[-1].ps_status;
  3832. if (jp->state == JOBSTOPPED)
  3833. status = jp->stopstatus;
  3834. col += sprint_status48(s + col, status, 0);
  3835. }
  3836. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3837. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3838. * or prints several "PID | <cmdN>" lines,
  3839. * depending on SHOW_PIDS bit.
  3840. * We do not print status of individual processes
  3841. * between PID and <cmdN>. bash does it, but not very well:
  3842. * first line shows overall job status, not process status,
  3843. * making it impossible to know 1st process status.
  3844. */
  3845. goto start;
  3846. do {
  3847. /* for each process */
  3848. s[0] = '\0';
  3849. col = 33;
  3850. if (mode & SHOW_PIDS)
  3851. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3852. start:
  3853. fprintf(out, "%s%*c%s%s",
  3854. s,
  3855. 33 - col >= 0 ? 33 - col : 0, ' ',
  3856. ps == jp->ps ? "" : "| ",
  3857. ps->ps_cmd
  3858. );
  3859. } while (++ps != psend);
  3860. newline_and_flush(out);
  3861. jp->changed = 0;
  3862. if (jp->state == JOBDONE) {
  3863. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3864. freejob(jp);
  3865. }
  3866. }
  3867. /*
  3868. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3869. * statuses have changed since the last call to showjobs.
  3870. */
  3871. static void
  3872. showjobs(int mode)
  3873. {
  3874. struct job *jp;
  3875. TRACE(("showjobs(0x%x) called\n", mode));
  3876. /* Handle all finished jobs */
  3877. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3878. continue;
  3879. for (jp = curjob; jp; jp = jp->prev_job) {
  3880. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3881. showjob(jp, mode);
  3882. }
  3883. }
  3884. }
  3885. static int FAST_FUNC
  3886. jobscmd(int argc UNUSED_PARAM, char **argv)
  3887. {
  3888. int mode, m;
  3889. mode = 0;
  3890. while ((m = nextopt("lp")) != '\0') {
  3891. if (m == 'l')
  3892. mode |= SHOW_PIDS;
  3893. else
  3894. mode |= SHOW_ONLY_PGID;
  3895. }
  3896. argv = argptr;
  3897. if (*argv) {
  3898. do
  3899. showjob(getjob(*argv, 0), mode);
  3900. while (*++argv);
  3901. } else {
  3902. showjobs(mode);
  3903. }
  3904. return 0;
  3905. }
  3906. #endif /* JOBS */
  3907. /* Called only on finished or stopped jobs (no members are running) */
  3908. static int
  3909. getstatus(struct job *job)
  3910. {
  3911. int status;
  3912. int retval;
  3913. struct procstat *ps;
  3914. /* Fetch last member's status */
  3915. ps = job->ps + job->nprocs - 1;
  3916. status = ps->ps_status;
  3917. if (pipefail) {
  3918. /* "set -o pipefail" mode: use last _nonzero_ status */
  3919. while (status == 0 && --ps >= job->ps)
  3920. status = ps->ps_status;
  3921. }
  3922. retval = WEXITSTATUS(status);
  3923. if (!WIFEXITED(status)) {
  3924. #if JOBS
  3925. retval = WSTOPSIG(status);
  3926. if (!WIFSTOPPED(status))
  3927. #endif
  3928. {
  3929. /* XXX: limits number of signals */
  3930. retval = WTERMSIG(status);
  3931. #if JOBS
  3932. if (retval == SIGINT)
  3933. job->sigint = 1;
  3934. #endif
  3935. }
  3936. retval += 128;
  3937. }
  3938. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3939. jobno(job), job->nprocs, status, retval));
  3940. return retval;
  3941. }
  3942. static int FAST_FUNC
  3943. waitcmd(int argc UNUSED_PARAM, char **argv)
  3944. {
  3945. struct job *job;
  3946. int retval;
  3947. struct job *jp;
  3948. nextopt(nullstr);
  3949. retval = 0;
  3950. argv = argptr;
  3951. if (!*argv) {
  3952. /* wait for all jobs */
  3953. for (;;) {
  3954. jp = curjob;
  3955. while (1) {
  3956. if (!jp) /* no running procs */
  3957. goto ret;
  3958. if (jp->state == JOBRUNNING)
  3959. break;
  3960. jp->waited = 1;
  3961. jp = jp->prev_job;
  3962. }
  3963. /* man bash:
  3964. * "When bash is waiting for an asynchronous command via
  3965. * the wait builtin, the reception of a signal for which a trap
  3966. * has been set will cause the wait builtin to return immediately
  3967. * with an exit status greater than 128, immediately after which
  3968. * the trap is executed."
  3969. */
  3970. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  3971. /* if child sends us a signal *and immediately exits*,
  3972. * dowait() returns pid > 0. Check this case,
  3973. * not "if (dowait() < 0)"!
  3974. */
  3975. if (pending_sig)
  3976. goto sigout;
  3977. }
  3978. }
  3979. retval = 127;
  3980. do {
  3981. if (**argv != '%') {
  3982. pid_t pid = number(*argv);
  3983. job = curjob;
  3984. while (1) {
  3985. if (!job)
  3986. goto repeat;
  3987. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3988. break;
  3989. job = job->prev_job;
  3990. }
  3991. } else {
  3992. job = getjob(*argv, 0);
  3993. }
  3994. /* loop until process terminated or stopped */
  3995. while (job->state == JOBRUNNING) {
  3996. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  3997. if (pending_sig)
  3998. goto sigout;
  3999. }
  4000. job->waited = 1;
  4001. retval = getstatus(job);
  4002. repeat: ;
  4003. } while (*++argv);
  4004. ret:
  4005. return retval;
  4006. sigout:
  4007. retval = 128 + pending_sig;
  4008. return retval;
  4009. }
  4010. static struct job *
  4011. growjobtab(void)
  4012. {
  4013. size_t len;
  4014. ptrdiff_t offset;
  4015. struct job *jp, *jq;
  4016. len = njobs * sizeof(*jp);
  4017. jq = jobtab;
  4018. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4019. offset = (char *)jp - (char *)jq;
  4020. if (offset) {
  4021. /* Relocate pointers */
  4022. size_t l = len;
  4023. jq = (struct job *)((char *)jq + l);
  4024. while (l) {
  4025. l -= sizeof(*jp);
  4026. jq--;
  4027. #define joff(p) ((struct job *)((char *)(p) + l))
  4028. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4029. if (joff(jp)->ps == &jq->ps0)
  4030. jmove(joff(jp)->ps);
  4031. if (joff(jp)->prev_job)
  4032. jmove(joff(jp)->prev_job);
  4033. }
  4034. if (curjob)
  4035. jmove(curjob);
  4036. #undef joff
  4037. #undef jmove
  4038. }
  4039. njobs += 4;
  4040. jobtab = jp;
  4041. jp = (struct job *)((char *)jp + len);
  4042. jq = jp + 3;
  4043. do {
  4044. jq->used = 0;
  4045. } while (--jq >= jp);
  4046. return jp;
  4047. }
  4048. /*
  4049. * Return a new job structure.
  4050. * Called with interrupts off.
  4051. */
  4052. static struct job *
  4053. makejob(/*union node *node,*/ int nprocs)
  4054. {
  4055. int i;
  4056. struct job *jp;
  4057. for (i = njobs, jp = jobtab; ; jp++) {
  4058. if (--i < 0) {
  4059. jp = growjobtab();
  4060. break;
  4061. }
  4062. if (jp->used == 0)
  4063. break;
  4064. if (jp->state != JOBDONE || !jp->waited)
  4065. continue;
  4066. #if JOBS
  4067. if (doing_jobctl)
  4068. continue;
  4069. #endif
  4070. freejob(jp);
  4071. break;
  4072. }
  4073. memset(jp, 0, sizeof(*jp));
  4074. #if JOBS
  4075. /* jp->jobctl is a bitfield.
  4076. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4077. if (doing_jobctl)
  4078. jp->jobctl = 1;
  4079. #endif
  4080. jp->prev_job = curjob;
  4081. curjob = jp;
  4082. jp->used = 1;
  4083. jp->ps = &jp->ps0;
  4084. if (nprocs > 1) {
  4085. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4086. }
  4087. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4088. jobno(jp)));
  4089. return jp;
  4090. }
  4091. #if JOBS
  4092. /*
  4093. * Return a string identifying a command (to be printed by the
  4094. * jobs command).
  4095. */
  4096. static char *cmdnextc;
  4097. static void
  4098. cmdputs(const char *s)
  4099. {
  4100. static const char vstype[VSTYPE + 1][3] = {
  4101. "", "}", "-", "+", "?", "=",
  4102. "%", "%%", "#", "##"
  4103. IF_BASH_SUBSTR(, ":")
  4104. IF_BASH_PATTERN_SUBST(, "/", "//")
  4105. };
  4106. const char *p, *str;
  4107. char cc[2];
  4108. char *nextc;
  4109. unsigned char c;
  4110. unsigned char subtype = 0;
  4111. int quoted = 0;
  4112. cc[1] = '\0';
  4113. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4114. p = s;
  4115. while ((c = *p++) != '\0') {
  4116. str = NULL;
  4117. switch (c) {
  4118. case CTLESC:
  4119. c = *p++;
  4120. break;
  4121. case CTLVAR:
  4122. subtype = *p++;
  4123. if ((subtype & VSTYPE) == VSLENGTH)
  4124. str = "${#";
  4125. else
  4126. str = "${";
  4127. goto dostr;
  4128. case CTLENDVAR:
  4129. str = "\"}" + !(quoted & 1);
  4130. quoted >>= 1;
  4131. subtype = 0;
  4132. goto dostr;
  4133. case CTLBACKQ:
  4134. str = "$(...)";
  4135. goto dostr;
  4136. #if ENABLE_FEATURE_SH_MATH
  4137. case CTLARI:
  4138. str = "$((";
  4139. goto dostr;
  4140. case CTLENDARI:
  4141. str = "))";
  4142. goto dostr;
  4143. #endif
  4144. case CTLQUOTEMARK:
  4145. quoted ^= 1;
  4146. c = '"';
  4147. break;
  4148. case '=':
  4149. if (subtype == 0)
  4150. break;
  4151. if ((subtype & VSTYPE) != VSNORMAL)
  4152. quoted <<= 1;
  4153. str = vstype[subtype & VSTYPE];
  4154. if (subtype & VSNUL)
  4155. c = ':';
  4156. else
  4157. goto checkstr;
  4158. break;
  4159. case '\'':
  4160. case '\\':
  4161. case '"':
  4162. case '$':
  4163. /* These can only happen inside quotes */
  4164. cc[0] = c;
  4165. str = cc;
  4166. c = '\\';
  4167. break;
  4168. default:
  4169. break;
  4170. }
  4171. USTPUTC(c, nextc);
  4172. checkstr:
  4173. if (!str)
  4174. continue;
  4175. dostr:
  4176. while ((c = *str++) != '\0') {
  4177. USTPUTC(c, nextc);
  4178. }
  4179. } /* while *p++ not NUL */
  4180. if (quoted & 1) {
  4181. USTPUTC('"', nextc);
  4182. }
  4183. *nextc = 0;
  4184. cmdnextc = nextc;
  4185. }
  4186. /* cmdtxt() and cmdlist() call each other */
  4187. static void cmdtxt(union node *n);
  4188. static void
  4189. cmdlist(union node *np, int sep)
  4190. {
  4191. for (; np; np = np->narg.next) {
  4192. if (!sep)
  4193. cmdputs(" ");
  4194. cmdtxt(np);
  4195. if (sep && np->narg.next)
  4196. cmdputs(" ");
  4197. }
  4198. }
  4199. static void
  4200. cmdtxt(union node *n)
  4201. {
  4202. union node *np;
  4203. struct nodelist *lp;
  4204. const char *p;
  4205. if (!n)
  4206. return;
  4207. switch (n->type) {
  4208. default:
  4209. #if DEBUG
  4210. abort();
  4211. #endif
  4212. case NPIPE:
  4213. lp = n->npipe.cmdlist;
  4214. for (;;) {
  4215. cmdtxt(lp->n);
  4216. lp = lp->next;
  4217. if (!lp)
  4218. break;
  4219. cmdputs(" | ");
  4220. }
  4221. break;
  4222. case NSEMI:
  4223. p = "; ";
  4224. goto binop;
  4225. case NAND:
  4226. p = " && ";
  4227. goto binop;
  4228. case NOR:
  4229. p = " || ";
  4230. binop:
  4231. cmdtxt(n->nbinary.ch1);
  4232. cmdputs(p);
  4233. n = n->nbinary.ch2;
  4234. goto donode;
  4235. case NREDIR:
  4236. case NBACKGND:
  4237. n = n->nredir.n;
  4238. goto donode;
  4239. case NNOT:
  4240. cmdputs("!");
  4241. n = n->nnot.com;
  4242. donode:
  4243. cmdtxt(n);
  4244. break;
  4245. case NIF:
  4246. cmdputs("if ");
  4247. cmdtxt(n->nif.test);
  4248. cmdputs("; then ");
  4249. if (n->nif.elsepart) {
  4250. cmdtxt(n->nif.ifpart);
  4251. cmdputs("; else ");
  4252. n = n->nif.elsepart;
  4253. } else {
  4254. n = n->nif.ifpart;
  4255. }
  4256. p = "; fi";
  4257. goto dotail;
  4258. case NSUBSHELL:
  4259. cmdputs("(");
  4260. n = n->nredir.n;
  4261. p = ")";
  4262. goto dotail;
  4263. case NWHILE:
  4264. p = "while ";
  4265. goto until;
  4266. case NUNTIL:
  4267. p = "until ";
  4268. until:
  4269. cmdputs(p);
  4270. cmdtxt(n->nbinary.ch1);
  4271. n = n->nbinary.ch2;
  4272. p = "; done";
  4273. dodo:
  4274. cmdputs("; do ");
  4275. dotail:
  4276. cmdtxt(n);
  4277. goto dotail2;
  4278. case NFOR:
  4279. cmdputs("for ");
  4280. cmdputs(n->nfor.var);
  4281. cmdputs(" in ");
  4282. cmdlist(n->nfor.args, 1);
  4283. n = n->nfor.body;
  4284. p = "; done";
  4285. goto dodo;
  4286. case NDEFUN:
  4287. cmdputs(n->narg.text);
  4288. p = "() { ... }";
  4289. goto dotail2;
  4290. case NCMD:
  4291. cmdlist(n->ncmd.args, 1);
  4292. cmdlist(n->ncmd.redirect, 0);
  4293. break;
  4294. case NARG:
  4295. p = n->narg.text;
  4296. dotail2:
  4297. cmdputs(p);
  4298. break;
  4299. case NHERE:
  4300. case NXHERE:
  4301. p = "<<...";
  4302. goto dotail2;
  4303. case NCASE:
  4304. cmdputs("case ");
  4305. cmdputs(n->ncase.expr->narg.text);
  4306. cmdputs(" in ");
  4307. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4308. cmdtxt(np->nclist.pattern);
  4309. cmdputs(") ");
  4310. cmdtxt(np->nclist.body);
  4311. cmdputs(";; ");
  4312. }
  4313. p = "esac";
  4314. goto dotail2;
  4315. case NTO:
  4316. p = ">";
  4317. goto redir;
  4318. case NCLOBBER:
  4319. p = ">|";
  4320. goto redir;
  4321. case NAPPEND:
  4322. p = ">>";
  4323. goto redir;
  4324. #if BASH_REDIR_OUTPUT
  4325. case NTO2:
  4326. #endif
  4327. case NTOFD:
  4328. p = ">&";
  4329. goto redir;
  4330. case NFROM:
  4331. p = "<";
  4332. goto redir;
  4333. case NFROMFD:
  4334. p = "<&";
  4335. goto redir;
  4336. case NFROMTO:
  4337. p = "<>";
  4338. redir:
  4339. cmdputs(utoa(n->nfile.fd));
  4340. cmdputs(p);
  4341. if (n->type == NTOFD || n->type == NFROMFD) {
  4342. cmdputs(utoa(n->ndup.dupfd));
  4343. break;
  4344. }
  4345. n = n->nfile.fname;
  4346. goto donode;
  4347. }
  4348. }
  4349. static char *
  4350. commandtext(union node *n)
  4351. {
  4352. char *name;
  4353. STARTSTACKSTR(cmdnextc);
  4354. cmdtxt(n);
  4355. name = stackblock();
  4356. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4357. return ckstrdup(name);
  4358. }
  4359. #endif /* JOBS */
  4360. /*
  4361. * Fork off a subshell. If we are doing job control, give the subshell its
  4362. * own process group. Jp is a job structure that the job is to be added to.
  4363. * N is the command that will be evaluated by the child. Both jp and n may
  4364. * be NULL. The mode parameter can be one of the following:
  4365. * FORK_FG - Fork off a foreground process.
  4366. * FORK_BG - Fork off a background process.
  4367. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4368. * process group even if job control is on.
  4369. *
  4370. * When job control is turned off, background processes have their standard
  4371. * input redirected to /dev/null (except for the second and later processes
  4372. * in a pipeline).
  4373. *
  4374. * Called with interrupts off.
  4375. */
  4376. /*
  4377. * Clear traps on a fork.
  4378. */
  4379. static void
  4380. clear_traps(void)
  4381. {
  4382. char **tp;
  4383. INT_OFF;
  4384. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4385. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4386. if (trap_ptr == trap)
  4387. free(*tp);
  4388. /* else: it "belongs" to trap_ptr vector, don't free */
  4389. *tp = NULL;
  4390. if ((tp - trap) != 0)
  4391. setsignal(tp - trap);
  4392. }
  4393. }
  4394. may_have_traps = 0;
  4395. INT_ON;
  4396. }
  4397. /* Lives far away from here, needed for forkchild */
  4398. static void closescript(void);
  4399. /* Called after fork(), in child */
  4400. /* jp and n are NULL when called by openhere() for heredoc support */
  4401. static NOINLINE void
  4402. forkchild(struct job *jp, union node *n, int mode)
  4403. {
  4404. int oldlvl;
  4405. TRACE(("Child shell %d\n", getpid()));
  4406. oldlvl = shlvl;
  4407. shlvl++;
  4408. /* man bash: "Non-builtin commands run by bash have signal handlers
  4409. * set to the values inherited by the shell from its parent".
  4410. * Do we do it correctly? */
  4411. closescript();
  4412. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4413. && n && n->type == NCMD /* is it single cmd? */
  4414. /* && n->ncmd.args->type == NARG - always true? */
  4415. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4416. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4417. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4418. ) {
  4419. TRACE(("Trap hack\n"));
  4420. /* Awful hack for `trap` or $(trap).
  4421. *
  4422. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4423. * contains an example where "trap" is executed in a subshell:
  4424. *
  4425. * save_traps=$(trap)
  4426. * ...
  4427. * eval "$save_traps"
  4428. *
  4429. * Standard does not say that "trap" in subshell shall print
  4430. * parent shell's traps. It only says that its output
  4431. * must have suitable form, but then, in the above example
  4432. * (which is not supposed to be normative), it implies that.
  4433. *
  4434. * bash (and probably other shell) does implement it
  4435. * (traps are reset to defaults, but "trap" still shows them),
  4436. * but as a result, "trap" logic is hopelessly messed up:
  4437. *
  4438. * # trap
  4439. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4440. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4441. * # true | trap <--- trap is in subshell - no output (ditto)
  4442. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4443. * trap -- 'echo Ho' SIGWINCH
  4444. * # echo `(trap)` <--- in subshell in subshell - output
  4445. * trap -- 'echo Ho' SIGWINCH
  4446. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4447. * trap -- 'echo Ho' SIGWINCH
  4448. *
  4449. * The rules when to forget and when to not forget traps
  4450. * get really complex and nonsensical.
  4451. *
  4452. * Our solution: ONLY bare $(trap) or `trap` is special.
  4453. */
  4454. /* Save trap handler strings for trap builtin to print */
  4455. trap_ptr = xmemdup(trap, sizeof(trap));
  4456. /* Fall through into clearing traps */
  4457. }
  4458. clear_traps();
  4459. #if JOBS
  4460. /* do job control only in root shell */
  4461. doing_jobctl = 0;
  4462. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4463. pid_t pgrp;
  4464. if (jp->nprocs == 0)
  4465. pgrp = getpid();
  4466. else
  4467. pgrp = jp->ps[0].ps_pid;
  4468. /* this can fail because we are doing it in the parent also */
  4469. setpgid(0, pgrp);
  4470. if (mode == FORK_FG)
  4471. xtcsetpgrp(ttyfd, pgrp);
  4472. setsignal(SIGTSTP);
  4473. setsignal(SIGTTOU);
  4474. } else
  4475. #endif
  4476. if (mode == FORK_BG) {
  4477. /* man bash: "When job control is not in effect,
  4478. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4479. ignoresig(SIGINT);
  4480. ignoresig(SIGQUIT);
  4481. if (jp->nprocs == 0) {
  4482. close(0);
  4483. if (open(bb_dev_null, O_RDONLY) != 0)
  4484. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4485. }
  4486. }
  4487. if (oldlvl == 0) {
  4488. if (iflag) { /* why if iflag only? */
  4489. setsignal(SIGINT);
  4490. setsignal(SIGTERM);
  4491. }
  4492. /* man bash:
  4493. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4494. * commands run by bash have signal handlers
  4495. * set to the values inherited by the shell
  4496. * from its parent".
  4497. * Take care of the second rule: */
  4498. setsignal(SIGQUIT);
  4499. }
  4500. #if JOBS
  4501. if (n && n->type == NCMD
  4502. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4503. ) {
  4504. TRACE(("Job hack\n"));
  4505. /* "jobs": we do not want to clear job list for it,
  4506. * instead we remove only _its_ own_ job from job list.
  4507. * This makes "jobs .... | cat" more useful.
  4508. */
  4509. freejob(curjob);
  4510. return;
  4511. }
  4512. #endif
  4513. for (jp = curjob; jp; jp = jp->prev_job)
  4514. freejob(jp);
  4515. jobless = 0;
  4516. }
  4517. /* Called after fork(), in parent */
  4518. #if !JOBS
  4519. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4520. #endif
  4521. static void
  4522. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4523. {
  4524. TRACE(("In parent shell: child = %d\n", pid));
  4525. if (!jp) {
  4526. /* jp is NULL when called by openhere() for heredoc support */
  4527. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4528. continue;
  4529. jobless++;
  4530. return;
  4531. }
  4532. #if JOBS
  4533. if (mode != FORK_NOJOB && jp->jobctl) {
  4534. int pgrp;
  4535. if (jp->nprocs == 0)
  4536. pgrp = pid;
  4537. else
  4538. pgrp = jp->ps[0].ps_pid;
  4539. /* This can fail because we are doing it in the child also */
  4540. setpgid(pid, pgrp);
  4541. }
  4542. #endif
  4543. if (mode == FORK_BG) {
  4544. backgndpid = pid; /* set $! */
  4545. set_curjob(jp, CUR_RUNNING);
  4546. }
  4547. if (jp) {
  4548. struct procstat *ps = &jp->ps[jp->nprocs++];
  4549. ps->ps_pid = pid;
  4550. ps->ps_status = -1;
  4551. ps->ps_cmd = nullstr;
  4552. #if JOBS
  4553. if (doing_jobctl && n)
  4554. ps->ps_cmd = commandtext(n);
  4555. #endif
  4556. }
  4557. }
  4558. /* jp and n are NULL when called by openhere() for heredoc support */
  4559. static int
  4560. forkshell(struct job *jp, union node *n, int mode)
  4561. {
  4562. int pid;
  4563. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4564. pid = fork();
  4565. if (pid < 0) {
  4566. TRACE(("Fork failed, errno=%d", errno));
  4567. if (jp)
  4568. freejob(jp);
  4569. ash_msg_and_raise_error("can't fork");
  4570. }
  4571. if (pid == 0) {
  4572. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4573. forkchild(jp, n, mode);
  4574. } else {
  4575. forkparent(jp, n, mode, pid);
  4576. }
  4577. return pid;
  4578. }
  4579. /*
  4580. * Wait for job to finish.
  4581. *
  4582. * Under job control we have the problem that while a child process
  4583. * is running interrupts generated by the user are sent to the child
  4584. * but not to the shell. This means that an infinite loop started by
  4585. * an interactive user may be hard to kill. With job control turned off,
  4586. * an interactive user may place an interactive program inside a loop.
  4587. * If the interactive program catches interrupts, the user doesn't want
  4588. * these interrupts to also abort the loop. The approach we take here
  4589. * is to have the shell ignore interrupt signals while waiting for a
  4590. * foreground process to terminate, and then send itself an interrupt
  4591. * signal if the child process was terminated by an interrupt signal.
  4592. * Unfortunately, some programs want to do a bit of cleanup and then
  4593. * exit on interrupt; unless these processes terminate themselves by
  4594. * sending a signal to themselves (instead of calling exit) they will
  4595. * confuse this approach.
  4596. *
  4597. * Called with interrupts off.
  4598. */
  4599. static int
  4600. waitforjob(struct job *jp)
  4601. {
  4602. int st;
  4603. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4604. INT_OFF;
  4605. while (jp->state == JOBRUNNING) {
  4606. /* In non-interactive shells, we _can_ get
  4607. * a keyboard signal here and be EINTRed,
  4608. * but we just loop back, waiting for command to complete.
  4609. *
  4610. * man bash:
  4611. * "If bash is waiting for a command to complete and receives
  4612. * a signal for which a trap has been set, the trap
  4613. * will not be executed until the command completes."
  4614. *
  4615. * Reality is that even if trap is not set, bash
  4616. * will not act on the signal until command completes.
  4617. * Try this. sleep5intoff.c:
  4618. * #include <signal.h>
  4619. * #include <unistd.h>
  4620. * int main() {
  4621. * sigset_t set;
  4622. * sigemptyset(&set);
  4623. * sigaddset(&set, SIGINT);
  4624. * sigaddset(&set, SIGQUIT);
  4625. * sigprocmask(SIG_BLOCK, &set, NULL);
  4626. * sleep(5);
  4627. * return 0;
  4628. * }
  4629. * $ bash -c './sleep5intoff; echo hi'
  4630. * ^C^C^C^C <--- pressing ^C once a second
  4631. * $ _
  4632. * $ bash -c './sleep5intoff; echo hi'
  4633. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4634. * $ _
  4635. */
  4636. dowait(DOWAIT_BLOCK, jp);
  4637. }
  4638. INT_ON;
  4639. st = getstatus(jp);
  4640. #if JOBS
  4641. if (jp->jobctl) {
  4642. xtcsetpgrp(ttyfd, rootpid);
  4643. restore_tty_if_stopped_or_signaled(jp);
  4644. /*
  4645. * This is truly gross.
  4646. * If we're doing job control, then we did a TIOCSPGRP which
  4647. * caused us (the shell) to no longer be in the controlling
  4648. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4649. * intuit from the subprocess exit status whether a SIGINT
  4650. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4651. */
  4652. if (jp->sigint) /* TODO: do the same with all signals */
  4653. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4654. }
  4655. if (jp->state == JOBDONE)
  4656. #endif
  4657. freejob(jp);
  4658. return st;
  4659. }
  4660. /*
  4661. * return 1 if there are stopped jobs, otherwise 0
  4662. */
  4663. static int
  4664. stoppedjobs(void)
  4665. {
  4666. struct job *jp;
  4667. int retval;
  4668. retval = 0;
  4669. if (job_warning)
  4670. goto out;
  4671. jp = curjob;
  4672. if (jp && jp->state == JOBSTOPPED) {
  4673. out2str("You have stopped jobs.\n");
  4674. job_warning = 2;
  4675. retval++;
  4676. }
  4677. out:
  4678. return retval;
  4679. }
  4680. /*
  4681. * Code for dealing with input/output redirection.
  4682. */
  4683. #undef EMPTY
  4684. #undef CLOSED
  4685. #define EMPTY -2 /* marks an unused slot in redirtab */
  4686. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4687. /*
  4688. * Open a file in noclobber mode.
  4689. * The code was copied from bash.
  4690. */
  4691. static int
  4692. noclobberopen(const char *fname)
  4693. {
  4694. int r, fd;
  4695. struct stat finfo, finfo2;
  4696. /*
  4697. * If the file exists and is a regular file, return an error
  4698. * immediately.
  4699. */
  4700. r = stat(fname, &finfo);
  4701. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4702. errno = EEXIST;
  4703. return -1;
  4704. }
  4705. /*
  4706. * If the file was not present (r != 0), make sure we open it
  4707. * exclusively so that if it is created before we open it, our open
  4708. * will fail. Make sure that we do not truncate an existing file.
  4709. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4710. * file was not a regular file, we leave O_EXCL off.
  4711. */
  4712. if (r != 0)
  4713. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4714. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4715. /* If the open failed, return the file descriptor right away. */
  4716. if (fd < 0)
  4717. return fd;
  4718. /*
  4719. * OK, the open succeeded, but the file may have been changed from a
  4720. * non-regular file to a regular file between the stat and the open.
  4721. * We are assuming that the O_EXCL open handles the case where FILENAME
  4722. * did not exist and is symlinked to an existing file between the stat
  4723. * and open.
  4724. */
  4725. /*
  4726. * If we can open it and fstat the file descriptor, and neither check
  4727. * revealed that it was a regular file, and the file has not been
  4728. * replaced, return the file descriptor.
  4729. */
  4730. if (fstat(fd, &finfo2) == 0
  4731. && !S_ISREG(finfo2.st_mode)
  4732. && finfo.st_dev == finfo2.st_dev
  4733. && finfo.st_ino == finfo2.st_ino
  4734. ) {
  4735. return fd;
  4736. }
  4737. /* The file has been replaced. badness. */
  4738. close(fd);
  4739. errno = EEXIST;
  4740. return -1;
  4741. }
  4742. /*
  4743. * Handle here documents. Normally we fork off a process to write the
  4744. * data to a pipe. If the document is short, we can stuff the data in
  4745. * the pipe without forking.
  4746. */
  4747. /* openhere needs this forward reference */
  4748. static void expandhere(union node *arg, int fd);
  4749. static int
  4750. openhere(union node *redir)
  4751. {
  4752. int pip[2];
  4753. size_t len = 0;
  4754. if (pipe(pip) < 0)
  4755. ash_msg_and_raise_error("pipe call failed");
  4756. if (redir->type == NHERE) {
  4757. len = strlen(redir->nhere.doc->narg.text);
  4758. if (len <= PIPE_BUF) {
  4759. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4760. goto out;
  4761. }
  4762. }
  4763. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4764. /* child */
  4765. close(pip[0]);
  4766. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4767. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4768. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4769. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4770. signal(SIGPIPE, SIG_DFL);
  4771. if (redir->type == NHERE)
  4772. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4773. else /* NXHERE */
  4774. expandhere(redir->nhere.doc, pip[1]);
  4775. _exit(EXIT_SUCCESS);
  4776. }
  4777. out:
  4778. close(pip[1]);
  4779. return pip[0];
  4780. }
  4781. static int
  4782. openredirect(union node *redir)
  4783. {
  4784. char *fname;
  4785. int f;
  4786. switch (redir->nfile.type) {
  4787. /* Can't happen, our single caller does this itself */
  4788. // case NTOFD:
  4789. // case NFROMFD:
  4790. // return -1;
  4791. case NHERE:
  4792. case NXHERE:
  4793. return openhere(redir);
  4794. }
  4795. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4796. * allocated space. Do it only when we know it is safe.
  4797. */
  4798. fname = redir->nfile.expfname;
  4799. switch (redir->nfile.type) {
  4800. default:
  4801. #if DEBUG
  4802. abort();
  4803. #endif
  4804. case NFROM:
  4805. f = open(fname, O_RDONLY);
  4806. if (f < 0)
  4807. goto eopen;
  4808. break;
  4809. case NFROMTO:
  4810. f = open(fname, O_RDWR|O_CREAT, 0666);
  4811. if (f < 0)
  4812. goto ecreate;
  4813. break;
  4814. case NTO:
  4815. #if BASH_REDIR_OUTPUT
  4816. case NTO2:
  4817. #endif
  4818. /* Take care of noclobber mode. */
  4819. if (Cflag) {
  4820. f = noclobberopen(fname);
  4821. if (f < 0)
  4822. goto ecreate;
  4823. break;
  4824. }
  4825. /* FALLTHROUGH */
  4826. case NCLOBBER:
  4827. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4828. if (f < 0)
  4829. goto ecreate;
  4830. break;
  4831. case NAPPEND:
  4832. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4833. if (f < 0)
  4834. goto ecreate;
  4835. break;
  4836. }
  4837. return f;
  4838. ecreate:
  4839. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4840. eopen:
  4841. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4842. }
  4843. /*
  4844. * Copy a file descriptor to be >= 10. Throws exception on error.
  4845. */
  4846. static int
  4847. savefd(int from)
  4848. {
  4849. int newfd;
  4850. int err;
  4851. newfd = fcntl(from, F_DUPFD, 10);
  4852. err = newfd < 0 ? errno : 0;
  4853. if (err != EBADF) {
  4854. if (err)
  4855. ash_msg_and_raise_error("%d: %m", from);
  4856. close(from);
  4857. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4858. }
  4859. return newfd;
  4860. }
  4861. static int
  4862. dup2_or_raise(int from, int to)
  4863. {
  4864. int newfd;
  4865. newfd = (from != to) ? dup2(from, to) : to;
  4866. if (newfd < 0) {
  4867. /* Happens when source fd is not open: try "echo >&99" */
  4868. ash_msg_and_raise_error("%d: %m", from);
  4869. }
  4870. return newfd;
  4871. }
  4872. /* Struct def and variable are moved down to the first usage site */
  4873. struct two_fd_t {
  4874. int orig, copy;
  4875. };
  4876. struct redirtab {
  4877. struct redirtab *next;
  4878. int pair_count;
  4879. struct two_fd_t two_fd[];
  4880. };
  4881. #define redirlist (G_var.redirlist)
  4882. enum {
  4883. COPYFD_RESTORE = (int)~(INT_MAX),
  4884. };
  4885. static int
  4886. need_to_remember(struct redirtab *rp, int fd)
  4887. {
  4888. int i;
  4889. if (!rp) /* remembering was not requested */
  4890. return 0;
  4891. for (i = 0; i < rp->pair_count; i++) {
  4892. if (rp->two_fd[i].orig == fd) {
  4893. /* already remembered */
  4894. return 0;
  4895. }
  4896. }
  4897. return 1;
  4898. }
  4899. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4900. static int
  4901. is_hidden_fd(struct redirtab *rp, int fd)
  4902. {
  4903. int i;
  4904. struct parsefile *pf;
  4905. if (fd == -1)
  4906. return 0;
  4907. /* Check open scripts' fds */
  4908. pf = g_parsefile;
  4909. while (pf) {
  4910. /* We skip pf_fd == 0 case because of the following case:
  4911. * $ ash # running ash interactively
  4912. * $ . ./script.sh
  4913. * and in script.sh: "exec 9>&0".
  4914. * Even though top-level pf_fd _is_ 0,
  4915. * it's still ok to use it: "read" builtin uses it,
  4916. * why should we cripple "exec" builtin?
  4917. */
  4918. if (pf->pf_fd > 0 && fd == pf->pf_fd) {
  4919. return 1;
  4920. }
  4921. pf = pf->prev;
  4922. }
  4923. if (!rp)
  4924. return 0;
  4925. /* Check saved fds of redirects */
  4926. fd |= COPYFD_RESTORE;
  4927. for (i = 0; i < rp->pair_count; i++) {
  4928. if (rp->two_fd[i].copy == fd) {
  4929. return 1;
  4930. }
  4931. }
  4932. return 0;
  4933. }
  4934. /*
  4935. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4936. * old file descriptors are stashed away so that the redirection can be
  4937. * undone by calling popredir.
  4938. */
  4939. /* flags passed to redirect */
  4940. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4941. #define REDIR_SAVEFD2 03 /* set preverrout */
  4942. static void
  4943. redirect(union node *redir, int flags)
  4944. {
  4945. struct redirtab *sv;
  4946. int sv_pos;
  4947. int i;
  4948. int fd;
  4949. int newfd;
  4950. int copied_fd2 = -1;
  4951. if (!redir) {
  4952. return;
  4953. }
  4954. sv = NULL;
  4955. sv_pos = 0;
  4956. INT_OFF;
  4957. if (flags & REDIR_PUSH) {
  4958. union node *tmp = redir;
  4959. do {
  4960. sv_pos++;
  4961. #if BASH_REDIR_OUTPUT
  4962. if (tmp->nfile.type == NTO2)
  4963. sv_pos++;
  4964. #endif
  4965. tmp = tmp->nfile.next;
  4966. } while (tmp);
  4967. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4968. sv->next = redirlist;
  4969. sv->pair_count = sv_pos;
  4970. redirlist = sv;
  4971. while (sv_pos > 0) {
  4972. sv_pos--;
  4973. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4974. }
  4975. }
  4976. do {
  4977. int right_fd = -1;
  4978. fd = redir->nfile.fd;
  4979. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4980. right_fd = redir->ndup.dupfd;
  4981. //bb_error_msg("doing %d > %d", fd, right_fd);
  4982. /* redirect from/to same file descriptor? */
  4983. if (right_fd == fd)
  4984. continue;
  4985. /* "echo >&10" and 10 is a fd opened to a sh script? */
  4986. if (is_hidden_fd(sv, right_fd)) {
  4987. errno = EBADF; /* as if it is closed */
  4988. ash_msg_and_raise_error("%d: %m", right_fd);
  4989. }
  4990. newfd = -1;
  4991. } else {
  4992. newfd = openredirect(redir); /* always >= 0 */
  4993. if (fd == newfd) {
  4994. /* Descriptor wasn't open before redirect.
  4995. * Mark it for close in the future */
  4996. if (need_to_remember(sv, fd)) {
  4997. goto remember_to_close;
  4998. }
  4999. continue;
  5000. }
  5001. }
  5002. #if BASH_REDIR_OUTPUT
  5003. redirect_more:
  5004. #endif
  5005. if (need_to_remember(sv, fd)) {
  5006. /* Copy old descriptor */
  5007. /* Careful to not accidentally "save"
  5008. * to the same fd as right side fd in N>&M */
  5009. int minfd = right_fd < 10 ? 10 : right_fd + 1;
  5010. #if defined(F_DUPFD_CLOEXEC)
  5011. i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
  5012. #else
  5013. i = fcntl(fd, F_DUPFD, minfd);
  5014. #endif
  5015. if (i == -1) {
  5016. i = errno;
  5017. if (i != EBADF) {
  5018. /* Strange error (e.g. "too many files" EMFILE?) */
  5019. if (newfd >= 0)
  5020. close(newfd);
  5021. errno = i;
  5022. ash_msg_and_raise_error("%d: %m", fd);
  5023. /* NOTREACHED */
  5024. }
  5025. /* EBADF: it is not open - good, remember to close it */
  5026. remember_to_close:
  5027. i = CLOSED;
  5028. } else { /* fd is open, save its copy */
  5029. #if !defined(F_DUPFD_CLOEXEC)
  5030. fcntl(i, F_SETFD, FD_CLOEXEC);
  5031. #endif
  5032. /* "exec fd>&-" should not close fds
  5033. * which point to script file(s).
  5034. * Force them to be restored afterwards */
  5035. if (is_hidden_fd(sv, fd))
  5036. i |= COPYFD_RESTORE;
  5037. }
  5038. if (fd == 2)
  5039. copied_fd2 = i;
  5040. sv->two_fd[sv_pos].orig = fd;
  5041. sv->two_fd[sv_pos].copy = i;
  5042. sv_pos++;
  5043. }
  5044. if (newfd < 0) {
  5045. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  5046. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  5047. /* Don't want to trigger debugging */
  5048. if (fd != -1)
  5049. close(fd);
  5050. } else {
  5051. dup2_or_raise(redir->ndup.dupfd, fd);
  5052. }
  5053. } else if (fd != newfd) { /* move newfd to fd */
  5054. dup2_or_raise(newfd, fd);
  5055. #if BASH_REDIR_OUTPUT
  5056. if (!(redir->nfile.type == NTO2 && fd == 2))
  5057. #endif
  5058. close(newfd);
  5059. }
  5060. #if BASH_REDIR_OUTPUT
  5061. if (redir->nfile.type == NTO2 && fd == 1) {
  5062. /* We already redirected it to fd 1, now copy it to 2 */
  5063. newfd = 1;
  5064. fd = 2;
  5065. goto redirect_more;
  5066. }
  5067. #endif
  5068. } while ((redir = redir->nfile.next) != NULL);
  5069. INT_ON;
  5070. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5071. preverrout_fd = copied_fd2;
  5072. }
  5073. /*
  5074. * Undo the effects of the last redirection.
  5075. */
  5076. static void
  5077. popredir(int drop, int restore)
  5078. {
  5079. struct redirtab *rp;
  5080. int i;
  5081. if (redirlist == NULL)
  5082. return;
  5083. INT_OFF;
  5084. rp = redirlist;
  5085. for (i = 0; i < rp->pair_count; i++) {
  5086. int fd = rp->two_fd[i].orig;
  5087. int copy = rp->two_fd[i].copy;
  5088. if (copy == CLOSED) {
  5089. if (!drop)
  5090. close(fd);
  5091. continue;
  5092. }
  5093. if (copy != EMPTY) {
  5094. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  5095. copy &= ~COPYFD_RESTORE;
  5096. /*close(fd);*/
  5097. dup2_or_raise(copy, fd);
  5098. }
  5099. close(copy & ~COPYFD_RESTORE);
  5100. }
  5101. }
  5102. redirlist = rp->next;
  5103. free(rp);
  5104. INT_ON;
  5105. }
  5106. /*
  5107. * Undo all redirections. Called on error or interrupt.
  5108. */
  5109. static int
  5110. redirectsafe(union node *redir, int flags)
  5111. {
  5112. int err;
  5113. volatile int saveint;
  5114. struct jmploc *volatile savehandler = exception_handler;
  5115. struct jmploc jmploc;
  5116. SAVE_INT(saveint);
  5117. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5118. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  5119. if (!err) {
  5120. exception_handler = &jmploc;
  5121. redirect(redir, flags);
  5122. }
  5123. exception_handler = savehandler;
  5124. if (err && exception_type != EXERROR)
  5125. longjmp(exception_handler->loc, 1);
  5126. RESTORE_INT(saveint);
  5127. return err;
  5128. }
  5129. /* ============ Routines to expand arguments to commands
  5130. *
  5131. * We have to deal with backquotes, shell variables, and file metacharacters.
  5132. */
  5133. #if ENABLE_FEATURE_SH_MATH
  5134. static arith_t
  5135. ash_arith(const char *s)
  5136. {
  5137. arith_state_t math_state;
  5138. arith_t result;
  5139. math_state.lookupvar = lookupvar;
  5140. math_state.setvar = setvar0;
  5141. //math_state.endofname = endofname;
  5142. INT_OFF;
  5143. result = arith(&math_state, s);
  5144. if (math_state.errmsg)
  5145. ash_msg_and_raise_error(math_state.errmsg);
  5146. INT_ON;
  5147. return result;
  5148. }
  5149. #endif
  5150. /*
  5151. * expandarg flags
  5152. */
  5153. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5154. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5155. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5156. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5157. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5158. * POSIX says for this case:
  5159. * Pathname expansion shall not be performed on the word by a
  5160. * non-interactive shell; an interactive shell may perform it, but shall
  5161. * do so only when the expansion would result in one word.
  5162. * Currently, our code complies to the above rule by never globbing
  5163. * redirection filenames.
  5164. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5165. * (this means that on a typical Linux distro, bash almost always
  5166. * performs globbing, and thus diverges from what we do).
  5167. */
  5168. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5169. #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
  5170. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5171. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5172. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5173. /*
  5174. * rmescape() flags
  5175. */
  5176. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5177. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5178. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5179. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5180. #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
  5181. /* Add CTLESC when necessary. */
  5182. #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
  5183. /* Do not skip NUL characters. */
  5184. #define QUOTES_KEEPNUL EXP_TILDE
  5185. /*
  5186. * Structure specifying which parts of the string should be searched
  5187. * for IFS characters.
  5188. */
  5189. struct ifsregion {
  5190. struct ifsregion *next; /* next region in list */
  5191. int begoff; /* offset of start of region */
  5192. int endoff; /* offset of end of region */
  5193. int nulonly; /* search for nul bytes only */
  5194. };
  5195. struct arglist {
  5196. struct strlist *list;
  5197. struct strlist **lastp;
  5198. };
  5199. /* output of current string */
  5200. static char *expdest;
  5201. /* list of back quote expressions */
  5202. static struct nodelist *argbackq;
  5203. /* first struct in list of ifs regions */
  5204. static struct ifsregion ifsfirst;
  5205. /* last struct in list */
  5206. static struct ifsregion *ifslastp;
  5207. /* holds expanded arg list */
  5208. static struct arglist exparg;
  5209. /*
  5210. * Our own itoa().
  5211. */
  5212. #if !ENABLE_FEATURE_SH_MATH
  5213. /* cvtnum() is used even if math support is off (to prepare $? values and such) */
  5214. typedef long arith_t;
  5215. # define ARITH_FMT "%ld"
  5216. #endif
  5217. static int
  5218. cvtnum(arith_t num)
  5219. {
  5220. int len;
  5221. expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
  5222. len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
  5223. STADJUST(len, expdest);
  5224. return len;
  5225. }
  5226. /*
  5227. * Break the argument string into pieces based upon IFS and add the
  5228. * strings to the argument list. The regions of the string to be
  5229. * searched for IFS characters have been stored by recordregion.
  5230. */
  5231. static void
  5232. ifsbreakup(char *string, struct arglist *arglist)
  5233. {
  5234. struct ifsregion *ifsp;
  5235. struct strlist *sp;
  5236. char *start;
  5237. char *p;
  5238. char *q;
  5239. const char *ifs, *realifs;
  5240. int ifsspc;
  5241. int nulonly;
  5242. start = string;
  5243. if (ifslastp != NULL) {
  5244. ifsspc = 0;
  5245. nulonly = 0;
  5246. realifs = ifsset() ? ifsval() : defifs;
  5247. ifsp = &ifsfirst;
  5248. do {
  5249. p = string + ifsp->begoff;
  5250. nulonly = ifsp->nulonly;
  5251. ifs = nulonly ? nullstr : realifs;
  5252. ifsspc = 0;
  5253. while (p < string + ifsp->endoff) {
  5254. q = p;
  5255. if ((unsigned char)*p == CTLESC)
  5256. p++;
  5257. if (!strchr(ifs, *p)) {
  5258. p++;
  5259. continue;
  5260. }
  5261. if (!nulonly)
  5262. ifsspc = (strchr(defifs, *p) != NULL);
  5263. /* Ignore IFS whitespace at start */
  5264. if (q == start && ifsspc) {
  5265. p++;
  5266. start = p;
  5267. continue;
  5268. }
  5269. *q = '\0';
  5270. sp = stzalloc(sizeof(*sp));
  5271. sp->text = start;
  5272. *arglist->lastp = sp;
  5273. arglist->lastp = &sp->next;
  5274. p++;
  5275. if (!nulonly) {
  5276. for (;;) {
  5277. if (p >= string + ifsp->endoff) {
  5278. break;
  5279. }
  5280. q = p;
  5281. if ((unsigned char)*p == CTLESC)
  5282. p++;
  5283. if (strchr(ifs, *p) == NULL) {
  5284. p = q;
  5285. break;
  5286. }
  5287. if (strchr(defifs, *p) == NULL) {
  5288. if (ifsspc) {
  5289. p++;
  5290. ifsspc = 0;
  5291. } else {
  5292. p = q;
  5293. break;
  5294. }
  5295. } else
  5296. p++;
  5297. }
  5298. }
  5299. start = p;
  5300. } /* while */
  5301. ifsp = ifsp->next;
  5302. } while (ifsp != NULL);
  5303. if (nulonly)
  5304. goto add;
  5305. }
  5306. if (!*start)
  5307. return;
  5308. add:
  5309. sp = stzalloc(sizeof(*sp));
  5310. sp->text = start;
  5311. *arglist->lastp = sp;
  5312. arglist->lastp = &sp->next;
  5313. }
  5314. static void
  5315. ifsfree(void)
  5316. {
  5317. struct ifsregion *p = ifsfirst.next;
  5318. if (!p)
  5319. goto out;
  5320. INT_OFF;
  5321. do {
  5322. struct ifsregion *ifsp;
  5323. ifsp = p->next;
  5324. free(p);
  5325. p = ifsp;
  5326. } while (p);
  5327. ifsfirst.next = NULL;
  5328. INT_ON;
  5329. out:
  5330. ifslastp = NULL;
  5331. }
  5332. static size_t
  5333. esclen(const char *start, const char *p)
  5334. {
  5335. size_t esc = 0;
  5336. while (p > start && (unsigned char)*--p == CTLESC) {
  5337. esc++;
  5338. }
  5339. return esc;
  5340. }
  5341. /*
  5342. * Remove any CTLESC characters from a string.
  5343. */
  5344. static char *
  5345. rmescapes(char *str, int flag)
  5346. {
  5347. static const char qchars[] ALIGN1 = {
  5348. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5349. char *p, *q, *r;
  5350. unsigned inquotes;
  5351. unsigned protect_against_glob;
  5352. unsigned globbing;
  5353. IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
  5354. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
  5355. if (!p)
  5356. return str;
  5357. q = p;
  5358. r = str;
  5359. if (flag & RMESCAPE_ALLOC) {
  5360. size_t len = p - str;
  5361. size_t fulllen = len + strlen(p) + 1;
  5362. if (flag & RMESCAPE_GROW) {
  5363. int strloc = str - (char *)stackblock();
  5364. r = makestrspace(fulllen, expdest);
  5365. /* p and str may be invalidated by makestrspace */
  5366. str = (char *)stackblock() + strloc;
  5367. p = str + len;
  5368. } else if (flag & RMESCAPE_HEAP) {
  5369. r = ckmalloc(fulllen);
  5370. } else {
  5371. r = stalloc(fulllen);
  5372. }
  5373. q = r;
  5374. if (len > 0) {
  5375. q = (char *)memcpy(q, str, len) + len;
  5376. }
  5377. }
  5378. inquotes = 0;
  5379. globbing = flag & RMESCAPE_GLOB;
  5380. protect_against_glob = globbing;
  5381. while (*p) {
  5382. if ((unsigned char)*p == CTLQUOTEMARK) {
  5383. // Note: both inquotes and protect_against_glob only affect whether
  5384. inquotes = ~inquotes;
  5385. p++;
  5386. protect_against_glob = globbing;
  5387. continue;
  5388. }
  5389. if ((unsigned char)*p == CTLESC) {
  5390. p++;
  5391. #if DEBUG
  5392. if (*p == '\0')
  5393. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5394. #endif
  5395. if (protect_against_glob) {
  5396. *q++ = '\\';
  5397. }
  5398. } else if (*p == '\\' && !inquotes) {
  5399. /* naked back slash */
  5400. protect_against_glob = 0;
  5401. goto copy;
  5402. }
  5403. #if BASH_PATTERN_SUBST
  5404. else if (*p == '/' && slash) {
  5405. /* stop handling globbing and mark location of slash */
  5406. globbing = slash = 0;
  5407. *p = CTLESC;
  5408. }
  5409. #endif
  5410. protect_against_glob = globbing;
  5411. copy:
  5412. *q++ = *p++;
  5413. }
  5414. *q = '\0';
  5415. if (flag & RMESCAPE_GROW) {
  5416. expdest = r;
  5417. STADJUST(q - r + 1, expdest);
  5418. }
  5419. return r;
  5420. }
  5421. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5422. /*
  5423. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5424. *
  5425. * Returns an stalloced string.
  5426. */
  5427. static char *
  5428. preglob(const char *pattern, int flag)
  5429. {
  5430. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
  5431. }
  5432. /*
  5433. * Put a string on the stack.
  5434. */
  5435. static void
  5436. memtodest(const char *p, size_t len, int syntax, int quotes)
  5437. {
  5438. char *q;
  5439. if (!len)
  5440. return;
  5441. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5442. do {
  5443. unsigned char c = *p++;
  5444. if (c) {
  5445. if (quotes & QUOTES_ESC) {
  5446. int n = SIT(c, syntax);
  5447. if (n == CCTL
  5448. || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
  5449. && n == CBACK
  5450. )
  5451. ) {
  5452. USTPUTC(CTLESC, q);
  5453. }
  5454. }
  5455. } else if (!(quotes & QUOTES_KEEPNUL))
  5456. continue;
  5457. USTPUTC(c, q);
  5458. } while (--len);
  5459. expdest = q;
  5460. }
  5461. static size_t
  5462. strtodest(const char *p, int syntax, int quotes)
  5463. {
  5464. size_t len = strlen(p);
  5465. memtodest(p, len, syntax, quotes);
  5466. return len;
  5467. }
  5468. /*
  5469. * Record the fact that we have to scan this region of the
  5470. * string for IFS characters.
  5471. */
  5472. static void
  5473. recordregion(int start, int end, int nulonly)
  5474. {
  5475. struct ifsregion *ifsp;
  5476. if (ifslastp == NULL) {
  5477. ifsp = &ifsfirst;
  5478. } else {
  5479. INT_OFF;
  5480. ifsp = ckzalloc(sizeof(*ifsp));
  5481. /*ifsp->next = NULL; - ckzalloc did it */
  5482. ifslastp->next = ifsp;
  5483. INT_ON;
  5484. }
  5485. ifslastp = ifsp;
  5486. ifslastp->begoff = start;
  5487. ifslastp->endoff = end;
  5488. ifslastp->nulonly = nulonly;
  5489. }
  5490. static void
  5491. removerecordregions(int endoff)
  5492. {
  5493. if (ifslastp == NULL)
  5494. return;
  5495. if (ifsfirst.endoff > endoff) {
  5496. while (ifsfirst.next) {
  5497. struct ifsregion *ifsp;
  5498. INT_OFF;
  5499. ifsp = ifsfirst.next->next;
  5500. free(ifsfirst.next);
  5501. ifsfirst.next = ifsp;
  5502. INT_ON;
  5503. }
  5504. if (ifsfirst.begoff > endoff) {
  5505. ifslastp = NULL;
  5506. } else {
  5507. ifslastp = &ifsfirst;
  5508. ifsfirst.endoff = endoff;
  5509. }
  5510. return;
  5511. }
  5512. ifslastp = &ifsfirst;
  5513. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5514. ifslastp = ifslastp->next;
  5515. while (ifslastp->next) {
  5516. struct ifsregion *ifsp;
  5517. INT_OFF;
  5518. ifsp = ifslastp->next->next;
  5519. free(ifslastp->next);
  5520. ifslastp->next = ifsp;
  5521. INT_ON;
  5522. }
  5523. if (ifslastp->endoff > endoff)
  5524. ifslastp->endoff = endoff;
  5525. }
  5526. static char *
  5527. exptilde(char *startp, char *p, int flags)
  5528. {
  5529. unsigned char c;
  5530. char *name;
  5531. struct passwd *pw;
  5532. const char *home;
  5533. int quotes = flags & QUOTES_ESC;
  5534. name = p + 1;
  5535. while ((c = *++p) != '\0') {
  5536. switch (c) {
  5537. case CTLESC:
  5538. return startp;
  5539. case CTLQUOTEMARK:
  5540. return startp;
  5541. case ':':
  5542. if (flags & EXP_VARTILDE)
  5543. goto done;
  5544. break;
  5545. case '/':
  5546. case CTLENDVAR:
  5547. goto done;
  5548. }
  5549. }
  5550. done:
  5551. *p = '\0';
  5552. if (*name == '\0') {
  5553. home = lookupvar("HOME");
  5554. } else {
  5555. pw = getpwnam(name);
  5556. if (pw == NULL)
  5557. goto lose;
  5558. home = pw->pw_dir;
  5559. }
  5560. if (!home || !*home)
  5561. goto lose;
  5562. *p = c;
  5563. strtodest(home, SQSYNTAX, quotes);
  5564. return p;
  5565. lose:
  5566. *p = c;
  5567. return startp;
  5568. }
  5569. /*
  5570. * Execute a command inside back quotes. If it's a builtin command, we
  5571. * want to save its output in a block obtained from malloc. Otherwise
  5572. * we fork off a subprocess and get the output of the command via a pipe.
  5573. * Should be called with interrupts off.
  5574. */
  5575. struct backcmd { /* result of evalbackcmd */
  5576. int fd; /* file descriptor to read from */
  5577. int nleft; /* number of chars in buffer */
  5578. char *buf; /* buffer */
  5579. struct job *jp; /* job structure for command */
  5580. };
  5581. /* These forward decls are needed to use "eval" code for backticks handling: */
  5582. #define EV_EXIT 01 /* exit after evaluating tree */
  5583. static int evaltree(union node *, int);
  5584. static void FAST_FUNC
  5585. evalbackcmd(union node *n, struct backcmd *result)
  5586. {
  5587. int pip[2];
  5588. struct job *jp;
  5589. result->fd = -1;
  5590. result->buf = NULL;
  5591. result->nleft = 0;
  5592. result->jp = NULL;
  5593. if (n == NULL) {
  5594. goto out;
  5595. }
  5596. if (pipe(pip) < 0)
  5597. ash_msg_and_raise_error("pipe call failed");
  5598. jp = makejob(/*n,*/ 1);
  5599. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5600. /* child */
  5601. FORCE_INT_ON;
  5602. close(pip[0]);
  5603. if (pip[1] != 1) {
  5604. /*close(1);*/
  5605. dup2_or_raise(pip[1], 1);
  5606. close(pip[1]);
  5607. }
  5608. /* TODO: eflag clearing makes the following not abort:
  5609. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5610. * which is what bash does (unless it is in POSIX mode).
  5611. * dash deleted "eflag = 0" line in the commit
  5612. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5613. * [EVAL] Don't clear eflag in evalbackcmd
  5614. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5615. */
  5616. eflag = 0;
  5617. ifsfree();
  5618. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5619. /* NOTREACHED */
  5620. }
  5621. /* parent */
  5622. close(pip[1]);
  5623. result->fd = pip[0];
  5624. result->jp = jp;
  5625. out:
  5626. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5627. result->fd, result->buf, result->nleft, result->jp));
  5628. }
  5629. /*
  5630. * Expand stuff in backwards quotes.
  5631. */
  5632. static void
  5633. expbackq(union node *cmd, int flag)
  5634. {
  5635. struct backcmd in;
  5636. int i;
  5637. char buf[128];
  5638. char *p;
  5639. char *dest;
  5640. int startloc;
  5641. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5642. struct stackmark smark;
  5643. INT_OFF;
  5644. startloc = expdest - (char *)stackblock();
  5645. pushstackmark(&smark, startloc);
  5646. evalbackcmd(cmd, &in);
  5647. popstackmark(&smark);
  5648. p = in.buf;
  5649. i = in.nleft;
  5650. if (i == 0)
  5651. goto read;
  5652. for (;;) {
  5653. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5654. read:
  5655. if (in.fd < 0)
  5656. break;
  5657. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5658. TRACE(("expbackq: read returns %d\n", i));
  5659. if (i <= 0)
  5660. break;
  5661. p = buf;
  5662. }
  5663. free(in.buf);
  5664. if (in.fd >= 0) {
  5665. close(in.fd);
  5666. back_exitstatus = waitforjob(in.jp);
  5667. }
  5668. INT_ON;
  5669. /* Eat all trailing newlines */
  5670. dest = expdest;
  5671. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5672. STUNPUTC(dest);
  5673. expdest = dest;
  5674. if (!(flag & EXP_QUOTED))
  5675. recordregion(startloc, dest - (char *)stackblock(), 0);
  5676. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5677. (int)((dest - (char *)stackblock()) - startloc),
  5678. (int)((dest - (char *)stackblock()) - startloc),
  5679. stackblock() + startloc));
  5680. }
  5681. #if ENABLE_FEATURE_SH_MATH
  5682. /*
  5683. * Expand arithmetic expression. Backup to start of expression,
  5684. * evaluate, place result in (backed up) result, adjust string position.
  5685. */
  5686. static void
  5687. expari(int flag)
  5688. {
  5689. char *p, *start;
  5690. int begoff;
  5691. int len;
  5692. /* ifsfree(); */
  5693. /*
  5694. * This routine is slightly over-complicated for
  5695. * efficiency. Next we scan backwards looking for the
  5696. * start of arithmetic.
  5697. */
  5698. start = stackblock();
  5699. p = expdest - 1;
  5700. *p = '\0';
  5701. p--;
  5702. while (1) {
  5703. int esc;
  5704. while ((unsigned char)*p != CTLARI) {
  5705. p--;
  5706. #if DEBUG
  5707. if (p < start) {
  5708. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5709. }
  5710. #endif
  5711. }
  5712. esc = esclen(start, p);
  5713. if (!(esc % 2)) {
  5714. break;
  5715. }
  5716. p -= esc + 1;
  5717. }
  5718. begoff = p - start;
  5719. removerecordregions(begoff);
  5720. expdest = p;
  5721. if (flag & QUOTES_ESC)
  5722. rmescapes(p + 1, 0);
  5723. len = cvtnum(ash_arith(p + 1));
  5724. if (!(flag & EXP_QUOTED))
  5725. recordregion(begoff, begoff + len, 0);
  5726. }
  5727. #endif
  5728. /* argstr needs it */
  5729. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5730. /*
  5731. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5732. * characters to allow for further processing. Otherwise treat
  5733. * $@ like $* since no splitting will be performed.
  5734. *
  5735. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5736. * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
  5737. * for correct expansion of "B=$A" word.
  5738. */
  5739. static void
  5740. argstr(char *p, int flags, struct strlist *var_str_list)
  5741. {
  5742. static const char spclchars[] ALIGN1 = {
  5743. '=',
  5744. ':',
  5745. CTLQUOTEMARK,
  5746. CTLENDVAR,
  5747. CTLESC,
  5748. CTLVAR,
  5749. CTLBACKQ,
  5750. #if ENABLE_FEATURE_SH_MATH
  5751. CTLENDARI,
  5752. #endif
  5753. '\0'
  5754. };
  5755. const char *reject = spclchars;
  5756. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5757. int inquotes;
  5758. size_t length;
  5759. int startloc;
  5760. if (!(flags & EXP_VARTILDE)) {
  5761. reject += 2;
  5762. } else if (flags & EXP_VARTILDE2) {
  5763. reject++;
  5764. }
  5765. inquotes = 0;
  5766. length = 0;
  5767. if (flags & EXP_TILDE) {
  5768. char *q;
  5769. flags &= ~EXP_TILDE;
  5770. tilde:
  5771. q = p;
  5772. if (*q == '~')
  5773. p = exptilde(p, q, flags);
  5774. }
  5775. start:
  5776. startloc = expdest - (char *)stackblock();
  5777. for (;;) {
  5778. unsigned char c;
  5779. length += strcspn(p + length, reject);
  5780. c = p[length];
  5781. if (c) {
  5782. if (!(c & 0x80)
  5783. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  5784. ) {
  5785. /* c == '=' || c == ':' || c == CTLENDARI */
  5786. length++;
  5787. }
  5788. }
  5789. if (length > 0) {
  5790. int newloc;
  5791. expdest = stack_nputstr(p, length, expdest);
  5792. newloc = expdest - (char *)stackblock();
  5793. if (breakall && !inquotes && newloc > startloc) {
  5794. recordregion(startloc, newloc, 0);
  5795. }
  5796. startloc = newloc;
  5797. }
  5798. p += length + 1;
  5799. length = 0;
  5800. switch (c) {
  5801. case '\0':
  5802. goto breakloop;
  5803. case '=':
  5804. if (flags & EXP_VARTILDE2) {
  5805. p--;
  5806. continue;
  5807. }
  5808. flags |= EXP_VARTILDE2;
  5809. reject++;
  5810. /* fall through */
  5811. case ':':
  5812. /*
  5813. * sort of a hack - expand tildes in variable
  5814. * assignments (after the first '=' and after ':'s).
  5815. */
  5816. if (*--p == '~') {
  5817. goto tilde;
  5818. }
  5819. continue;
  5820. }
  5821. switch (c) {
  5822. case CTLENDVAR: /* ??? */
  5823. goto breakloop;
  5824. case CTLQUOTEMARK:
  5825. inquotes ^= EXP_QUOTED;
  5826. /* "$@" syntax adherence hack */
  5827. if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  5828. p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
  5829. goto start;
  5830. }
  5831. addquote:
  5832. if (flags & QUOTES_ESC) {
  5833. p--;
  5834. length++;
  5835. startloc++;
  5836. }
  5837. break;
  5838. case CTLESC:
  5839. startloc++;
  5840. length++;
  5841. /*
  5842. * Quoted parameter expansion pattern: remove quote
  5843. * unless inside inner quotes or we have a literal
  5844. * backslash.
  5845. */
  5846. if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
  5847. EXP_QPAT && *p != '\\')
  5848. break;
  5849. goto addquote;
  5850. case CTLVAR:
  5851. TRACE(("argstr: evalvar('%s')\n", p));
  5852. p = evalvar(p, flags | inquotes, var_str_list);
  5853. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  5854. goto start;
  5855. case CTLBACKQ:
  5856. expbackq(argbackq->n, flags | inquotes);
  5857. argbackq = argbackq->next;
  5858. goto start;
  5859. #if ENABLE_FEATURE_SH_MATH
  5860. case CTLENDARI:
  5861. p--;
  5862. expari(flags | inquotes);
  5863. goto start;
  5864. #endif
  5865. }
  5866. }
  5867. breakloop: ;
  5868. }
  5869. static char *
  5870. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  5871. char *pattern, int quotes, int zero)
  5872. {
  5873. char *loc, *loc2;
  5874. char c;
  5875. loc = startp;
  5876. loc2 = rmesc;
  5877. do {
  5878. int match;
  5879. const char *s = loc2;
  5880. c = *loc2;
  5881. if (zero) {
  5882. *loc2 = '\0';
  5883. s = rmesc;
  5884. }
  5885. match = pmatch(pattern, s);
  5886. *loc2 = c;
  5887. if (match)
  5888. return loc;
  5889. if (quotes && (unsigned char)*loc == CTLESC)
  5890. loc++;
  5891. loc++;
  5892. loc2++;
  5893. } while (c);
  5894. return NULL;
  5895. }
  5896. static char *
  5897. scanright(char *startp, char *rmesc, char *rmescend,
  5898. char *pattern, int quotes, int match_at_start)
  5899. {
  5900. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5901. int try2optimize = match_at_start;
  5902. #endif
  5903. int esc = 0;
  5904. char *loc;
  5905. char *loc2;
  5906. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5907. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5908. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5909. * Logic:
  5910. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5911. * and on each iteration they go back two/one char until they reach the beginning.
  5912. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5913. */
  5914. /* TODO: document in what other circumstances we are called. */
  5915. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5916. int match;
  5917. char c = *loc2;
  5918. const char *s = loc2;
  5919. if (match_at_start) {
  5920. *loc2 = '\0';
  5921. s = rmesc;
  5922. }
  5923. match = pmatch(pattern, s);
  5924. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5925. *loc2 = c;
  5926. if (match)
  5927. return loc;
  5928. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5929. if (try2optimize) {
  5930. /* Maybe we can optimize this:
  5931. * if pattern ends with unescaped *, we can avoid checking
  5932. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  5933. * it won't match truncated "raw_value_of_" strings too.
  5934. */
  5935. unsigned plen = strlen(pattern);
  5936. /* Does it end with "*"? */
  5937. if (plen != 0 && pattern[--plen] == '*') {
  5938. /* "xxxx*" is not escaped */
  5939. /* "xxx\*" is escaped */
  5940. /* "xx\\*" is not escaped */
  5941. /* "x\\\*" is escaped */
  5942. int slashes = 0;
  5943. while (plen != 0 && pattern[--plen] == '\\')
  5944. slashes++;
  5945. if (!(slashes & 1))
  5946. break; /* ends with unescaped "*" */
  5947. }
  5948. try2optimize = 0;
  5949. }
  5950. #endif
  5951. loc--;
  5952. if (quotes) {
  5953. if (--esc < 0) {
  5954. esc = esclen(startp, loc);
  5955. }
  5956. if (esc % 2) {
  5957. esc--;
  5958. loc--;
  5959. }
  5960. }
  5961. }
  5962. return NULL;
  5963. }
  5964. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5965. static void
  5966. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5967. {
  5968. const char *msg;
  5969. const char *tail;
  5970. tail = nullstr;
  5971. msg = "parameter not set";
  5972. if (umsg) {
  5973. if ((unsigned char)*end == CTLENDVAR) {
  5974. if (varflags & VSNUL)
  5975. tail = " or null";
  5976. } else {
  5977. msg = umsg;
  5978. }
  5979. }
  5980. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  5981. }
  5982. static const char *
  5983. subevalvar(char *p, char *varname, int strloc, int subtype,
  5984. int startloc, int varflags, int flag, struct strlist *var_str_list)
  5985. {
  5986. struct nodelist *saveargbackq = argbackq;
  5987. int quotes = flag & QUOTES_ESC;
  5988. char *startp;
  5989. char *loc;
  5990. char *rmesc, *rmescend;
  5991. char *str;
  5992. IF_BASH_SUBSTR(int pos, len, orig_len;)
  5993. int amount, resetloc;
  5994. IF_BASH_PATTERN_SUBST(int workloc;)
  5995. IF_BASH_PATTERN_SUBST(char *repl = NULL;)
  5996. int zero;
  5997. char *(*scan)(char*, char*, char*, char*, int, int);
  5998. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  5999. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6000. argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
  6001. (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
  6002. var_str_list);
  6003. STPUTC('\0', expdest);
  6004. argbackq = saveargbackq;
  6005. startp = (char *)stackblock() + startloc;
  6006. switch (subtype) {
  6007. case VSASSIGN:
  6008. setvar0(varname, startp);
  6009. amount = startp - expdest;
  6010. STADJUST(amount, expdest);
  6011. return startp;
  6012. case VSQUESTION:
  6013. varunset(p, varname, startp, varflags);
  6014. /* NOTREACHED */
  6015. #if BASH_SUBSTR
  6016. case VSSUBSTR:
  6017. //TODO: support more general format ${v:EXPR:EXPR},
  6018. // where EXPR follows $(()) rules
  6019. loc = str = stackblock() + strloc;
  6020. /* Read POS in ${var:POS:LEN} */
  6021. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  6022. len = str - startp - 1;
  6023. /* *loc != '\0', guaranteed by parser */
  6024. if (quotes) {
  6025. char *ptr;
  6026. /* Adjust the length by the number of escapes */
  6027. for (ptr = startp; ptr < (str - 1); ptr++) {
  6028. if ((unsigned char)*ptr == CTLESC) {
  6029. len--;
  6030. ptr++;
  6031. }
  6032. }
  6033. }
  6034. orig_len = len;
  6035. if (*loc++ == ':') {
  6036. /* ${var::LEN} */
  6037. len = number(loc);
  6038. } else {
  6039. /* Skip POS in ${var:POS:LEN} */
  6040. len = orig_len;
  6041. while (*loc && *loc != ':') {
  6042. /* TODO?
  6043. * bash complains on: var=qwe; echo ${var:1a:123}
  6044. if (!isdigit(*loc))
  6045. ash_msg_and_raise_error(msg_illnum, str);
  6046. */
  6047. loc++;
  6048. }
  6049. if (*loc++ == ':') {
  6050. len = number(loc);
  6051. }
  6052. }
  6053. if (pos < 0) {
  6054. /* ${VAR:$((-n)):l} starts n chars from the end */
  6055. pos = orig_len + pos;
  6056. }
  6057. if ((unsigned)pos >= orig_len) {
  6058. /* apart from obvious ${VAR:999999:l},
  6059. * covers ${VAR:$((-9999999)):l} - result is ""
  6060. * (bash-compat)
  6061. */
  6062. pos = 0;
  6063. len = 0;
  6064. }
  6065. if (len > (orig_len - pos))
  6066. len = orig_len - pos;
  6067. for (str = startp; pos; str++, pos--) {
  6068. if (quotes && (unsigned char)*str == CTLESC)
  6069. str++;
  6070. }
  6071. for (loc = startp; len; len--) {
  6072. if (quotes && (unsigned char)*str == CTLESC)
  6073. *loc++ = *str++;
  6074. *loc++ = *str++;
  6075. }
  6076. *loc = '\0';
  6077. amount = loc - expdest;
  6078. STADJUST(amount, expdest);
  6079. return loc;
  6080. #endif /* BASH_SUBSTR */
  6081. }
  6082. resetloc = expdest - (char *)stackblock();
  6083. #if BASH_PATTERN_SUBST
  6084. /* We'll comeback here if we grow the stack while handling
  6085. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6086. * stack will need rebasing, and we'll need to remove our work
  6087. * areas each time
  6088. */
  6089. restart:
  6090. #endif
  6091. amount = expdest - ((char *)stackblock() + resetloc);
  6092. STADJUST(-amount, expdest);
  6093. startp = (char *)stackblock() + startloc;
  6094. rmesc = startp;
  6095. rmescend = (char *)stackblock() + strloc;
  6096. if (quotes) {
  6097. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  6098. if (rmesc != startp) {
  6099. rmescend = expdest;
  6100. startp = (char *)stackblock() + startloc;
  6101. }
  6102. }
  6103. rmescend--;
  6104. str = (char *)stackblock() + strloc;
  6105. /*
  6106. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6107. * The result is a_\_z_c (not a\_\_z_c)!
  6108. *
  6109. * The search pattern and replace string treat backslashes differently!
  6110. * RMESCAPE_SLASH causes preglob to work differently on the pattern
  6111. * and string. It's only used on the first call.
  6112. */
  6113. preglob(str, IF_BASH_PATTERN_SUBST(
  6114. (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
  6115. RMESCAPE_SLASH : ) 0);
  6116. #if BASH_PATTERN_SUBST
  6117. workloc = expdest - (char *)stackblock();
  6118. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6119. char *idx, *end;
  6120. if (!repl) {
  6121. repl = strchr(str, CTLESC);
  6122. if (repl)
  6123. *repl++ = '\0';
  6124. else
  6125. repl = nullstr;
  6126. }
  6127. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6128. /* If there's no pattern to match, return the expansion unmolested */
  6129. if (str[0] == '\0')
  6130. return NULL;
  6131. len = 0;
  6132. idx = startp;
  6133. end = str - 1;
  6134. while (idx < end) {
  6135. try_to_match:
  6136. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6137. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6138. if (!loc) {
  6139. /* No match, advance */
  6140. char *restart_detect = stackblock();
  6141. skip_matching:
  6142. STPUTC(*idx, expdest);
  6143. if (quotes && (unsigned char)*idx == CTLESC) {
  6144. idx++;
  6145. len++;
  6146. STPUTC(*idx, expdest);
  6147. }
  6148. if (stackblock() != restart_detect)
  6149. goto restart;
  6150. idx++;
  6151. len++;
  6152. rmesc++;
  6153. /* continue; - prone to quadratic behavior, smarter code: */
  6154. if (idx >= end)
  6155. break;
  6156. if (str[0] == '*') {
  6157. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6158. * it would never match "ong_string" etc, no point in trying.
  6159. */
  6160. goto skip_matching;
  6161. }
  6162. goto try_to_match;
  6163. }
  6164. if (subtype == VSREPLACEALL) {
  6165. while (idx < loc) {
  6166. if (quotes && (unsigned char)*idx == CTLESC)
  6167. idx++;
  6168. idx++;
  6169. rmesc++;
  6170. }
  6171. } else {
  6172. idx = loc;
  6173. }
  6174. //bb_error_msg("repl:'%s'", repl);
  6175. for (loc = (char*)repl; *loc; loc++) {
  6176. char *restart_detect = stackblock();
  6177. if (quotes && *loc == '\\') {
  6178. STPUTC(CTLESC, expdest);
  6179. len++;
  6180. }
  6181. STPUTC(*loc, expdest);
  6182. if (stackblock() != restart_detect)
  6183. goto restart;
  6184. len++;
  6185. }
  6186. if (subtype == VSREPLACE) {
  6187. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6188. while (*idx) {
  6189. char *restart_detect = stackblock();
  6190. STPUTC(*idx, expdest);
  6191. if (stackblock() != restart_detect)
  6192. goto restart;
  6193. len++;
  6194. idx++;
  6195. }
  6196. break;
  6197. }
  6198. }
  6199. /* We've put the replaced text into a buffer at workloc, now
  6200. * move it to the right place and adjust the stack.
  6201. */
  6202. STPUTC('\0', expdest);
  6203. startp = (char *)stackblock() + startloc;
  6204. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6205. //bb_error_msg("startp:'%s'", startp);
  6206. amount = expdest - (startp + len);
  6207. STADJUST(-amount, expdest);
  6208. return startp;
  6209. }
  6210. #endif /* BASH_PATTERN_SUBST */
  6211. subtype -= VSTRIMRIGHT;
  6212. #if DEBUG
  6213. if (subtype < 0 || subtype > 7)
  6214. abort();
  6215. #endif
  6216. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6217. zero = subtype >> 1;
  6218. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6219. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6220. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6221. if (loc) {
  6222. if (zero) {
  6223. memmove(startp, loc, str - loc);
  6224. loc = startp + (str - loc) - 1;
  6225. }
  6226. *loc = '\0';
  6227. amount = loc - expdest;
  6228. STADJUST(amount, expdest);
  6229. }
  6230. return loc;
  6231. }
  6232. /*
  6233. * Add the value of a specialized variable to the stack string.
  6234. * name parameter (examples):
  6235. * ash -c 'echo $1' name:'1='
  6236. * ash -c 'echo $qwe' name:'qwe='
  6237. * ash -c 'echo $$' name:'$='
  6238. * ash -c 'echo ${$}' name:'$='
  6239. * ash -c 'echo ${$##q}' name:'$=q'
  6240. * ash -c 'echo ${#$}' name:'$='
  6241. * note: examples with bad shell syntax:
  6242. * ash -c 'echo ${#$1}' name:'$=1'
  6243. * ash -c 'echo ${#1#}' name:'1=#'
  6244. */
  6245. static NOINLINE ssize_t
  6246. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
  6247. {
  6248. const char *p;
  6249. int num;
  6250. int i;
  6251. ssize_t len = 0;
  6252. int sep;
  6253. int quoted = *quotedp;
  6254. int subtype = varflags & VSTYPE;
  6255. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6256. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6257. int syntax;
  6258. sep = (flags & EXP_FULL) << CHAR_BIT;
  6259. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6260. switch (*name) {
  6261. case '$':
  6262. num = rootpid;
  6263. goto numvar;
  6264. case '?':
  6265. num = exitstatus;
  6266. goto numvar;
  6267. case '#':
  6268. num = shellparam.nparam;
  6269. goto numvar;
  6270. case '!':
  6271. num = backgndpid;
  6272. if (num == 0)
  6273. return -1;
  6274. numvar:
  6275. len = cvtnum(num);
  6276. goto check_1char_name;
  6277. case '-':
  6278. expdest = makestrspace(NOPTS, expdest);
  6279. for (i = NOPTS - 1; i >= 0; i--) {
  6280. if (optlist[i]) {
  6281. USTPUTC(optletters(i), expdest);
  6282. len++;
  6283. }
  6284. }
  6285. check_1char_name:
  6286. #if 0
  6287. /* handles cases similar to ${#$1} */
  6288. if (name[2] != '\0')
  6289. raise_error_syntax("bad substitution");
  6290. #endif
  6291. break;
  6292. case '@':
  6293. if (quoted && sep)
  6294. goto param;
  6295. /* fall through */
  6296. case '*': {
  6297. char **ap;
  6298. char sepc;
  6299. if (quoted)
  6300. sep = 0;
  6301. sep |= ifsset() ? ifsval()[0] : ' ';
  6302. param:
  6303. sepc = sep;
  6304. *quotedp = !sepc;
  6305. ap = shellparam.p;
  6306. if (!ap)
  6307. return -1;
  6308. while ((p = *ap++) != NULL) {
  6309. len += strtodest(p, syntax, quotes);
  6310. if (*ap && sep) {
  6311. len++;
  6312. memtodest(&sepc, 1, syntax, quotes);
  6313. }
  6314. }
  6315. break;
  6316. } /* case '*' */
  6317. case '0':
  6318. case '1':
  6319. case '2':
  6320. case '3':
  6321. case '4':
  6322. case '5':
  6323. case '6':
  6324. case '7':
  6325. case '8':
  6326. case '9':
  6327. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6328. if (num < 0 || num > shellparam.nparam)
  6329. return -1;
  6330. p = num ? shellparam.p[num - 1] : arg0;
  6331. goto value;
  6332. default:
  6333. /* NB: name has form "VAR=..." */
  6334. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  6335. * which should be considered before we check variables. */
  6336. if (var_str_list) {
  6337. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  6338. p = NULL;
  6339. do {
  6340. char *str, *eq;
  6341. str = var_str_list->text;
  6342. eq = strchr(str, '=');
  6343. if (!eq) /* stop at first non-assignment */
  6344. break;
  6345. eq++;
  6346. if (name_len == (unsigned)(eq - str)
  6347. && strncmp(str, name, name_len) == 0
  6348. ) {
  6349. p = eq;
  6350. /* goto value; - WRONG! */
  6351. /* think "A=1 A=2 B=$A" */
  6352. }
  6353. var_str_list = var_str_list->next;
  6354. } while (var_str_list);
  6355. if (p)
  6356. goto value;
  6357. }
  6358. p = lookupvar(name);
  6359. value:
  6360. if (!p)
  6361. return -1;
  6362. len = strtodest(p, syntax, quotes);
  6363. #if ENABLE_UNICODE_SUPPORT
  6364. if (subtype == VSLENGTH && len > 0) {
  6365. reinit_unicode_for_ash();
  6366. if (unicode_status == UNICODE_ON) {
  6367. STADJUST(-len, expdest);
  6368. discard = 0;
  6369. len = unicode_strlen(p);
  6370. }
  6371. }
  6372. #endif
  6373. break;
  6374. }
  6375. if (discard)
  6376. STADJUST(-len, expdest);
  6377. return len;
  6378. }
  6379. /*
  6380. * Expand a variable, and return a pointer to the next character in the
  6381. * input string.
  6382. */
  6383. static char *
  6384. evalvar(char *p, int flag, struct strlist *var_str_list)
  6385. {
  6386. char varflags;
  6387. char subtype;
  6388. int quoted;
  6389. char easy;
  6390. char *var;
  6391. int patloc;
  6392. int startloc;
  6393. ssize_t varlen;
  6394. varflags = (unsigned char) *p++;
  6395. subtype = varflags & VSTYPE;
  6396. if (!subtype)
  6397. raise_error_syntax("bad substitution");
  6398. quoted = flag & EXP_QUOTED;
  6399. var = p;
  6400. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6401. startloc = expdest - (char *)stackblock();
  6402. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6403. again:
  6404. varlen = varvalue(var, varflags, flag, var_str_list, &quoted);
  6405. if (varflags & VSNUL)
  6406. varlen--;
  6407. if (subtype == VSPLUS) {
  6408. varlen = -1 - varlen;
  6409. goto vsplus;
  6410. }
  6411. if (subtype == VSMINUS) {
  6412. vsplus:
  6413. if (varlen < 0) {
  6414. argstr(
  6415. p,
  6416. flag | EXP_TILDE | EXP_WORD,
  6417. var_str_list
  6418. );
  6419. goto end;
  6420. }
  6421. goto record;
  6422. }
  6423. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6424. if (varlen >= 0)
  6425. goto record;
  6426. subevalvar(p, var, 0, subtype, startloc, varflags,
  6427. flag & ~QUOTES_ESC, var_str_list);
  6428. varflags &= ~VSNUL;
  6429. /*
  6430. * Remove any recorded regions beyond
  6431. * start of variable
  6432. */
  6433. removerecordregions(startloc);
  6434. goto again;
  6435. }
  6436. if (varlen < 0 && uflag)
  6437. varunset(p, var, 0, 0);
  6438. if (subtype == VSLENGTH) {
  6439. cvtnum(varlen > 0 ? varlen : 0);
  6440. goto record;
  6441. }
  6442. if (subtype == VSNORMAL) {
  6443. record:
  6444. if (!easy)
  6445. goto end;
  6446. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6447. goto end;
  6448. }
  6449. #if DEBUG
  6450. switch (subtype) {
  6451. case VSTRIMLEFT:
  6452. case VSTRIMLEFTMAX:
  6453. case VSTRIMRIGHT:
  6454. case VSTRIMRIGHTMAX:
  6455. #if BASH_SUBSTR
  6456. case VSSUBSTR:
  6457. #endif
  6458. #if BASH_PATTERN_SUBST
  6459. case VSREPLACE:
  6460. case VSREPLACEALL:
  6461. #endif
  6462. break;
  6463. default:
  6464. abort();
  6465. }
  6466. #endif
  6467. if (varlen >= 0) {
  6468. /*
  6469. * Terminate the string and start recording the pattern
  6470. * right after it
  6471. */
  6472. STPUTC('\0', expdest);
  6473. patloc = expdest - (char *)stackblock();
  6474. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6475. startloc, varflags, flag, var_str_list)) {
  6476. int amount = expdest - (
  6477. (char *)stackblock() + patloc - 1
  6478. );
  6479. STADJUST(-amount, expdest);
  6480. }
  6481. /* Remove any recorded regions beyond start of variable */
  6482. removerecordregions(startloc);
  6483. goto record;
  6484. }
  6485. end:
  6486. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6487. int nesting = 1;
  6488. for (;;) {
  6489. unsigned char c = *p++;
  6490. if (c == CTLESC)
  6491. p++;
  6492. else if (c == CTLBACKQ) {
  6493. if (varlen >= 0)
  6494. argbackq = argbackq->next;
  6495. } else if (c == CTLVAR) {
  6496. if ((*p++ & VSTYPE) != VSNORMAL)
  6497. nesting++;
  6498. } else if (c == CTLENDVAR) {
  6499. if (--nesting == 0)
  6500. break;
  6501. }
  6502. }
  6503. }
  6504. return p;
  6505. }
  6506. /*
  6507. * Add a file name to the list.
  6508. */
  6509. static void
  6510. addfname(const char *name)
  6511. {
  6512. struct strlist *sp;
  6513. sp = stzalloc(sizeof(*sp));
  6514. sp->text = sstrdup(name);
  6515. *exparg.lastp = sp;
  6516. exparg.lastp = &sp->next;
  6517. }
  6518. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6519. static int
  6520. hasmeta(const char *p)
  6521. {
  6522. static const char chars[] ALIGN1 = {
  6523. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6524. };
  6525. for (;;) {
  6526. p = strpbrk(p, chars);
  6527. if (!p)
  6528. break;
  6529. switch ((unsigned char) *p) {
  6530. case CTLQUOTEMARK:
  6531. for (;;) {
  6532. p++;
  6533. if (*p == CTLQUOTEMARK)
  6534. break;
  6535. if (*p == CTLESC)
  6536. p++;
  6537. if (*p == '\0') /* huh? */
  6538. return 0;
  6539. }
  6540. break;
  6541. case '\\':
  6542. case CTLESC:
  6543. p++;
  6544. if (*p == '\0')
  6545. return 0;
  6546. break;
  6547. case '[':
  6548. if (!strchr(p + 1, ']')) {
  6549. /* It's not a properly closed [] pattern,
  6550. * but other metas may follow. Continue checking.
  6551. * my[file* _is_ globbed by bash
  6552. * and matches filenames like "my[file1".
  6553. */
  6554. break;
  6555. }
  6556. /* fallthrough */
  6557. default:
  6558. /* case '*': */
  6559. /* case '?': */
  6560. return 1;
  6561. }
  6562. p++;
  6563. }
  6564. return 0;
  6565. }
  6566. /* If we want to use glob() from libc... */
  6567. #if !ENABLE_ASH_INTERNAL_GLOB
  6568. /* Add the result of glob() to the list */
  6569. static void
  6570. addglob(const glob_t *pglob)
  6571. {
  6572. char **p = pglob->gl_pathv;
  6573. do {
  6574. addfname(*p);
  6575. } while (*++p);
  6576. }
  6577. static void
  6578. expandmeta(struct strlist *str /*, int flag*/)
  6579. {
  6580. /* TODO - EXP_REDIR */
  6581. while (str) {
  6582. char *p;
  6583. glob_t pglob;
  6584. int i;
  6585. if (fflag)
  6586. goto nometa;
  6587. if (!hasmeta(str->text))
  6588. goto nometa;
  6589. INT_OFF;
  6590. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6591. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6592. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6593. //
  6594. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6595. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6596. // Which means you need to unescape the string, right? Not so fast:
  6597. // if there _is_ a file named "file\?" (with backslash), it is returned
  6598. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6599. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6600. //
  6601. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6602. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6603. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6604. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6605. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6606. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6607. i = glob(p, 0, NULL, &pglob);
  6608. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6609. if (p != str->text)
  6610. free(p);
  6611. switch (i) {
  6612. case 0:
  6613. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6614. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6615. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6616. goto nometa2;
  6617. #endif
  6618. addglob(&pglob);
  6619. globfree(&pglob);
  6620. INT_ON;
  6621. break;
  6622. case GLOB_NOMATCH:
  6623. //nometa2:
  6624. globfree(&pglob);
  6625. INT_ON;
  6626. nometa:
  6627. *exparg.lastp = str;
  6628. rmescapes(str->text, 0);
  6629. exparg.lastp = &str->next;
  6630. break;
  6631. default: /* GLOB_NOSPACE */
  6632. globfree(&pglob);
  6633. INT_ON;
  6634. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6635. }
  6636. str = str->next;
  6637. }
  6638. }
  6639. #else
  6640. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6641. /*
  6642. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6643. */
  6644. static void
  6645. expmeta(char *expdir, char *enddir, char *name)
  6646. {
  6647. char *p;
  6648. const char *cp;
  6649. char *start;
  6650. char *endname;
  6651. int metaflag;
  6652. struct stat statb;
  6653. DIR *dirp;
  6654. struct dirent *dp;
  6655. int atend;
  6656. int matchdot;
  6657. int esc;
  6658. metaflag = 0;
  6659. start = name;
  6660. for (p = name; esc = 0, *p; p += esc + 1) {
  6661. if (*p == '*' || *p == '?')
  6662. metaflag = 1;
  6663. else if (*p == '[') {
  6664. char *q = p + 1;
  6665. if (*q == '!')
  6666. q++;
  6667. for (;;) {
  6668. if (*q == '\\')
  6669. q++;
  6670. if (*q == '/' || *q == '\0')
  6671. break;
  6672. if (*++q == ']') {
  6673. metaflag = 1;
  6674. break;
  6675. }
  6676. }
  6677. } else {
  6678. if (*p == '\\')
  6679. esc++;
  6680. if (p[esc] == '/') {
  6681. if (metaflag)
  6682. break;
  6683. start = p + esc + 1;
  6684. }
  6685. }
  6686. }
  6687. if (metaflag == 0) { /* we've reached the end of the file name */
  6688. if (enddir != expdir)
  6689. metaflag++;
  6690. p = name;
  6691. do {
  6692. if (*p == '\\')
  6693. p++;
  6694. *enddir++ = *p;
  6695. } while (*p++);
  6696. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6697. addfname(expdir);
  6698. return;
  6699. }
  6700. endname = p;
  6701. if (name < start) {
  6702. p = name;
  6703. do {
  6704. if (*p == '\\')
  6705. p++;
  6706. *enddir++ = *p++;
  6707. } while (p < start);
  6708. }
  6709. if (enddir == expdir) {
  6710. cp = ".";
  6711. } else if (enddir == expdir + 1 && *expdir == '/') {
  6712. cp = "/";
  6713. } else {
  6714. cp = expdir;
  6715. enddir[-1] = '\0';
  6716. }
  6717. dirp = opendir(cp);
  6718. if (dirp == NULL)
  6719. return;
  6720. if (enddir != expdir)
  6721. enddir[-1] = '/';
  6722. if (*endname == 0) {
  6723. atend = 1;
  6724. } else {
  6725. atend = 0;
  6726. *endname = '\0';
  6727. endname += esc + 1;
  6728. }
  6729. matchdot = 0;
  6730. p = start;
  6731. if (*p == '\\')
  6732. p++;
  6733. if (*p == '.')
  6734. matchdot++;
  6735. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6736. if (dp->d_name[0] == '.' && !matchdot)
  6737. continue;
  6738. if (pmatch(start, dp->d_name)) {
  6739. if (atend) {
  6740. strcpy(enddir, dp->d_name);
  6741. addfname(expdir);
  6742. } else {
  6743. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6744. continue;
  6745. p[-1] = '/';
  6746. expmeta(expdir, p, endname);
  6747. }
  6748. }
  6749. }
  6750. closedir(dirp);
  6751. if (!atend)
  6752. endname[-esc - 1] = esc ? '\\' : '/';
  6753. }
  6754. static struct strlist *
  6755. msort(struct strlist *list, int len)
  6756. {
  6757. struct strlist *p, *q = NULL;
  6758. struct strlist **lpp;
  6759. int half;
  6760. int n;
  6761. if (len <= 1)
  6762. return list;
  6763. half = len >> 1;
  6764. p = list;
  6765. for (n = half; --n >= 0;) {
  6766. q = p;
  6767. p = p->next;
  6768. }
  6769. q->next = NULL; /* terminate first half of list */
  6770. q = msort(list, half); /* sort first half of list */
  6771. p = msort(p, len - half); /* sort second half */
  6772. lpp = &list;
  6773. for (;;) {
  6774. #if ENABLE_LOCALE_SUPPORT
  6775. if (strcoll(p->text, q->text) < 0)
  6776. #else
  6777. if (strcmp(p->text, q->text) < 0)
  6778. #endif
  6779. {
  6780. *lpp = p;
  6781. lpp = &p->next;
  6782. p = *lpp;
  6783. if (p == NULL) {
  6784. *lpp = q;
  6785. break;
  6786. }
  6787. } else {
  6788. *lpp = q;
  6789. lpp = &q->next;
  6790. q = *lpp;
  6791. if (q == NULL) {
  6792. *lpp = p;
  6793. break;
  6794. }
  6795. }
  6796. }
  6797. return list;
  6798. }
  6799. /*
  6800. * Sort the results of file name expansion. It calculates the number of
  6801. * strings to sort and then calls msort (short for merge sort) to do the
  6802. * work.
  6803. */
  6804. static struct strlist *
  6805. expsort(struct strlist *str)
  6806. {
  6807. int len;
  6808. struct strlist *sp;
  6809. len = 0;
  6810. for (sp = str; sp; sp = sp->next)
  6811. len++;
  6812. return msort(str, len);
  6813. }
  6814. static void
  6815. expandmeta(struct strlist *str /*, int flag*/)
  6816. {
  6817. /* TODO - EXP_REDIR */
  6818. while (str) {
  6819. char *expdir;
  6820. struct strlist **savelastp;
  6821. struct strlist *sp;
  6822. char *p;
  6823. if (fflag)
  6824. goto nometa;
  6825. if (!hasmeta(str->text))
  6826. goto nometa;
  6827. savelastp = exparg.lastp;
  6828. INT_OFF;
  6829. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6830. {
  6831. int i = strlen(str->text);
  6832. //BUGGY estimation of how long expanded name can be
  6833. expdir = ckmalloc(i < 2048 ? 2048 : i+1);
  6834. }
  6835. expmeta(expdir, expdir, p);
  6836. free(expdir);
  6837. if (p != str->text)
  6838. free(p);
  6839. INT_ON;
  6840. if (exparg.lastp == savelastp) {
  6841. /*
  6842. * no matches
  6843. */
  6844. nometa:
  6845. *exparg.lastp = str;
  6846. rmescapes(str->text, 0);
  6847. exparg.lastp = &str->next;
  6848. } else {
  6849. *exparg.lastp = NULL;
  6850. *savelastp = sp = expsort(*savelastp);
  6851. while (sp->next != NULL)
  6852. sp = sp->next;
  6853. exparg.lastp = &sp->next;
  6854. }
  6855. str = str->next;
  6856. }
  6857. }
  6858. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  6859. /*
  6860. * Perform variable substitution and command substitution on an argument,
  6861. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6862. * perform splitting and file name expansion. When arglist is NULL, perform
  6863. * here document expansion.
  6864. */
  6865. static void
  6866. expandarg(union node *arg, struct arglist *arglist, int flag)
  6867. {
  6868. struct strlist *sp;
  6869. char *p;
  6870. argbackq = arg->narg.backquote;
  6871. STARTSTACKSTR(expdest);
  6872. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  6873. argstr(arg->narg.text, flag,
  6874. /* var_str_list: */ arglist ? arglist->list : NULL);
  6875. p = _STPUTC('\0', expdest);
  6876. expdest = p - 1;
  6877. if (arglist == NULL) {
  6878. /* here document expanded */
  6879. goto out;
  6880. }
  6881. p = grabstackstr(p);
  6882. TRACE(("expandarg: p:'%s'\n", p));
  6883. exparg.lastp = &exparg.list;
  6884. /*
  6885. * TODO - EXP_REDIR
  6886. */
  6887. if (flag & EXP_FULL) {
  6888. ifsbreakup(p, &exparg);
  6889. *exparg.lastp = NULL;
  6890. exparg.lastp = &exparg.list;
  6891. expandmeta(exparg.list /*, flag*/);
  6892. } else {
  6893. if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
  6894. rmescapes(p, 0);
  6895. TRACE(("expandarg: rmescapes:'%s'\n", p));
  6896. }
  6897. sp = stzalloc(sizeof(*sp));
  6898. sp->text = p;
  6899. *exparg.lastp = sp;
  6900. exparg.lastp = &sp->next;
  6901. }
  6902. *exparg.lastp = NULL;
  6903. if (exparg.list) {
  6904. *arglist->lastp = exparg.list;
  6905. arglist->lastp = exparg.lastp;
  6906. }
  6907. out:
  6908. ifsfree();
  6909. }
  6910. /*
  6911. * Expand shell variables and backquotes inside a here document.
  6912. */
  6913. static void
  6914. expandhere(union node *arg, int fd)
  6915. {
  6916. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  6917. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6918. }
  6919. /*
  6920. * Returns true if the pattern matches the string.
  6921. */
  6922. static int
  6923. patmatch(char *pattern, const char *string)
  6924. {
  6925. return pmatch(preglob(pattern, 0), string);
  6926. }
  6927. /*
  6928. * See if a pattern matches in a case statement.
  6929. */
  6930. static int
  6931. casematch(union node *pattern, char *val)
  6932. {
  6933. struct stackmark smark;
  6934. int result;
  6935. setstackmark(&smark);
  6936. argbackq = pattern->narg.backquote;
  6937. STARTSTACKSTR(expdest);
  6938. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6939. /* var_str_list: */ NULL);
  6940. STACKSTRNUL(expdest);
  6941. ifsfree();
  6942. result = patmatch(stackblock(), val);
  6943. popstackmark(&smark);
  6944. return result;
  6945. }
  6946. /* ============ find_command */
  6947. struct builtincmd {
  6948. const char *name;
  6949. int (*builtin)(int, char **) FAST_FUNC;
  6950. /* unsigned flags; */
  6951. };
  6952. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6953. /* "regular" builtins always take precedence over commands,
  6954. * regardless of PATH=....%builtin... position */
  6955. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6956. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6957. struct cmdentry {
  6958. smallint cmdtype; /* CMDxxx */
  6959. union param {
  6960. int index;
  6961. /* index >= 0 for commands without path (slashes) */
  6962. /* (TODO: what exactly does the value mean? PATH position?) */
  6963. /* index == -1 for commands with slashes */
  6964. /* index == (-2 - applet_no) for NOFORK applets */
  6965. const struct builtincmd *cmd;
  6966. struct funcnode *func;
  6967. } u;
  6968. };
  6969. /* values of cmdtype */
  6970. #define CMDUNKNOWN -1 /* no entry in table for command */
  6971. #define CMDNORMAL 0 /* command is an executable program */
  6972. #define CMDFUNCTION 1 /* command is a shell function */
  6973. #define CMDBUILTIN 2 /* command is a shell builtin */
  6974. /* action to find_command() */
  6975. #define DO_ERR 0x01 /* prints errors */
  6976. #define DO_ABS 0x02 /* checks absolute paths */
  6977. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6978. #define DO_ALTPATH 0x08 /* using alternate path */
  6979. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6980. static void find_command(char *, struct cmdentry *, int, const char *);
  6981. /* ============ Hashing commands */
  6982. /*
  6983. * When commands are first encountered, they are entered in a hash table.
  6984. * This ensures that a full path search will not have to be done for them
  6985. * on each invocation.
  6986. *
  6987. * We should investigate converting to a linear search, even though that
  6988. * would make the command name "hash" a misnomer.
  6989. */
  6990. struct tblentry {
  6991. struct tblentry *next; /* next entry in hash chain */
  6992. union param param; /* definition of builtin function */
  6993. smallint cmdtype; /* CMDxxx */
  6994. char rehash; /* if set, cd done since entry created */
  6995. char cmdname[1]; /* name of command */
  6996. };
  6997. static struct tblentry **cmdtable;
  6998. #define INIT_G_cmdtable() do { \
  6999. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7000. } while (0)
  7001. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7002. static void
  7003. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  7004. {
  7005. #if ENABLE_FEATURE_SH_STANDALONE
  7006. if (applet_no >= 0) {
  7007. if (APPLET_IS_NOEXEC(applet_no)) {
  7008. clearenv();
  7009. while (*envp)
  7010. putenv(*envp++);
  7011. run_applet_no_and_exit(applet_no, cmd, argv);
  7012. }
  7013. /* re-exec ourselves with the new arguments */
  7014. execve(bb_busybox_exec_path, argv, envp);
  7015. /* If they called chroot or otherwise made the binary no longer
  7016. * executable, fall through */
  7017. }
  7018. #endif
  7019. repeat:
  7020. #ifdef SYSV
  7021. do {
  7022. execve(cmd, argv, envp);
  7023. } while (errno == EINTR);
  7024. #else
  7025. execve(cmd, argv, envp);
  7026. #endif
  7027. if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
  7028. /* Run "cmd" as a shell script:
  7029. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7030. * "If the execve() function fails with ENOEXEC, the shell
  7031. * shall execute a command equivalent to having a shell invoked
  7032. * with the command name as its first operand,
  7033. * with any remaining arguments passed to the new shell"
  7034. *
  7035. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7036. * just call ourselves.
  7037. *
  7038. * Note that bash reads ~80 chars of the file, and if it sees
  7039. * a zero byte before it sees newline, it doesn't try to
  7040. * interpret it, but fails with "cannot execute binary file"
  7041. * message and exit code 126. For one, this prevents attempts
  7042. * to interpret foreign ELF binaries as shell scripts.
  7043. */
  7044. argv[0] = cmd;
  7045. cmd = (char*) bb_busybox_exec_path;
  7046. /* NB: this is only possible because all callers of shellexec()
  7047. * ensure that the argv[-1] slot exists!
  7048. */
  7049. argv--;
  7050. argv[0] = (char*) "ash";
  7051. goto repeat;
  7052. }
  7053. }
  7054. /*
  7055. * Exec a program. Never returns. If you change this routine, you may
  7056. * have to change the find_command routine as well.
  7057. * argv[-1] must exist and be writable! See tryexec() for why.
  7058. */
  7059. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7060. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7061. {
  7062. char *cmdname;
  7063. int e;
  7064. char **envp;
  7065. int exerrno;
  7066. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7067. envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
  7068. if (strchr(prog, '/') != NULL
  7069. #if ENABLE_FEATURE_SH_STANDALONE
  7070. || (applet_no = find_applet_by_name(prog)) >= 0
  7071. #endif
  7072. ) {
  7073. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7074. if (applet_no >= 0) {
  7075. /* We tried execing ourself, but it didn't work.
  7076. * Maybe /proc/self/exe doesn't exist?
  7077. * Try $PATH search.
  7078. */
  7079. goto try_PATH;
  7080. }
  7081. e = errno;
  7082. } else {
  7083. try_PATH:
  7084. e = ENOENT;
  7085. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7086. if (--idx < 0 && pathopt == NULL) {
  7087. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7088. if (errno != ENOENT && errno != ENOTDIR)
  7089. e = errno;
  7090. }
  7091. stunalloc(cmdname);
  7092. }
  7093. }
  7094. /* Map to POSIX errors */
  7095. switch (e) {
  7096. case EACCES:
  7097. exerrno = 126;
  7098. break;
  7099. case ENOENT:
  7100. exerrno = 127;
  7101. break;
  7102. default:
  7103. exerrno = 2;
  7104. break;
  7105. }
  7106. exitstatus = exerrno;
  7107. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7108. prog, e, suppress_int));
  7109. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7110. /* NOTREACHED */
  7111. }
  7112. static void
  7113. printentry(struct tblentry *cmdp)
  7114. {
  7115. int idx;
  7116. const char *path;
  7117. char *name;
  7118. idx = cmdp->param.index;
  7119. path = pathval();
  7120. do {
  7121. name = path_advance(&path, cmdp->cmdname);
  7122. stunalloc(name);
  7123. } while (--idx >= 0);
  7124. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7125. }
  7126. /*
  7127. * Clear out command entries. The argument specifies the first entry in
  7128. * PATH which has changed.
  7129. */
  7130. static void
  7131. clearcmdentry(int firstchange)
  7132. {
  7133. struct tblentry **tblp;
  7134. struct tblentry **pp;
  7135. struct tblentry *cmdp;
  7136. INT_OFF;
  7137. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7138. pp = tblp;
  7139. while ((cmdp = *pp) != NULL) {
  7140. if ((cmdp->cmdtype == CMDNORMAL &&
  7141. cmdp->param.index >= firstchange)
  7142. || (cmdp->cmdtype == CMDBUILTIN &&
  7143. builtinloc >= firstchange)
  7144. ) {
  7145. *pp = cmdp->next;
  7146. free(cmdp);
  7147. } else {
  7148. pp = &cmdp->next;
  7149. }
  7150. }
  7151. }
  7152. INT_ON;
  7153. }
  7154. /*
  7155. * Locate a command in the command hash table. If "add" is nonzero,
  7156. * add the command to the table if it is not already present. The
  7157. * variable "lastcmdentry" is set to point to the address of the link
  7158. * pointing to the entry, so that delete_cmd_entry can delete the
  7159. * entry.
  7160. *
  7161. * Interrupts must be off if called with add != 0.
  7162. */
  7163. static struct tblentry **lastcmdentry;
  7164. static struct tblentry *
  7165. cmdlookup(const char *name, int add)
  7166. {
  7167. unsigned int hashval;
  7168. const char *p;
  7169. struct tblentry *cmdp;
  7170. struct tblentry **pp;
  7171. p = name;
  7172. hashval = (unsigned char)*p << 4;
  7173. while (*p)
  7174. hashval += (unsigned char)*p++;
  7175. hashval &= 0x7FFF;
  7176. pp = &cmdtable[hashval % CMDTABLESIZE];
  7177. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7178. if (strcmp(cmdp->cmdname, name) == 0)
  7179. break;
  7180. pp = &cmdp->next;
  7181. }
  7182. if (add && cmdp == NULL) {
  7183. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7184. + strlen(name)
  7185. /* + 1 - already done because
  7186. * tblentry::cmdname is char[1] */);
  7187. /*cmdp->next = NULL; - ckzalloc did it */
  7188. cmdp->cmdtype = CMDUNKNOWN;
  7189. strcpy(cmdp->cmdname, name);
  7190. }
  7191. lastcmdentry = pp;
  7192. return cmdp;
  7193. }
  7194. /*
  7195. * Delete the command entry returned on the last lookup.
  7196. */
  7197. static void
  7198. delete_cmd_entry(void)
  7199. {
  7200. struct tblentry *cmdp;
  7201. INT_OFF;
  7202. cmdp = *lastcmdentry;
  7203. *lastcmdentry = cmdp->next;
  7204. if (cmdp->cmdtype == CMDFUNCTION)
  7205. freefunc(cmdp->param.func);
  7206. free(cmdp);
  7207. INT_ON;
  7208. }
  7209. /*
  7210. * Add a new command entry, replacing any existing command entry for
  7211. * the same name - except special builtins.
  7212. */
  7213. static void
  7214. addcmdentry(char *name, struct cmdentry *entry)
  7215. {
  7216. struct tblentry *cmdp;
  7217. cmdp = cmdlookup(name, 1);
  7218. if (cmdp->cmdtype == CMDFUNCTION) {
  7219. freefunc(cmdp->param.func);
  7220. }
  7221. cmdp->cmdtype = entry->cmdtype;
  7222. cmdp->param = entry->u;
  7223. cmdp->rehash = 0;
  7224. }
  7225. static int FAST_FUNC
  7226. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7227. {
  7228. struct tblentry **pp;
  7229. struct tblentry *cmdp;
  7230. int c;
  7231. struct cmdentry entry;
  7232. char *name;
  7233. if (nextopt("r") != '\0') {
  7234. clearcmdentry(0);
  7235. return 0;
  7236. }
  7237. if (*argptr == NULL) {
  7238. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7239. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7240. if (cmdp->cmdtype == CMDNORMAL)
  7241. printentry(cmdp);
  7242. }
  7243. }
  7244. return 0;
  7245. }
  7246. c = 0;
  7247. while ((name = *argptr) != NULL) {
  7248. cmdp = cmdlookup(name, 0);
  7249. if (cmdp != NULL
  7250. && (cmdp->cmdtype == CMDNORMAL
  7251. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7252. ) {
  7253. delete_cmd_entry();
  7254. }
  7255. find_command(name, &entry, DO_ERR, pathval());
  7256. if (entry.cmdtype == CMDUNKNOWN)
  7257. c = 1;
  7258. argptr++;
  7259. }
  7260. return c;
  7261. }
  7262. /*
  7263. * Called when a cd is done. Marks all commands so the next time they
  7264. * are executed they will be rehashed.
  7265. */
  7266. static void
  7267. hashcd(void)
  7268. {
  7269. struct tblentry **pp;
  7270. struct tblentry *cmdp;
  7271. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7272. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7273. if (cmdp->cmdtype == CMDNORMAL
  7274. || (cmdp->cmdtype == CMDBUILTIN
  7275. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7276. && builtinloc > 0)
  7277. ) {
  7278. cmdp->rehash = 1;
  7279. }
  7280. }
  7281. }
  7282. }
  7283. /*
  7284. * Fix command hash table when PATH changed.
  7285. * Called before PATH is changed. The argument is the new value of PATH;
  7286. * pathval() still returns the old value at this point.
  7287. * Called with interrupts off.
  7288. */
  7289. static void FAST_FUNC
  7290. changepath(const char *new)
  7291. {
  7292. const char *old;
  7293. int firstchange;
  7294. int idx;
  7295. int idx_bltin;
  7296. old = pathval();
  7297. firstchange = 9999; /* assume no change */
  7298. idx = 0;
  7299. idx_bltin = -1;
  7300. for (;;) {
  7301. if (*old != *new) {
  7302. firstchange = idx;
  7303. if ((*old == '\0' && *new == ':')
  7304. || (*old == ':' && *new == '\0')
  7305. ) {
  7306. firstchange++;
  7307. }
  7308. old = new; /* ignore subsequent differences */
  7309. }
  7310. if (*new == '\0')
  7311. break;
  7312. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7313. idx_bltin = idx;
  7314. if (*new == ':')
  7315. idx++;
  7316. new++;
  7317. old++;
  7318. }
  7319. if (builtinloc < 0 && idx_bltin >= 0)
  7320. builtinloc = idx_bltin; /* zap builtins */
  7321. if (builtinloc >= 0 && idx_bltin < 0)
  7322. firstchange = 0;
  7323. clearcmdentry(firstchange);
  7324. builtinloc = idx_bltin;
  7325. }
  7326. enum {
  7327. TEOF,
  7328. TNL,
  7329. TREDIR,
  7330. TWORD,
  7331. TSEMI,
  7332. TBACKGND,
  7333. TAND,
  7334. TOR,
  7335. TPIPE,
  7336. TLP,
  7337. TRP,
  7338. TENDCASE,
  7339. TENDBQUOTE,
  7340. TNOT,
  7341. TCASE,
  7342. TDO,
  7343. TDONE,
  7344. TELIF,
  7345. TELSE,
  7346. TESAC,
  7347. TFI,
  7348. TFOR,
  7349. #if BASH_FUNCTION
  7350. TFUNCTION,
  7351. #endif
  7352. TIF,
  7353. TIN,
  7354. TTHEN,
  7355. TUNTIL,
  7356. TWHILE,
  7357. TBEGIN,
  7358. TEND
  7359. };
  7360. typedef smallint token_id_t;
  7361. /* Nth bit indicates if token marks the end of a list */
  7362. enum {
  7363. tokendlist = 0
  7364. /* 0 */ | (1u << TEOF)
  7365. /* 1 */ | (0u << TNL)
  7366. /* 2 */ | (0u << TREDIR)
  7367. /* 3 */ | (0u << TWORD)
  7368. /* 4 */ | (0u << TSEMI)
  7369. /* 5 */ | (0u << TBACKGND)
  7370. /* 6 */ | (0u << TAND)
  7371. /* 7 */ | (0u << TOR)
  7372. /* 8 */ | (0u << TPIPE)
  7373. /* 9 */ | (0u << TLP)
  7374. /* 10 */ | (1u << TRP)
  7375. /* 11 */ | (1u << TENDCASE)
  7376. /* 12 */ | (1u << TENDBQUOTE)
  7377. /* 13 */ | (0u << TNOT)
  7378. /* 14 */ | (0u << TCASE)
  7379. /* 15 */ | (1u << TDO)
  7380. /* 16 */ | (1u << TDONE)
  7381. /* 17 */ | (1u << TELIF)
  7382. /* 18 */ | (1u << TELSE)
  7383. /* 19 */ | (1u << TESAC)
  7384. /* 20 */ | (1u << TFI)
  7385. /* 21 */ | (0u << TFOR)
  7386. #if BASH_FUNCTION
  7387. /* 22 */ | (0u << TFUNCTION)
  7388. #endif
  7389. /* 23 */ | (0u << TIF)
  7390. /* 24 */ | (0u << TIN)
  7391. /* 25 */ | (1u << TTHEN)
  7392. /* 26 */ | (0u << TUNTIL)
  7393. /* 27 */ | (0u << TWHILE)
  7394. /* 28 */ | (0u << TBEGIN)
  7395. /* 29 */ | (1u << TEND)
  7396. , /* thus far 29 bits used */
  7397. };
  7398. static const char *const tokname_array[] = {
  7399. "end of file",
  7400. "newline",
  7401. "redirection",
  7402. "word",
  7403. ";",
  7404. "&",
  7405. "&&",
  7406. "||",
  7407. "|",
  7408. "(",
  7409. ")",
  7410. ";;",
  7411. "`",
  7412. #define KWDOFFSET 13
  7413. /* the following are keywords */
  7414. "!",
  7415. "case",
  7416. "do",
  7417. "done",
  7418. "elif",
  7419. "else",
  7420. "esac",
  7421. "fi",
  7422. "for",
  7423. #if BASH_FUNCTION
  7424. "function",
  7425. #endif
  7426. "if",
  7427. "in",
  7428. "then",
  7429. "until",
  7430. "while",
  7431. "{",
  7432. "}",
  7433. };
  7434. /* Wrapper around strcmp for qsort/bsearch/... */
  7435. static int
  7436. pstrcmp(const void *a, const void *b)
  7437. {
  7438. return strcmp((char*)a, *(char**)b);
  7439. }
  7440. static const char *const *
  7441. findkwd(const char *s)
  7442. {
  7443. return bsearch(s, tokname_array + KWDOFFSET,
  7444. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7445. sizeof(tokname_array[0]), pstrcmp);
  7446. }
  7447. /*
  7448. * Locate and print what a word is...
  7449. */
  7450. static int
  7451. describe_command(char *command, const char *path, int describe_command_verbose)
  7452. {
  7453. struct cmdentry entry;
  7454. #if ENABLE_ASH_ALIAS
  7455. const struct alias *ap;
  7456. #endif
  7457. path = path ? path : pathval();
  7458. if (describe_command_verbose) {
  7459. out1str(command);
  7460. }
  7461. /* First look at the keywords */
  7462. if (findkwd(command)) {
  7463. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7464. goto out;
  7465. }
  7466. #if ENABLE_ASH_ALIAS
  7467. /* Then look at the aliases */
  7468. ap = lookupalias(command, 0);
  7469. if (ap != NULL) {
  7470. if (!describe_command_verbose) {
  7471. out1str("alias ");
  7472. printalias(ap);
  7473. return 0;
  7474. }
  7475. out1fmt(" is an alias for %s", ap->val);
  7476. goto out;
  7477. }
  7478. #endif
  7479. /* Brute force */
  7480. find_command(command, &entry, DO_ABS, path);
  7481. switch (entry.cmdtype) {
  7482. case CMDNORMAL: {
  7483. int j = entry.u.index;
  7484. char *p;
  7485. if (j < 0) {
  7486. p = command;
  7487. } else {
  7488. do {
  7489. p = path_advance(&path, command);
  7490. stunalloc(p);
  7491. } while (--j >= 0);
  7492. }
  7493. if (describe_command_verbose) {
  7494. out1fmt(" is %s", p);
  7495. } else {
  7496. out1str(p);
  7497. }
  7498. break;
  7499. }
  7500. case CMDFUNCTION:
  7501. if (describe_command_verbose) {
  7502. out1str(" is a shell function");
  7503. } else {
  7504. out1str(command);
  7505. }
  7506. break;
  7507. case CMDBUILTIN:
  7508. if (describe_command_verbose) {
  7509. out1fmt(" is a %sshell builtin",
  7510. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7511. "special " : nullstr
  7512. );
  7513. } else {
  7514. out1str(command);
  7515. }
  7516. break;
  7517. default:
  7518. if (describe_command_verbose) {
  7519. out1str(": not found\n");
  7520. }
  7521. return 127;
  7522. }
  7523. out:
  7524. out1str("\n");
  7525. return 0;
  7526. }
  7527. static int FAST_FUNC
  7528. typecmd(int argc UNUSED_PARAM, char **argv)
  7529. {
  7530. int i = 1;
  7531. int err = 0;
  7532. int verbose = 1;
  7533. /* type -p ... ? (we don't bother checking for 'p') */
  7534. if (argv[1] && argv[1][0] == '-') {
  7535. i++;
  7536. verbose = 0;
  7537. }
  7538. while (argv[i]) {
  7539. err |= describe_command(argv[i++], NULL, verbose);
  7540. }
  7541. return err;
  7542. }
  7543. #if ENABLE_ASH_CMDCMD
  7544. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7545. static char **
  7546. parse_command_args(char **argv, const char **path)
  7547. {
  7548. char *cp, c;
  7549. for (;;) {
  7550. cp = *++argv;
  7551. if (!cp)
  7552. return NULL;
  7553. if (*cp++ != '-')
  7554. break;
  7555. c = *cp++;
  7556. if (!c)
  7557. break;
  7558. if (c == '-' && !*cp) {
  7559. if (!*++argv)
  7560. return NULL;
  7561. break;
  7562. }
  7563. do {
  7564. switch (c) {
  7565. case 'p':
  7566. *path = bb_default_path;
  7567. break;
  7568. default:
  7569. /* run 'typecmd' for other options */
  7570. return NULL;
  7571. }
  7572. c = *cp++;
  7573. } while (c);
  7574. }
  7575. return argv;
  7576. }
  7577. static int FAST_FUNC
  7578. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7579. {
  7580. char *cmd;
  7581. int c;
  7582. enum {
  7583. VERIFY_BRIEF = 1,
  7584. VERIFY_VERBOSE = 2,
  7585. } verify = 0;
  7586. const char *path = NULL;
  7587. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7588. * never reaches this function.
  7589. */
  7590. while ((c = nextopt("pvV")) != '\0')
  7591. if (c == 'V')
  7592. verify |= VERIFY_VERBOSE;
  7593. else if (c == 'v')
  7594. /*verify |= VERIFY_BRIEF*/;
  7595. #if DEBUG
  7596. else if (c != 'p')
  7597. abort();
  7598. #endif
  7599. else
  7600. path = bb_default_path;
  7601. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7602. cmd = *argptr;
  7603. if (/*verify && */ cmd)
  7604. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7605. return 0;
  7606. }
  7607. #endif
  7608. /*static int funcblocksize; // size of structures in function */
  7609. /*static int funcstringsize; // size of strings in node */
  7610. static void *funcblock; /* block to allocate function from */
  7611. static char *funcstring_end; /* end of block to allocate strings from */
  7612. /* flags in argument to evaltree */
  7613. #define EV_EXIT 01 /* exit after evaluating tree */
  7614. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7615. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7616. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7617. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7618. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7619. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7620. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7621. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7622. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7623. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7624. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7625. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7626. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7627. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7628. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7629. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7630. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7631. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7632. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7633. #if BASH_REDIR_OUTPUT
  7634. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7635. #endif
  7636. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7637. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7638. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7639. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7640. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7641. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7642. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7643. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7644. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7645. };
  7646. static int calcsize(int funcblocksize, union node *n);
  7647. static int
  7648. sizenodelist(int funcblocksize, struct nodelist *lp)
  7649. {
  7650. while (lp) {
  7651. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7652. funcblocksize = calcsize(funcblocksize, lp->n);
  7653. lp = lp->next;
  7654. }
  7655. return funcblocksize;
  7656. }
  7657. static int
  7658. calcsize(int funcblocksize, union node *n)
  7659. {
  7660. if (n == NULL)
  7661. return funcblocksize;
  7662. funcblocksize += nodesize[n->type];
  7663. switch (n->type) {
  7664. case NCMD:
  7665. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7666. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7667. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7668. break;
  7669. case NPIPE:
  7670. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7671. break;
  7672. case NREDIR:
  7673. case NBACKGND:
  7674. case NSUBSHELL:
  7675. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7676. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7677. break;
  7678. case NAND:
  7679. case NOR:
  7680. case NSEMI:
  7681. case NWHILE:
  7682. case NUNTIL:
  7683. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7684. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7685. break;
  7686. case NIF:
  7687. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7688. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7689. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7690. break;
  7691. case NFOR:
  7692. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7693. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7694. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7695. break;
  7696. case NCASE:
  7697. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7698. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7699. break;
  7700. case NCLIST:
  7701. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7702. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7703. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7704. break;
  7705. case NDEFUN:
  7706. case NARG:
  7707. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  7708. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  7709. funcblocksize = calcsize(funcblocksize, n->narg.next);
  7710. break;
  7711. case NTO:
  7712. #if BASH_REDIR_OUTPUT
  7713. case NTO2:
  7714. #endif
  7715. case NCLOBBER:
  7716. case NFROM:
  7717. case NFROMTO:
  7718. case NAPPEND:
  7719. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  7720. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  7721. break;
  7722. case NTOFD:
  7723. case NFROMFD:
  7724. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  7725. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  7726. break;
  7727. case NHERE:
  7728. case NXHERE:
  7729. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  7730. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  7731. break;
  7732. case NNOT:
  7733. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  7734. break;
  7735. };
  7736. return funcblocksize;
  7737. }
  7738. static char *
  7739. nodeckstrdup(char *s)
  7740. {
  7741. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  7742. return strcpy(funcstring_end, s);
  7743. }
  7744. static union node *copynode(union node *);
  7745. static struct nodelist *
  7746. copynodelist(struct nodelist *lp)
  7747. {
  7748. struct nodelist *start;
  7749. struct nodelist **lpp;
  7750. lpp = &start;
  7751. while (lp) {
  7752. *lpp = funcblock;
  7753. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7754. (*lpp)->n = copynode(lp->n);
  7755. lp = lp->next;
  7756. lpp = &(*lpp)->next;
  7757. }
  7758. *lpp = NULL;
  7759. return start;
  7760. }
  7761. static union node *
  7762. copynode(union node *n)
  7763. {
  7764. union node *new;
  7765. if (n == NULL)
  7766. return NULL;
  7767. new = funcblock;
  7768. funcblock = (char *) funcblock + nodesize[n->type];
  7769. switch (n->type) {
  7770. case NCMD:
  7771. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7772. new->ncmd.args = copynode(n->ncmd.args);
  7773. new->ncmd.assign = copynode(n->ncmd.assign);
  7774. break;
  7775. case NPIPE:
  7776. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7777. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7778. break;
  7779. case NREDIR:
  7780. case NBACKGND:
  7781. case NSUBSHELL:
  7782. new->nredir.redirect = copynode(n->nredir.redirect);
  7783. new->nredir.n = copynode(n->nredir.n);
  7784. break;
  7785. case NAND:
  7786. case NOR:
  7787. case NSEMI:
  7788. case NWHILE:
  7789. case NUNTIL:
  7790. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7791. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7792. break;
  7793. case NIF:
  7794. new->nif.elsepart = copynode(n->nif.elsepart);
  7795. new->nif.ifpart = copynode(n->nif.ifpart);
  7796. new->nif.test = copynode(n->nif.test);
  7797. break;
  7798. case NFOR:
  7799. new->nfor.var = nodeckstrdup(n->nfor.var);
  7800. new->nfor.body = copynode(n->nfor.body);
  7801. new->nfor.args = copynode(n->nfor.args);
  7802. break;
  7803. case NCASE:
  7804. new->ncase.cases = copynode(n->ncase.cases);
  7805. new->ncase.expr = copynode(n->ncase.expr);
  7806. break;
  7807. case NCLIST:
  7808. new->nclist.body = copynode(n->nclist.body);
  7809. new->nclist.pattern = copynode(n->nclist.pattern);
  7810. new->nclist.next = copynode(n->nclist.next);
  7811. break;
  7812. case NDEFUN:
  7813. case NARG:
  7814. new->narg.backquote = copynodelist(n->narg.backquote);
  7815. new->narg.text = nodeckstrdup(n->narg.text);
  7816. new->narg.next = copynode(n->narg.next);
  7817. break;
  7818. case NTO:
  7819. #if BASH_REDIR_OUTPUT
  7820. case NTO2:
  7821. #endif
  7822. case NCLOBBER:
  7823. case NFROM:
  7824. case NFROMTO:
  7825. case NAPPEND:
  7826. new->nfile.fname = copynode(n->nfile.fname);
  7827. new->nfile.fd = n->nfile.fd;
  7828. new->nfile.next = copynode(n->nfile.next);
  7829. break;
  7830. case NTOFD:
  7831. case NFROMFD:
  7832. new->ndup.vname = copynode(n->ndup.vname);
  7833. new->ndup.dupfd = n->ndup.dupfd;
  7834. new->ndup.fd = n->ndup.fd;
  7835. new->ndup.next = copynode(n->ndup.next);
  7836. break;
  7837. case NHERE:
  7838. case NXHERE:
  7839. new->nhere.doc = copynode(n->nhere.doc);
  7840. new->nhere.fd = n->nhere.fd;
  7841. new->nhere.next = copynode(n->nhere.next);
  7842. break;
  7843. case NNOT:
  7844. new->nnot.com = copynode(n->nnot.com);
  7845. break;
  7846. };
  7847. new->type = n->type;
  7848. return new;
  7849. }
  7850. /*
  7851. * Make a copy of a parse tree.
  7852. */
  7853. static struct funcnode *
  7854. copyfunc(union node *n)
  7855. {
  7856. struct funcnode *f;
  7857. size_t blocksize;
  7858. /*funcstringsize = 0;*/
  7859. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  7860. f = ckzalloc(blocksize /* + funcstringsize */);
  7861. funcblock = (char *) f + offsetof(struct funcnode, n);
  7862. funcstring_end = (char *) f + blocksize;
  7863. copynode(n);
  7864. /* f->count = 0; - ckzalloc did it */
  7865. return f;
  7866. }
  7867. /*
  7868. * Define a shell function.
  7869. */
  7870. static void
  7871. defun(union node *func)
  7872. {
  7873. struct cmdentry entry;
  7874. INT_OFF;
  7875. entry.cmdtype = CMDFUNCTION;
  7876. entry.u.func = copyfunc(func);
  7877. addcmdentry(func->narg.text, &entry);
  7878. INT_ON;
  7879. }
  7880. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7881. #define SKIPBREAK (1 << 0)
  7882. #define SKIPCONT (1 << 1)
  7883. #define SKIPFUNC (1 << 2)
  7884. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7885. static int skipcount; /* number of levels to skip */
  7886. static int funcnest; /* depth of function calls */
  7887. static int loopnest; /* current loop nesting level */
  7888. /* Forward decl way out to parsing code - dotrap needs it */
  7889. static int evalstring(char *s, int flags);
  7890. /* Called to execute a trap.
  7891. * Single callsite - at the end of evaltree().
  7892. * If we return non-zero, evaltree raises EXEXIT exception.
  7893. *
  7894. * Perhaps we should avoid entering new trap handlers
  7895. * while we are executing a trap handler. [is it a TODO?]
  7896. */
  7897. static void
  7898. dotrap(void)
  7899. {
  7900. uint8_t *g;
  7901. int sig;
  7902. uint8_t last_status;
  7903. if (!pending_sig)
  7904. return;
  7905. last_status = exitstatus;
  7906. pending_sig = 0;
  7907. barrier();
  7908. TRACE(("dotrap entered\n"));
  7909. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7910. char *p;
  7911. if (!*g)
  7912. continue;
  7913. if (evalskip) {
  7914. pending_sig = sig;
  7915. break;
  7916. }
  7917. p = trap[sig];
  7918. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7919. * don't upset it by resetting gotsig[SIGINT-1] */
  7920. if (sig == SIGINT && !p)
  7921. continue;
  7922. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  7923. *g = 0;
  7924. if (!p)
  7925. continue;
  7926. evalstring(p, 0);
  7927. }
  7928. exitstatus = last_status;
  7929. TRACE(("dotrap returns\n"));
  7930. }
  7931. /* forward declarations - evaluation is fairly recursive business... */
  7932. static int evalloop(union node *, int);
  7933. static int evalfor(union node *, int);
  7934. static int evalcase(union node *, int);
  7935. static int evalsubshell(union node *, int);
  7936. static void expredir(union node *);
  7937. static int evalpipe(union node *, int);
  7938. static int evalcommand(union node *, int);
  7939. static int evalbltin(const struct builtincmd *, int, char **, int);
  7940. static void prehash(union node *);
  7941. /*
  7942. * Evaluate a parse tree. The value is left in the global variable
  7943. * exitstatus.
  7944. */
  7945. static int
  7946. evaltree(union node *n, int flags)
  7947. {
  7948. int checkexit = 0;
  7949. int (*evalfn)(union node *, int);
  7950. int status = 0;
  7951. if (n == NULL) {
  7952. TRACE(("evaltree(NULL) called\n"));
  7953. goto out;
  7954. }
  7955. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7956. dotrap();
  7957. switch (n->type) {
  7958. default:
  7959. #if DEBUG
  7960. out1fmt("Node type = %d\n", n->type);
  7961. fflush_all();
  7962. break;
  7963. #endif
  7964. case NNOT:
  7965. status = !evaltree(n->nnot.com, EV_TESTED);
  7966. goto setstatus;
  7967. case NREDIR:
  7968. expredir(n->nredir.redirect);
  7969. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7970. if (!status) {
  7971. status = evaltree(n->nredir.n, flags & EV_TESTED);
  7972. }
  7973. if (n->nredir.redirect)
  7974. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7975. goto setstatus;
  7976. case NCMD:
  7977. evalfn = evalcommand;
  7978. checkexit:
  7979. if (eflag && !(flags & EV_TESTED))
  7980. checkexit = ~0;
  7981. goto calleval;
  7982. case NFOR:
  7983. evalfn = evalfor;
  7984. goto calleval;
  7985. case NWHILE:
  7986. case NUNTIL:
  7987. evalfn = evalloop;
  7988. goto calleval;
  7989. case NSUBSHELL:
  7990. case NBACKGND:
  7991. evalfn = evalsubshell;
  7992. goto checkexit;
  7993. case NPIPE:
  7994. evalfn = evalpipe;
  7995. goto checkexit;
  7996. case NCASE:
  7997. evalfn = evalcase;
  7998. goto calleval;
  7999. case NAND:
  8000. case NOR:
  8001. case NSEMI: {
  8002. #if NAND + 1 != NOR
  8003. #error NAND + 1 != NOR
  8004. #endif
  8005. #if NOR + 1 != NSEMI
  8006. #error NOR + 1 != NSEMI
  8007. #endif
  8008. unsigned is_or = n->type - NAND;
  8009. status = evaltree(
  8010. n->nbinary.ch1,
  8011. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8012. );
  8013. if ((!status) == is_or || evalskip)
  8014. break;
  8015. n = n->nbinary.ch2;
  8016. evaln:
  8017. evalfn = evaltree;
  8018. calleval:
  8019. status = evalfn(n, flags);
  8020. goto setstatus;
  8021. }
  8022. case NIF:
  8023. status = evaltree(n->nif.test, EV_TESTED);
  8024. if (evalskip)
  8025. break;
  8026. if (!status) {
  8027. n = n->nif.ifpart;
  8028. goto evaln;
  8029. }
  8030. if (n->nif.elsepart) {
  8031. n = n->nif.elsepart;
  8032. goto evaln;
  8033. }
  8034. status = 0;
  8035. goto setstatus;
  8036. case NDEFUN:
  8037. defun(n);
  8038. /* Not necessary. To test it:
  8039. * "false; f() { qwerty; }; echo $?" should print 0.
  8040. */
  8041. /* status = 0; */
  8042. setstatus:
  8043. exitstatus = status;
  8044. break;
  8045. }
  8046. out:
  8047. /* Order of checks below is important:
  8048. * signal handlers trigger before exit caused by "set -e".
  8049. */
  8050. dotrap();
  8051. if (checkexit & status)
  8052. raise_exception(EXEXIT);
  8053. if (flags & EV_EXIT)
  8054. raise_exception(EXEXIT);
  8055. TRACE(("leaving evaltree (no interrupts)\n"));
  8056. return exitstatus;
  8057. }
  8058. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  8059. static
  8060. #endif
  8061. int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  8062. static int
  8063. skiploop(void)
  8064. {
  8065. int skip = evalskip;
  8066. switch (skip) {
  8067. case 0:
  8068. break;
  8069. case SKIPBREAK:
  8070. case SKIPCONT:
  8071. if (--skipcount <= 0) {
  8072. evalskip = 0;
  8073. break;
  8074. }
  8075. skip = SKIPBREAK;
  8076. break;
  8077. }
  8078. return skip;
  8079. }
  8080. static int
  8081. evalloop(union node *n, int flags)
  8082. {
  8083. int skip;
  8084. int status;
  8085. loopnest++;
  8086. status = 0;
  8087. flags &= EV_TESTED;
  8088. do {
  8089. int i;
  8090. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8091. skip = skiploop();
  8092. if (skip == SKIPFUNC)
  8093. status = i;
  8094. if (skip)
  8095. continue;
  8096. if (n->type != NWHILE)
  8097. i = !i;
  8098. if (i != 0)
  8099. break;
  8100. status = evaltree(n->nbinary.ch2, flags);
  8101. skip = skiploop();
  8102. } while (!(skip & ~SKIPCONT));
  8103. loopnest--;
  8104. return status;
  8105. }
  8106. static int
  8107. evalfor(union node *n, int flags)
  8108. {
  8109. struct arglist arglist;
  8110. union node *argp;
  8111. struct strlist *sp;
  8112. struct stackmark smark;
  8113. int status = 0;
  8114. setstackmark(&smark);
  8115. arglist.list = NULL;
  8116. arglist.lastp = &arglist.list;
  8117. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8118. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8119. }
  8120. *arglist.lastp = NULL;
  8121. loopnest++;
  8122. flags &= EV_TESTED;
  8123. for (sp = arglist.list; sp; sp = sp->next) {
  8124. setvar0(n->nfor.var, sp->text);
  8125. status = evaltree(n->nfor.body, flags);
  8126. if (skiploop() & ~SKIPCONT)
  8127. break;
  8128. }
  8129. loopnest--;
  8130. popstackmark(&smark);
  8131. return status;
  8132. }
  8133. static int
  8134. evalcase(union node *n, int flags)
  8135. {
  8136. union node *cp;
  8137. union node *patp;
  8138. struct arglist arglist;
  8139. struct stackmark smark;
  8140. int status = 0;
  8141. setstackmark(&smark);
  8142. arglist.list = NULL;
  8143. arglist.lastp = &arglist.list;
  8144. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8145. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8146. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8147. if (casematch(patp, arglist.list->text)) {
  8148. /* Ensure body is non-empty as otherwise
  8149. * EV_EXIT may prevent us from setting the
  8150. * exit status.
  8151. */
  8152. if (evalskip == 0 && cp->nclist.body) {
  8153. status = evaltree(cp->nclist.body, flags);
  8154. }
  8155. goto out;
  8156. }
  8157. }
  8158. }
  8159. out:
  8160. popstackmark(&smark);
  8161. return status;
  8162. }
  8163. /*
  8164. * Kick off a subshell to evaluate a tree.
  8165. */
  8166. static int
  8167. evalsubshell(union node *n, int flags)
  8168. {
  8169. struct job *jp;
  8170. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8171. int status;
  8172. expredir(n->nredir.redirect);
  8173. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8174. goto nofork;
  8175. INT_OFF;
  8176. if (backgnd == FORK_FG)
  8177. get_tty_state();
  8178. jp = makejob(/*n,*/ 1);
  8179. if (forkshell(jp, n, backgnd) == 0) {
  8180. /* child */
  8181. INT_ON;
  8182. flags |= EV_EXIT;
  8183. if (backgnd)
  8184. flags &= ~EV_TESTED;
  8185. nofork:
  8186. redirect(n->nredir.redirect, 0);
  8187. evaltreenr(n->nredir.n, flags);
  8188. /* never returns */
  8189. }
  8190. /* parent */
  8191. status = 0;
  8192. if (backgnd == FORK_FG)
  8193. status = waitforjob(jp);
  8194. INT_ON;
  8195. return status;
  8196. }
  8197. /*
  8198. * Compute the names of the files in a redirection list.
  8199. */
  8200. static void fixredir(union node *, const char *, int);
  8201. static void
  8202. expredir(union node *n)
  8203. {
  8204. union node *redir;
  8205. for (redir = n; redir; redir = redir->nfile.next) {
  8206. struct arglist fn;
  8207. fn.list = NULL;
  8208. fn.lastp = &fn.list;
  8209. switch (redir->type) {
  8210. case NFROMTO:
  8211. case NFROM:
  8212. case NTO:
  8213. #if BASH_REDIR_OUTPUT
  8214. case NTO2:
  8215. #endif
  8216. case NCLOBBER:
  8217. case NAPPEND:
  8218. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8219. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8220. #if BASH_REDIR_OUTPUT
  8221. store_expfname:
  8222. #endif
  8223. #if 0
  8224. // By the design of stack allocator, the loop of this kind:
  8225. // while true; do while true; do break; done </dev/null; done
  8226. // will look like a memory leak: ash plans to free expfname's
  8227. // of "/dev/null" as soon as it finishes running the loop
  8228. // (in this case, never).
  8229. // This "fix" is wrong:
  8230. if (redir->nfile.expfname)
  8231. stunalloc(redir->nfile.expfname);
  8232. // It results in corrupted state of stacked allocations.
  8233. #endif
  8234. redir->nfile.expfname = fn.list->text;
  8235. break;
  8236. case NFROMFD:
  8237. case NTOFD: /* >& */
  8238. if (redir->ndup.vname) {
  8239. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8240. if (fn.list == NULL)
  8241. ash_msg_and_raise_error("redir error");
  8242. #if BASH_REDIR_OUTPUT
  8243. //FIXME: we used expandarg with different args!
  8244. if (!isdigit_str9(fn.list->text)) {
  8245. /* >&file, not >&fd */
  8246. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8247. ash_msg_and_raise_error("redir error");
  8248. redir->type = NTO2;
  8249. goto store_expfname;
  8250. }
  8251. #endif
  8252. fixredir(redir, fn.list->text, 1);
  8253. }
  8254. break;
  8255. }
  8256. }
  8257. }
  8258. /*
  8259. * Evaluate a pipeline. All the processes in the pipeline are children
  8260. * of the process creating the pipeline. (This differs from some versions
  8261. * of the shell, which make the last process in a pipeline the parent
  8262. * of all the rest.)
  8263. */
  8264. static int
  8265. evalpipe(union node *n, int flags)
  8266. {
  8267. struct job *jp;
  8268. struct nodelist *lp;
  8269. int pipelen;
  8270. int prevfd;
  8271. int pip[2];
  8272. int status = 0;
  8273. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8274. pipelen = 0;
  8275. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8276. pipelen++;
  8277. flags |= EV_EXIT;
  8278. INT_OFF;
  8279. if (n->npipe.pipe_backgnd == 0)
  8280. get_tty_state();
  8281. jp = makejob(/*n,*/ pipelen);
  8282. prevfd = -1;
  8283. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8284. prehash(lp->n);
  8285. pip[1] = -1;
  8286. if (lp->next) {
  8287. if (pipe(pip) < 0) {
  8288. close(prevfd);
  8289. ash_msg_and_raise_error("pipe call failed");
  8290. }
  8291. }
  8292. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8293. /* child */
  8294. INT_ON;
  8295. if (pip[1] >= 0) {
  8296. close(pip[0]);
  8297. }
  8298. if (prevfd > 0) {
  8299. dup2(prevfd, 0);
  8300. close(prevfd);
  8301. }
  8302. if (pip[1] > 1) {
  8303. dup2(pip[1], 1);
  8304. close(pip[1]);
  8305. }
  8306. evaltreenr(lp->n, flags);
  8307. /* never returns */
  8308. }
  8309. /* parent */
  8310. if (prevfd >= 0)
  8311. close(prevfd);
  8312. prevfd = pip[0];
  8313. /* Don't want to trigger debugging */
  8314. if (pip[1] != -1)
  8315. close(pip[1]);
  8316. }
  8317. if (n->npipe.pipe_backgnd == 0) {
  8318. status = waitforjob(jp);
  8319. TRACE(("evalpipe: job done exit status %d\n", status));
  8320. }
  8321. INT_ON;
  8322. return status;
  8323. }
  8324. /*
  8325. * Controls whether the shell is interactive or not.
  8326. */
  8327. static void
  8328. setinteractive(int on)
  8329. {
  8330. static smallint is_interactive;
  8331. if (++on == is_interactive)
  8332. return;
  8333. is_interactive = on;
  8334. setsignal(SIGINT);
  8335. setsignal(SIGQUIT);
  8336. setsignal(SIGTERM);
  8337. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8338. if (is_interactive > 1) {
  8339. /* Looks like they want an interactive shell */
  8340. static smallint did_banner;
  8341. if (!did_banner) {
  8342. /* note: ash and hush share this string */
  8343. out1fmt("\n\n%s %s\n"
  8344. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8345. "\n",
  8346. bb_banner,
  8347. "built-in shell (ash)"
  8348. );
  8349. did_banner = 1;
  8350. }
  8351. }
  8352. #endif
  8353. }
  8354. static void
  8355. optschanged(void)
  8356. {
  8357. #if DEBUG
  8358. opentrace();
  8359. #endif
  8360. setinteractive(iflag);
  8361. setjobctl(mflag);
  8362. #if ENABLE_FEATURE_EDITING_VI
  8363. if (viflag)
  8364. line_input_state->flags |= VI_MODE;
  8365. else
  8366. line_input_state->flags &= ~VI_MODE;
  8367. #else
  8368. viflag = 0; /* forcibly keep the option off */
  8369. #endif
  8370. }
  8371. static struct localvar *localvars;
  8372. /*
  8373. * Called after a function returns.
  8374. * Interrupts must be off.
  8375. */
  8376. static void
  8377. poplocalvars(void)
  8378. {
  8379. struct localvar *lvp;
  8380. struct var *vp;
  8381. while ((lvp = localvars) != NULL) {
  8382. localvars = lvp->next;
  8383. vp = lvp->vp;
  8384. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8385. if (vp == NULL) { /* $- saved */
  8386. memcpy(optlist, lvp->text, sizeof(optlist));
  8387. free((char*)lvp->text);
  8388. optschanged();
  8389. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  8390. unsetvar(vp->var_text);
  8391. } else {
  8392. if (vp->var_func)
  8393. vp->var_func(var_end(lvp->text));
  8394. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8395. free((char*)vp->var_text);
  8396. vp->flags = lvp->flags;
  8397. vp->var_text = lvp->text;
  8398. }
  8399. free(lvp);
  8400. }
  8401. }
  8402. static int
  8403. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8404. {
  8405. volatile struct shparam saveparam;
  8406. struct localvar *volatile savelocalvars;
  8407. struct jmploc *volatile savehandler;
  8408. struct jmploc jmploc;
  8409. int e;
  8410. saveparam = shellparam;
  8411. savelocalvars = localvars;
  8412. savehandler = exception_handler;
  8413. e = setjmp(jmploc.loc);
  8414. if (e) {
  8415. goto funcdone;
  8416. }
  8417. INT_OFF;
  8418. exception_handler = &jmploc;
  8419. localvars = NULL;
  8420. shellparam.malloced = 0;
  8421. func->count++;
  8422. funcnest++;
  8423. INT_ON;
  8424. shellparam.nparam = argc - 1;
  8425. shellparam.p = argv + 1;
  8426. #if ENABLE_ASH_GETOPTS
  8427. shellparam.optind = 1;
  8428. shellparam.optoff = -1;
  8429. #endif
  8430. evaltree(func->n.narg.next, flags & EV_TESTED);
  8431. funcdone:
  8432. INT_OFF;
  8433. funcnest--;
  8434. freefunc(func);
  8435. poplocalvars();
  8436. localvars = savelocalvars;
  8437. freeparam(&shellparam);
  8438. shellparam = saveparam;
  8439. exception_handler = savehandler;
  8440. INT_ON;
  8441. evalskip &= ~SKIPFUNC;
  8442. return e;
  8443. }
  8444. /*
  8445. * Make a variable a local variable. When a variable is made local, it's
  8446. * value and flags are saved in a localvar structure. The saved values
  8447. * will be restored when the shell function returns. We handle the name
  8448. * "-" as a special case: it makes changes to "set +-options" local
  8449. * (options will be restored on return from the function).
  8450. */
  8451. static void
  8452. mklocal(char *name)
  8453. {
  8454. struct localvar *lvp;
  8455. struct var **vpp;
  8456. struct var *vp;
  8457. char *eq = strchr(name, '=');
  8458. INT_OFF;
  8459. /* Cater for duplicate "local". Examples:
  8460. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8461. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8462. */
  8463. lvp = localvars;
  8464. while (lvp) {
  8465. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8466. if (eq)
  8467. setvareq(name, 0);
  8468. /* else:
  8469. * it's a duplicate "local VAR" declaration, do nothing
  8470. */
  8471. goto ret;
  8472. }
  8473. lvp = lvp->next;
  8474. }
  8475. lvp = ckzalloc(sizeof(*lvp));
  8476. if (LONE_DASH(name)) {
  8477. char *p;
  8478. p = ckmalloc(sizeof(optlist));
  8479. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8480. vp = NULL;
  8481. } else {
  8482. vpp = hashvar(name);
  8483. vp = *findvar(vpp, name);
  8484. if (vp == NULL) {
  8485. /* variable did not exist yet */
  8486. if (eq)
  8487. setvareq(name, VSTRFIXED);
  8488. else
  8489. setvar(name, NULL, VSTRFIXED);
  8490. vp = *vpp; /* the new variable */
  8491. lvp->flags = VUNSET;
  8492. } else {
  8493. lvp->text = vp->var_text;
  8494. lvp->flags = vp->flags;
  8495. /* make sure neither "struct var" nor string gets freed
  8496. * during (un)setting:
  8497. */
  8498. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8499. if (eq)
  8500. setvareq(name, 0);
  8501. else
  8502. /* "local VAR" unsets VAR: */
  8503. setvar0(name, NULL);
  8504. }
  8505. }
  8506. lvp->vp = vp;
  8507. lvp->next = localvars;
  8508. localvars = lvp;
  8509. ret:
  8510. INT_ON;
  8511. }
  8512. /*
  8513. * The "local" command.
  8514. */
  8515. static int FAST_FUNC
  8516. localcmd(int argc UNUSED_PARAM, char **argv)
  8517. {
  8518. char *name;
  8519. if (!funcnest)
  8520. ash_msg_and_raise_error("not in a function");
  8521. argv = argptr;
  8522. while ((name = *argv++) != NULL) {
  8523. mklocal(name);
  8524. }
  8525. return 0;
  8526. }
  8527. static int FAST_FUNC
  8528. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8529. {
  8530. return 1;
  8531. }
  8532. static int FAST_FUNC
  8533. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8534. {
  8535. return 0;
  8536. }
  8537. static int FAST_FUNC
  8538. execcmd(int argc UNUSED_PARAM, char **argv)
  8539. {
  8540. optionarg = NULL;
  8541. while (nextopt("a:") != '\0')
  8542. /* nextopt() sets optionarg to "-a ARGV0" */;
  8543. argv = argptr;
  8544. if (argv[0]) {
  8545. char *prog;
  8546. iflag = 0; /* exit on error */
  8547. mflag = 0;
  8548. optschanged();
  8549. /* We should set up signals for "exec CMD"
  8550. * the same way as for "CMD" without "exec".
  8551. * But optschanged->setinteractive->setsignal
  8552. * still thought we are a root shell. Therefore, for example,
  8553. * SIGQUIT is still set to IGN. Fix it:
  8554. */
  8555. shlvl++;
  8556. setsignal(SIGQUIT);
  8557. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8558. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8559. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8560. prog = argv[0];
  8561. if (optionarg)
  8562. argv[0] = optionarg;
  8563. shellexec(prog, argv, pathval(), 0);
  8564. /* NOTREACHED */
  8565. }
  8566. return 0;
  8567. }
  8568. /*
  8569. * The return command.
  8570. */
  8571. static int FAST_FUNC
  8572. returncmd(int argc UNUSED_PARAM, char **argv)
  8573. {
  8574. /*
  8575. * If called outside a function, do what ksh does;
  8576. * skip the rest of the file.
  8577. */
  8578. evalskip = SKIPFUNC;
  8579. return argv[1] ? number(argv[1]) : exitstatus;
  8580. }
  8581. /* Forward declarations for builtintab[] */
  8582. static int breakcmd(int, char **) FAST_FUNC;
  8583. static int dotcmd(int, char **) FAST_FUNC;
  8584. static int evalcmd(int, char **, int) FAST_FUNC;
  8585. static int exitcmd(int, char **) FAST_FUNC;
  8586. static int exportcmd(int, char **) FAST_FUNC;
  8587. #if ENABLE_ASH_GETOPTS
  8588. static int getoptscmd(int, char **) FAST_FUNC;
  8589. #endif
  8590. #if ENABLE_ASH_HELP
  8591. static int helpcmd(int, char **) FAST_FUNC;
  8592. #endif
  8593. #if MAX_HISTORY
  8594. static int historycmd(int, char **) FAST_FUNC;
  8595. #endif
  8596. #if ENABLE_FEATURE_SH_MATH
  8597. static int letcmd(int, char **) FAST_FUNC;
  8598. #endif
  8599. static int readcmd(int, char **) FAST_FUNC;
  8600. static int setcmd(int, char **) FAST_FUNC;
  8601. static int shiftcmd(int, char **) FAST_FUNC;
  8602. static int timescmd(int, char **) FAST_FUNC;
  8603. static int trapcmd(int, char **) FAST_FUNC;
  8604. static int umaskcmd(int, char **) FAST_FUNC;
  8605. static int unsetcmd(int, char **) FAST_FUNC;
  8606. static int ulimitcmd(int, char **) FAST_FUNC;
  8607. #define BUILTIN_NOSPEC "0"
  8608. #define BUILTIN_SPECIAL "1"
  8609. #define BUILTIN_REGULAR "2"
  8610. #define BUILTIN_SPEC_REG "3"
  8611. #define BUILTIN_ASSIGN "4"
  8612. #define BUILTIN_SPEC_ASSG "5"
  8613. #define BUILTIN_REG_ASSG "6"
  8614. #define BUILTIN_SPEC_REG_ASSG "7"
  8615. /* Stubs for calling non-FAST_FUNC's */
  8616. #if ENABLE_ASH_ECHO
  8617. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8618. #endif
  8619. #if ENABLE_ASH_PRINTF
  8620. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8621. #endif
  8622. #if ENABLE_ASH_TEST || BASH_TEST2
  8623. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8624. #endif
  8625. /* Keep these in proper order since it is searched via bsearch() */
  8626. static const struct builtincmd builtintab[] = {
  8627. { BUILTIN_SPEC_REG "." , dotcmd },
  8628. { BUILTIN_SPEC_REG ":" , truecmd },
  8629. #if ENABLE_ASH_TEST
  8630. { BUILTIN_REGULAR "[" , testcmd },
  8631. #endif
  8632. #if BASH_TEST2
  8633. { BUILTIN_REGULAR "[[" , testcmd },
  8634. #endif
  8635. #if ENABLE_ASH_ALIAS
  8636. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8637. #endif
  8638. #if JOBS
  8639. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8640. #endif
  8641. { BUILTIN_SPEC_REG "break" , breakcmd },
  8642. { BUILTIN_REGULAR "cd" , cdcmd },
  8643. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8644. #if ENABLE_ASH_CMDCMD
  8645. { BUILTIN_REGULAR "command" , commandcmd },
  8646. #endif
  8647. { BUILTIN_SPEC_REG "continue", breakcmd },
  8648. #if ENABLE_ASH_ECHO
  8649. { BUILTIN_REGULAR "echo" , echocmd },
  8650. #endif
  8651. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  8652. { BUILTIN_SPEC_REG "exec" , execcmd },
  8653. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8654. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8655. { BUILTIN_REGULAR "false" , falsecmd },
  8656. #if JOBS
  8657. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8658. #endif
  8659. #if ENABLE_ASH_GETOPTS
  8660. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8661. #endif
  8662. { BUILTIN_NOSPEC "hash" , hashcmd },
  8663. #if ENABLE_ASH_HELP
  8664. { BUILTIN_NOSPEC "help" , helpcmd },
  8665. #endif
  8666. #if MAX_HISTORY
  8667. { BUILTIN_NOSPEC "history" , historycmd },
  8668. #endif
  8669. #if JOBS
  8670. { BUILTIN_REGULAR "jobs" , jobscmd },
  8671. { BUILTIN_REGULAR "kill" , killcmd },
  8672. #endif
  8673. #if ENABLE_FEATURE_SH_MATH
  8674. { BUILTIN_NOSPEC "let" , letcmd },
  8675. #endif
  8676. { BUILTIN_ASSIGN "local" , localcmd },
  8677. #if ENABLE_ASH_PRINTF
  8678. { BUILTIN_REGULAR "printf" , printfcmd },
  8679. #endif
  8680. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8681. { BUILTIN_REGULAR "read" , readcmd },
  8682. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8683. { BUILTIN_SPEC_REG "return" , returncmd },
  8684. { BUILTIN_SPEC_REG "set" , setcmd },
  8685. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8686. #if BASH_SOURCE
  8687. { BUILTIN_SPEC_REG "source" , dotcmd },
  8688. #endif
  8689. #if ENABLE_ASH_TEST
  8690. { BUILTIN_REGULAR "test" , testcmd },
  8691. #endif
  8692. { BUILTIN_SPEC_REG "times" , timescmd },
  8693. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8694. { BUILTIN_REGULAR "true" , truecmd },
  8695. { BUILTIN_NOSPEC "type" , typecmd },
  8696. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8697. { BUILTIN_REGULAR "umask" , umaskcmd },
  8698. #if ENABLE_ASH_ALIAS
  8699. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8700. #endif
  8701. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8702. { BUILTIN_REGULAR "wait" , waitcmd },
  8703. };
  8704. /* Should match the above table! */
  8705. #define COMMANDCMD (builtintab + \
  8706. /* . : */ 2 + \
  8707. /* [ */ 1 * ENABLE_ASH_TEST + \
  8708. /* [[ */ 1 * BASH_TEST2 + \
  8709. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  8710. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  8711. /* break cd cddir */ 3)
  8712. #define EVALCMD (COMMANDCMD + \
  8713. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  8714. /* continue */ 1 + \
  8715. /* echo */ 1 * ENABLE_ASH_ECHO + \
  8716. 0)
  8717. #define EXECCMD (EVALCMD + \
  8718. /* eval */ 1)
  8719. /*
  8720. * Search the table of builtin commands.
  8721. */
  8722. static int
  8723. pstrcmp1(const void *a, const void *b)
  8724. {
  8725. return strcmp((char*)a, *(char**)b + 1);
  8726. }
  8727. static struct builtincmd *
  8728. find_builtin(const char *name)
  8729. {
  8730. struct builtincmd *bp;
  8731. bp = bsearch(
  8732. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8733. pstrcmp1
  8734. );
  8735. return bp;
  8736. }
  8737. /*
  8738. * Execute a simple command.
  8739. */
  8740. static int
  8741. isassignment(const char *p)
  8742. {
  8743. const char *q = endofname(p);
  8744. if (p == q)
  8745. return 0;
  8746. return *q == '=';
  8747. }
  8748. static int FAST_FUNC
  8749. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8750. {
  8751. /* Preserve exitstatus of a previous possible redirection
  8752. * as POSIX mandates */
  8753. return back_exitstatus;
  8754. }
  8755. static int
  8756. evalcommand(union node *cmd, int flags)
  8757. {
  8758. static const struct builtincmd null_bltin = {
  8759. "\0\0", bltincmd /* why three NULs? */
  8760. };
  8761. struct stackmark smark;
  8762. union node *argp;
  8763. struct arglist arglist;
  8764. struct arglist varlist;
  8765. char **argv;
  8766. int argc;
  8767. const struct strlist *sp;
  8768. struct cmdentry cmdentry;
  8769. struct job *jp;
  8770. char *lastarg;
  8771. const char *path;
  8772. int spclbltin;
  8773. int status;
  8774. char **nargv;
  8775. struct builtincmd *bcmd;
  8776. smallint cmd_is_exec;
  8777. smallint pseudovarflag = 0;
  8778. /* First expand the arguments. */
  8779. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8780. setstackmark(&smark);
  8781. back_exitstatus = 0;
  8782. cmdentry.cmdtype = CMDBUILTIN;
  8783. cmdentry.u.cmd = &null_bltin;
  8784. varlist.lastp = &varlist.list;
  8785. *varlist.lastp = NULL;
  8786. arglist.lastp = &arglist.list;
  8787. *arglist.lastp = NULL;
  8788. argc = 0;
  8789. if (cmd->ncmd.args) {
  8790. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8791. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8792. }
  8793. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8794. struct strlist **spp;
  8795. spp = arglist.lastp;
  8796. if (pseudovarflag && isassignment(argp->narg.text))
  8797. expandarg(argp, &arglist, EXP_VARTILDE);
  8798. else
  8799. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8800. for (sp = *spp; sp; sp = sp->next)
  8801. argc++;
  8802. }
  8803. /* Reserve one extra spot at the front for shellexec. */
  8804. nargv = stalloc(sizeof(char *) * (argc + 2));
  8805. argv = ++nargv;
  8806. for (sp = arglist.list; sp; sp = sp->next) {
  8807. TRACE(("evalcommand arg: %s\n", sp->text));
  8808. *nargv++ = sp->text;
  8809. }
  8810. *nargv = NULL;
  8811. lastarg = NULL;
  8812. if (iflag && funcnest == 0 && argc > 0)
  8813. lastarg = nargv[-1];
  8814. preverrout_fd = 2;
  8815. expredir(cmd->ncmd.redirect);
  8816. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8817. path = vpath.var_text;
  8818. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8819. struct strlist **spp;
  8820. char *p;
  8821. spp = varlist.lastp;
  8822. expandarg(argp, &varlist, EXP_VARTILDE);
  8823. /*
  8824. * Modify the command lookup path, if a PATH= assignment
  8825. * is present
  8826. */
  8827. p = (*spp)->text;
  8828. if (varcmp(p, path) == 0)
  8829. path = p;
  8830. }
  8831. /* Print the command if xflag is set. */
  8832. if (xflag) {
  8833. int n;
  8834. const char *p = " %s" + 1;
  8835. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8836. sp = varlist.list;
  8837. for (n = 0; n < 2; n++) {
  8838. while (sp) {
  8839. fdprintf(preverrout_fd, p, sp->text);
  8840. sp = sp->next;
  8841. p = " %s";
  8842. }
  8843. sp = arglist.list;
  8844. }
  8845. safe_write(preverrout_fd, "\n", 1);
  8846. }
  8847. cmd_is_exec = 0;
  8848. spclbltin = -1;
  8849. /* Now locate the command. */
  8850. if (argc) {
  8851. int cmd_flag = DO_ERR;
  8852. #if ENABLE_ASH_CMDCMD
  8853. const char *oldpath = path + 5;
  8854. #endif
  8855. path += 5;
  8856. for (;;) {
  8857. find_command(argv[0], &cmdentry, cmd_flag, path);
  8858. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8859. flush_stdout_stderr();
  8860. status = 127;
  8861. goto bail;
  8862. }
  8863. /* implement bltin and command here */
  8864. if (cmdentry.cmdtype != CMDBUILTIN)
  8865. break;
  8866. if (spclbltin < 0)
  8867. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8868. if (cmdentry.u.cmd == EXECCMD)
  8869. cmd_is_exec = 1;
  8870. #if ENABLE_ASH_CMDCMD
  8871. if (cmdentry.u.cmd == COMMANDCMD) {
  8872. path = oldpath;
  8873. nargv = parse_command_args(argv, &path);
  8874. if (!nargv)
  8875. break;
  8876. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  8877. * nargv => "PROG". path is updated if -p.
  8878. */
  8879. argc -= nargv - argv;
  8880. argv = nargv;
  8881. cmd_flag |= DO_NOFUNC;
  8882. } else
  8883. #endif
  8884. break;
  8885. }
  8886. }
  8887. if (status) {
  8888. bail:
  8889. exitstatus = status;
  8890. /* We have a redirection error. */
  8891. if (spclbltin > 0)
  8892. raise_exception(EXERROR);
  8893. goto out;
  8894. }
  8895. /* Execute the command. */
  8896. switch (cmdentry.cmdtype) {
  8897. default: {
  8898. #if ENABLE_FEATURE_SH_NOFORK
  8899. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  8900. * around run_nofork_applet() call.
  8901. * (2) Should this check also be done in forkshell()?
  8902. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  8903. */
  8904. /* find_command() encodes applet_no as (-2 - applet_no) */
  8905. int applet_no = (- cmdentry.u.index - 2);
  8906. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8907. listsetvar(varlist.list, VEXPORT|VSTACK);
  8908. /* run <applet>_main() */
  8909. status = run_nofork_applet(applet_no, argv);
  8910. break;
  8911. }
  8912. #endif
  8913. /* Can we avoid forking off? For example, very last command
  8914. * in a script or a subshell does not need forking,
  8915. * we can just exec it.
  8916. */
  8917. if (!(flags & EV_EXIT) || may_have_traps) {
  8918. /* No, forking off a child is necessary */
  8919. INT_OFF;
  8920. get_tty_state();
  8921. jp = makejob(/*cmd,*/ 1);
  8922. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8923. /* parent */
  8924. status = waitforjob(jp);
  8925. INT_ON;
  8926. TRACE(("forked child exited with %d\n", status));
  8927. break;
  8928. }
  8929. /* child */
  8930. FORCE_INT_ON;
  8931. /* fall through to exec'ing external program */
  8932. }
  8933. listsetvar(varlist.list, VEXPORT|VSTACK);
  8934. shellexec(argv[0], argv, path, cmdentry.u.index);
  8935. /* NOTREACHED */
  8936. } /* default */
  8937. case CMDBUILTIN:
  8938. cmdenviron = varlist.list;
  8939. if (cmdenviron) {
  8940. struct strlist *list = cmdenviron;
  8941. int i = VNOSET;
  8942. if (spclbltin > 0 || argc == 0) {
  8943. i = 0;
  8944. if (cmd_is_exec && argc > 1)
  8945. i = VEXPORT;
  8946. }
  8947. listsetvar(list, i);
  8948. }
  8949. /* Tight loop with builtins only:
  8950. * "while kill -0 $child; do true; done"
  8951. * will never exit even if $child died, unless we do this
  8952. * to reap the zombie and make kill detect that it's gone: */
  8953. dowait(DOWAIT_NONBLOCK, NULL);
  8954. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  8955. if (exception_type == EXERROR && spclbltin <= 0) {
  8956. FORCE_INT_ON;
  8957. goto readstatus;
  8958. }
  8959. raise:
  8960. longjmp(exception_handler->loc, 1);
  8961. }
  8962. goto readstatus;
  8963. case CMDFUNCTION:
  8964. listsetvar(varlist.list, 0);
  8965. /* See above for the rationale */
  8966. dowait(DOWAIT_NONBLOCK, NULL);
  8967. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8968. goto raise;
  8969. readstatus:
  8970. status = exitstatus;
  8971. break;
  8972. } /* switch */
  8973. out:
  8974. if (cmd->ncmd.redirect)
  8975. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8976. if (lastarg) {
  8977. /* dsl: I think this is intended to be used to support
  8978. * '_' in 'vi' command mode during line editing...
  8979. * However I implemented that within libedit itself.
  8980. */
  8981. setvar0("_", lastarg);
  8982. }
  8983. popstackmark(&smark);
  8984. return status;
  8985. }
  8986. static int
  8987. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  8988. {
  8989. char *volatile savecmdname;
  8990. struct jmploc *volatile savehandler;
  8991. struct jmploc jmploc;
  8992. int status;
  8993. int i;
  8994. savecmdname = commandname;
  8995. savehandler = exception_handler;
  8996. i = setjmp(jmploc.loc);
  8997. if (i)
  8998. goto cmddone;
  8999. exception_handler = &jmploc;
  9000. commandname = argv[0];
  9001. argptr = argv + 1;
  9002. optptr = NULL; /* initialize nextopt */
  9003. if (cmd == EVALCMD)
  9004. status = evalcmd(argc, argv, flags);
  9005. else
  9006. status = (*cmd->builtin)(argc, argv);
  9007. flush_stdout_stderr();
  9008. status |= ferror(stdout);
  9009. exitstatus = status;
  9010. cmddone:
  9011. clearerr(stdout);
  9012. commandname = savecmdname;
  9013. exception_handler = savehandler;
  9014. return i;
  9015. }
  9016. static int
  9017. goodname(const char *p)
  9018. {
  9019. return endofname(p)[0] == '\0';
  9020. }
  9021. /*
  9022. * Search for a command. This is called before we fork so that the
  9023. * location of the command will be available in the parent as well as
  9024. * the child. The check for "goodname" is an overly conservative
  9025. * check that the name will not be subject to expansion.
  9026. */
  9027. static void
  9028. prehash(union node *n)
  9029. {
  9030. struct cmdentry entry;
  9031. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9032. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9033. }
  9034. /* ============ Builtin commands
  9035. *
  9036. * Builtin commands whose functions are closely tied to evaluation
  9037. * are implemented here.
  9038. */
  9039. /*
  9040. * Handle break and continue commands. Break, continue, and return are
  9041. * all handled by setting the evalskip flag. The evaluation routines
  9042. * above all check this flag, and if it is set they start skipping
  9043. * commands rather than executing them. The variable skipcount is
  9044. * the number of loops to break/continue, or the number of function
  9045. * levels to return. (The latter is always 1.) It should probably
  9046. * be an error to break out of more loops than exist, but it isn't
  9047. * in the standard shell so we don't make it one here.
  9048. */
  9049. static int FAST_FUNC
  9050. breakcmd(int argc UNUSED_PARAM, char **argv)
  9051. {
  9052. int n = argv[1] ? number(argv[1]) : 1;
  9053. if (n <= 0)
  9054. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9055. if (n > loopnest)
  9056. n = loopnest;
  9057. if (n > 0) {
  9058. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9059. skipcount = n;
  9060. }
  9061. return 0;
  9062. }
  9063. /*
  9064. * This implements the input routines used by the parser.
  9065. */
  9066. enum {
  9067. INPUT_PUSH_FILE = 1,
  9068. INPUT_NOFILE_OK = 2,
  9069. };
  9070. static smallint checkkwd;
  9071. /* values of checkkwd variable */
  9072. #define CHKALIAS 0x1
  9073. #define CHKKWD 0x2
  9074. #define CHKNL 0x4
  9075. /*
  9076. * Push a string back onto the input at this current parsefile level.
  9077. * We handle aliases this way.
  9078. */
  9079. #if !ENABLE_ASH_ALIAS
  9080. #define pushstring(s, ap) pushstring(s)
  9081. #endif
  9082. static void
  9083. pushstring(char *s, struct alias *ap)
  9084. {
  9085. struct strpush *sp;
  9086. int len;
  9087. len = strlen(s);
  9088. INT_OFF;
  9089. if (g_parsefile->strpush) {
  9090. sp = ckzalloc(sizeof(*sp));
  9091. sp->prev = g_parsefile->strpush;
  9092. } else {
  9093. sp = &(g_parsefile->basestrpush);
  9094. }
  9095. g_parsefile->strpush = sp;
  9096. sp->prev_string = g_parsefile->next_to_pgetc;
  9097. sp->prev_left_in_line = g_parsefile->left_in_line;
  9098. sp->unget = g_parsefile->unget;
  9099. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9100. #if ENABLE_ASH_ALIAS
  9101. sp->ap = ap;
  9102. if (ap) {
  9103. ap->flag |= ALIASINUSE;
  9104. sp->string = s;
  9105. }
  9106. #endif
  9107. g_parsefile->next_to_pgetc = s;
  9108. g_parsefile->left_in_line = len;
  9109. g_parsefile->unget = 0;
  9110. INT_ON;
  9111. }
  9112. static void
  9113. popstring(void)
  9114. {
  9115. struct strpush *sp = g_parsefile->strpush;
  9116. INT_OFF;
  9117. #if ENABLE_ASH_ALIAS
  9118. if (sp->ap) {
  9119. if (g_parsefile->next_to_pgetc[-1] == ' '
  9120. || g_parsefile->next_to_pgetc[-1] == '\t'
  9121. ) {
  9122. checkkwd |= CHKALIAS;
  9123. }
  9124. if (sp->string != sp->ap->val) {
  9125. free(sp->string);
  9126. }
  9127. sp->ap->flag &= ~ALIASINUSE;
  9128. if (sp->ap->flag & ALIASDEAD) {
  9129. unalias(sp->ap->name);
  9130. }
  9131. }
  9132. #endif
  9133. g_parsefile->next_to_pgetc = sp->prev_string;
  9134. g_parsefile->left_in_line = sp->prev_left_in_line;
  9135. g_parsefile->unget = sp->unget;
  9136. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9137. g_parsefile->strpush = sp->prev;
  9138. if (sp != &(g_parsefile->basestrpush))
  9139. free(sp);
  9140. INT_ON;
  9141. }
  9142. static int
  9143. preadfd(void)
  9144. {
  9145. int nr;
  9146. char *buf = g_parsefile->buf;
  9147. g_parsefile->next_to_pgetc = buf;
  9148. #if ENABLE_FEATURE_EDITING
  9149. retry:
  9150. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9151. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9152. else {
  9153. int timeout = -1;
  9154. # if ENABLE_ASH_IDLE_TIMEOUT
  9155. if (iflag) {
  9156. const char *tmout_var = lookupvar("TMOUT");
  9157. if (tmout_var) {
  9158. timeout = atoi(tmout_var) * 1000;
  9159. if (timeout <= 0)
  9160. timeout = -1;
  9161. }
  9162. }
  9163. # endif
  9164. # if ENABLE_FEATURE_TAB_COMPLETION
  9165. line_input_state->path_lookup = pathval();
  9166. # endif
  9167. reinit_unicode_for_ash();
  9168. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
  9169. if (nr == 0) {
  9170. /* ^C pressed, "convert" to SIGINT */
  9171. write(STDOUT_FILENO, "^C", 2);
  9172. if (trap[SIGINT]) {
  9173. buf[0] = '\n';
  9174. buf[1] = '\0';
  9175. raise(SIGINT);
  9176. return 1;
  9177. }
  9178. exitstatus = 128 + SIGINT;
  9179. bb_putchar('\n');
  9180. goto retry;
  9181. }
  9182. if (nr < 0) {
  9183. if (errno == 0) {
  9184. /* Ctrl+D pressed */
  9185. nr = 0;
  9186. }
  9187. # if ENABLE_ASH_IDLE_TIMEOUT
  9188. else if (errno == EAGAIN && timeout > 0) {
  9189. puts("\007timed out waiting for input: auto-logout");
  9190. exitshell();
  9191. }
  9192. # endif
  9193. }
  9194. }
  9195. #else
  9196. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9197. #endif
  9198. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9199. if (nr < 0) {
  9200. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9201. int flags = fcntl(0, F_GETFL);
  9202. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9203. flags &= ~O_NONBLOCK;
  9204. if (fcntl(0, F_SETFL, flags) >= 0) {
  9205. out2str("sh: turning off NDELAY mode\n");
  9206. goto retry;
  9207. }
  9208. }
  9209. }
  9210. }
  9211. #endif
  9212. return nr;
  9213. }
  9214. /*
  9215. * Refill the input buffer and return the next input character:
  9216. *
  9217. * 1) If a string was pushed back on the input, pop it;
  9218. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9219. * or we are reading from a string so we can't refill the buffer,
  9220. * return EOF.
  9221. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9222. * 4) Process input up to the next newline, deleting nul characters.
  9223. */
  9224. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9225. #define pgetc_debug(...) ((void)0)
  9226. static int pgetc(void);
  9227. static int
  9228. preadbuffer(void)
  9229. {
  9230. char *q;
  9231. int more;
  9232. if (g_parsefile->strpush) {
  9233. #if ENABLE_ASH_ALIAS
  9234. if (g_parsefile->left_in_line == -1
  9235. && g_parsefile->strpush->ap
  9236. && g_parsefile->next_to_pgetc[-1] != ' '
  9237. && g_parsefile->next_to_pgetc[-1] != '\t'
  9238. ) {
  9239. pgetc_debug("preadbuffer PEOA");
  9240. return PEOA;
  9241. }
  9242. #endif
  9243. popstring();
  9244. return pgetc();
  9245. }
  9246. /* on both branches above g_parsefile->left_in_line < 0.
  9247. * "pgetc" needs refilling.
  9248. */
  9249. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9250. * pungetc() may increment it a few times.
  9251. * Assuming it won't increment it to less than -90.
  9252. */
  9253. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9254. pgetc_debug("preadbuffer PEOF1");
  9255. /* even in failure keep left_in_line and next_to_pgetc
  9256. * in lock step, for correct multi-layer pungetc.
  9257. * left_in_line was decremented before preadbuffer(),
  9258. * must inc next_to_pgetc: */
  9259. g_parsefile->next_to_pgetc++;
  9260. return PEOF;
  9261. }
  9262. more = g_parsefile->left_in_buffer;
  9263. if (more <= 0) {
  9264. flush_stdout_stderr();
  9265. again:
  9266. more = preadfd();
  9267. if (more <= 0) {
  9268. /* don't try reading again */
  9269. g_parsefile->left_in_line = -99;
  9270. pgetc_debug("preadbuffer PEOF2");
  9271. g_parsefile->next_to_pgetc++;
  9272. return PEOF;
  9273. }
  9274. }
  9275. /* Find out where's the end of line.
  9276. * Set g_parsefile->left_in_line
  9277. * and g_parsefile->left_in_buffer acordingly.
  9278. * NUL chars are deleted.
  9279. */
  9280. q = g_parsefile->next_to_pgetc;
  9281. for (;;) {
  9282. char c;
  9283. more--;
  9284. c = *q;
  9285. if (c == '\0') {
  9286. memmove(q, q + 1, more);
  9287. } else {
  9288. q++;
  9289. if (c == '\n') {
  9290. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9291. break;
  9292. }
  9293. }
  9294. if (more <= 0) {
  9295. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9296. if (g_parsefile->left_in_line < 0)
  9297. goto again;
  9298. break;
  9299. }
  9300. }
  9301. g_parsefile->left_in_buffer = more;
  9302. if (vflag) {
  9303. char save = *q;
  9304. *q = '\0';
  9305. out2str(g_parsefile->next_to_pgetc);
  9306. *q = save;
  9307. }
  9308. pgetc_debug("preadbuffer at %d:%p'%s'",
  9309. g_parsefile->left_in_line,
  9310. g_parsefile->next_to_pgetc,
  9311. g_parsefile->next_to_pgetc);
  9312. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9313. }
  9314. static void
  9315. nlprompt(void)
  9316. {
  9317. g_parsefile->linno++;
  9318. setprompt_if(doprompt, 2);
  9319. }
  9320. static void
  9321. nlnoprompt(void)
  9322. {
  9323. g_parsefile->linno++;
  9324. needprompt = doprompt;
  9325. }
  9326. static int
  9327. pgetc(void)
  9328. {
  9329. int c;
  9330. pgetc_debug("pgetc at %d:%p'%s'",
  9331. g_parsefile->left_in_line,
  9332. g_parsefile->next_to_pgetc,
  9333. g_parsefile->next_to_pgetc);
  9334. if (g_parsefile->unget)
  9335. return g_parsefile->lastc[--g_parsefile->unget];
  9336. if (--g_parsefile->left_in_line >= 0)
  9337. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9338. else
  9339. c = preadbuffer();
  9340. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9341. g_parsefile->lastc[0] = c;
  9342. return c;
  9343. }
  9344. #if ENABLE_ASH_ALIAS
  9345. static int
  9346. pgetc_without_PEOA(void)
  9347. {
  9348. int c;
  9349. do {
  9350. pgetc_debug("pgetc at %d:%p'%s'",
  9351. g_parsefile->left_in_line,
  9352. g_parsefile->next_to_pgetc,
  9353. g_parsefile->next_to_pgetc);
  9354. c = pgetc();
  9355. } while (c == PEOA);
  9356. return c;
  9357. }
  9358. #else
  9359. # define pgetc_without_PEOA() pgetc()
  9360. #endif
  9361. /*
  9362. * Read a line from the script.
  9363. */
  9364. static char *
  9365. pfgets(char *line, int len)
  9366. {
  9367. char *p = line;
  9368. int nleft = len;
  9369. int c;
  9370. while (--nleft > 0) {
  9371. c = pgetc_without_PEOA();
  9372. if (c == PEOF) {
  9373. if (p == line)
  9374. return NULL;
  9375. break;
  9376. }
  9377. *p++ = c;
  9378. if (c == '\n')
  9379. break;
  9380. }
  9381. *p = '\0';
  9382. return line;
  9383. }
  9384. /*
  9385. * Undo a call to pgetc. Only two characters may be pushed back.
  9386. * PEOF may be pushed back.
  9387. */
  9388. static void
  9389. pungetc(void)
  9390. {
  9391. g_parsefile->unget++;
  9392. }
  9393. /* This one eats backslash+newline */
  9394. static int
  9395. pgetc_eatbnl(void)
  9396. {
  9397. int c;
  9398. while ((c = pgetc()) == '\\') {
  9399. if (pgetc() != '\n') {
  9400. pungetc();
  9401. break;
  9402. }
  9403. nlprompt();
  9404. }
  9405. return c;
  9406. }
  9407. /*
  9408. * To handle the "." command, a stack of input files is used. Pushfile
  9409. * adds a new entry to the stack and popfile restores the previous level.
  9410. */
  9411. static void
  9412. pushfile(void)
  9413. {
  9414. struct parsefile *pf;
  9415. pf = ckzalloc(sizeof(*pf));
  9416. pf->prev = g_parsefile;
  9417. pf->pf_fd = -1;
  9418. /*pf->strpush = NULL; - ckzalloc did it */
  9419. /*pf->basestrpush.prev = NULL;*/
  9420. /*pf->unget = 0;*/
  9421. g_parsefile = pf;
  9422. }
  9423. static void
  9424. popfile(void)
  9425. {
  9426. struct parsefile *pf = g_parsefile;
  9427. if (pf == &basepf)
  9428. return;
  9429. INT_OFF;
  9430. if (pf->pf_fd >= 0)
  9431. close(pf->pf_fd);
  9432. free(pf->buf);
  9433. while (pf->strpush)
  9434. popstring();
  9435. g_parsefile = pf->prev;
  9436. free(pf);
  9437. INT_ON;
  9438. }
  9439. /*
  9440. * Return to top level.
  9441. */
  9442. static void
  9443. popallfiles(void)
  9444. {
  9445. while (g_parsefile != &basepf)
  9446. popfile();
  9447. }
  9448. /*
  9449. * Close the file(s) that the shell is reading commands from. Called
  9450. * after a fork is done.
  9451. */
  9452. static void
  9453. closescript(void)
  9454. {
  9455. popallfiles();
  9456. if (g_parsefile->pf_fd > 0) {
  9457. close(g_parsefile->pf_fd);
  9458. g_parsefile->pf_fd = 0;
  9459. }
  9460. }
  9461. /*
  9462. * Like setinputfile, but takes an open file descriptor. Call this with
  9463. * interrupts off.
  9464. */
  9465. static void
  9466. setinputfd(int fd, int push)
  9467. {
  9468. if (push) {
  9469. pushfile();
  9470. g_parsefile->buf = NULL;
  9471. }
  9472. g_parsefile->pf_fd = fd;
  9473. if (g_parsefile->buf == NULL)
  9474. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9475. g_parsefile->left_in_buffer = 0;
  9476. g_parsefile->left_in_line = 0;
  9477. g_parsefile->linno = 1;
  9478. }
  9479. /*
  9480. * Set the input to take input from a file. If push is set, push the
  9481. * old input onto the stack first.
  9482. */
  9483. static int
  9484. setinputfile(const char *fname, int flags)
  9485. {
  9486. int fd;
  9487. INT_OFF;
  9488. fd = open(fname, O_RDONLY);
  9489. if (fd < 0) {
  9490. if (flags & INPUT_NOFILE_OK)
  9491. goto out;
  9492. exitstatus = 127;
  9493. ash_msg_and_raise_error("can't open '%s'", fname);
  9494. }
  9495. if (fd < 10)
  9496. fd = savefd(fd);
  9497. else
  9498. close_on_exec_on(fd);
  9499. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9500. out:
  9501. INT_ON;
  9502. return fd;
  9503. }
  9504. /*
  9505. * Like setinputfile, but takes input from a string.
  9506. */
  9507. static void
  9508. setinputstring(char *string)
  9509. {
  9510. INT_OFF;
  9511. pushfile();
  9512. g_parsefile->next_to_pgetc = string;
  9513. g_parsefile->left_in_line = strlen(string);
  9514. g_parsefile->buf = NULL;
  9515. g_parsefile->linno = 1;
  9516. INT_ON;
  9517. }
  9518. /*
  9519. * Routines to check for mail.
  9520. */
  9521. #if ENABLE_ASH_MAIL
  9522. /* Hash of mtimes of mailboxes */
  9523. static unsigned mailtime_hash;
  9524. /* Set if MAIL or MAILPATH is changed. */
  9525. static smallint mail_var_path_changed;
  9526. /*
  9527. * Print appropriate message(s) if mail has arrived.
  9528. * If mail_var_path_changed is set,
  9529. * then the value of MAIL has mail_var_path_changed,
  9530. * so we just update the values.
  9531. */
  9532. static void
  9533. chkmail(void)
  9534. {
  9535. const char *mpath;
  9536. char *p;
  9537. char *q;
  9538. unsigned new_hash;
  9539. struct stackmark smark;
  9540. struct stat statb;
  9541. setstackmark(&smark);
  9542. mpath = mpathset() ? mpathval() : mailval();
  9543. new_hash = 0;
  9544. for (;;) {
  9545. p = path_advance(&mpath, nullstr);
  9546. if (p == NULL)
  9547. break;
  9548. if (*p == '\0')
  9549. continue;
  9550. for (q = p; *q; q++)
  9551. continue;
  9552. #if DEBUG
  9553. if (q[-1] != '/')
  9554. abort();
  9555. #endif
  9556. q[-1] = '\0'; /* delete trailing '/' */
  9557. if (stat(p, &statb) < 0) {
  9558. continue;
  9559. }
  9560. /* Very simplistic "hash": just a sum of all mtimes */
  9561. new_hash += (unsigned)statb.st_mtime;
  9562. }
  9563. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9564. if (mailtime_hash != 0)
  9565. out2str("you have mail\n");
  9566. mailtime_hash = new_hash;
  9567. }
  9568. mail_var_path_changed = 0;
  9569. popstackmark(&smark);
  9570. }
  9571. static void FAST_FUNC
  9572. changemail(const char *val UNUSED_PARAM)
  9573. {
  9574. mail_var_path_changed = 1;
  9575. }
  9576. #endif /* ASH_MAIL */
  9577. /* ============ ??? */
  9578. /*
  9579. * Set the shell parameters.
  9580. */
  9581. static void
  9582. setparam(char **argv)
  9583. {
  9584. char **newparam;
  9585. char **ap;
  9586. int nparam;
  9587. for (nparam = 0; argv[nparam]; nparam++)
  9588. continue;
  9589. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9590. while (*argv) {
  9591. *ap++ = ckstrdup(*argv++);
  9592. }
  9593. *ap = NULL;
  9594. freeparam(&shellparam);
  9595. shellparam.malloced = 1;
  9596. shellparam.nparam = nparam;
  9597. shellparam.p = newparam;
  9598. #if ENABLE_ASH_GETOPTS
  9599. shellparam.optind = 1;
  9600. shellparam.optoff = -1;
  9601. #endif
  9602. }
  9603. /*
  9604. * Process shell options. The global variable argptr contains a pointer
  9605. * to the argument list; we advance it past the options.
  9606. *
  9607. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9608. * For a non-interactive shell, an error condition encountered
  9609. * by a special built-in ... shall cause the shell to write a diagnostic message
  9610. * to standard error and exit as shown in the following table:
  9611. * Error Special Built-In
  9612. * ...
  9613. * Utility syntax error (option or operand error) Shall exit
  9614. * ...
  9615. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9616. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9617. * and shell continues), and people rely on this behavior!
  9618. * Testcase:
  9619. * set -o barfoo 2>/dev/null
  9620. * echo $?
  9621. *
  9622. * Oh well. Let's mimic that.
  9623. */
  9624. static int
  9625. plus_minus_o(char *name, int val)
  9626. {
  9627. int i;
  9628. if (name) {
  9629. for (i = 0; i < NOPTS; i++) {
  9630. if (strcmp(name, optnames(i)) == 0) {
  9631. optlist[i] = val;
  9632. return 0;
  9633. }
  9634. }
  9635. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9636. return 1;
  9637. }
  9638. for (i = 0; i < NOPTS; i++) {
  9639. if (val) {
  9640. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9641. } else {
  9642. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9643. }
  9644. }
  9645. return 0;
  9646. }
  9647. static void
  9648. setoption(int flag, int val)
  9649. {
  9650. int i;
  9651. for (i = 0; i < NOPTS; i++) {
  9652. if (optletters(i) == flag) {
  9653. optlist[i] = val;
  9654. return;
  9655. }
  9656. }
  9657. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9658. /* NOTREACHED */
  9659. }
  9660. static int
  9661. options(int cmdline)
  9662. {
  9663. char *p;
  9664. int val;
  9665. int c;
  9666. if (cmdline)
  9667. minusc = NULL;
  9668. while ((p = *argptr) != NULL) {
  9669. c = *p++;
  9670. if (c != '-' && c != '+')
  9671. break;
  9672. argptr++;
  9673. val = 0; /* val = 0 if c == '+' */
  9674. if (c == '-') {
  9675. val = 1;
  9676. if (p[0] == '\0' || LONE_DASH(p)) {
  9677. if (!cmdline) {
  9678. /* "-" means turn off -x and -v */
  9679. if (p[0] == '\0')
  9680. xflag = vflag = 0;
  9681. /* "--" means reset params */
  9682. else if (*argptr == NULL)
  9683. setparam(argptr);
  9684. }
  9685. break; /* "-" or "--" terminates options */
  9686. }
  9687. }
  9688. /* first char was + or - */
  9689. while ((c = *p++) != '\0') {
  9690. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9691. if (c == 'c' && cmdline) {
  9692. minusc = p; /* command is after shell args */
  9693. } else if (c == 'o') {
  9694. if (plus_minus_o(*argptr, val)) {
  9695. /* it already printed err message */
  9696. return 1; /* error */
  9697. }
  9698. if (*argptr)
  9699. argptr++;
  9700. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9701. isloginsh = 1;
  9702. /* bash does not accept +-login, we also won't */
  9703. } else if (cmdline && val && (c == '-')) { /* long options */
  9704. if (strcmp(p, "login") == 0)
  9705. isloginsh = 1;
  9706. break;
  9707. } else {
  9708. setoption(c, val);
  9709. }
  9710. }
  9711. }
  9712. return 0;
  9713. }
  9714. /*
  9715. * The shift builtin command.
  9716. */
  9717. static int FAST_FUNC
  9718. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9719. {
  9720. int n;
  9721. char **ap1, **ap2;
  9722. n = 1;
  9723. if (argv[1])
  9724. n = number(argv[1]);
  9725. if (n > shellparam.nparam)
  9726. n = 0; /* bash compat, was = shellparam.nparam; */
  9727. INT_OFF;
  9728. shellparam.nparam -= n;
  9729. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9730. if (shellparam.malloced)
  9731. free(*ap1);
  9732. }
  9733. ap2 = shellparam.p;
  9734. while ((*ap2++ = *ap1++) != NULL)
  9735. continue;
  9736. #if ENABLE_ASH_GETOPTS
  9737. shellparam.optind = 1;
  9738. shellparam.optoff = -1;
  9739. #endif
  9740. INT_ON;
  9741. return 0;
  9742. }
  9743. /*
  9744. * POSIX requires that 'set' (but not export or readonly) output the
  9745. * variables in lexicographic order - by the locale's collating order (sigh).
  9746. * Maybe we could keep them in an ordered balanced binary tree
  9747. * instead of hashed lists.
  9748. * For now just roll 'em through qsort for printing...
  9749. */
  9750. static int
  9751. showvars(const char *sep_prefix, int on, int off)
  9752. {
  9753. const char *sep;
  9754. char **ep, **epend;
  9755. ep = listvars(on, off, &epend);
  9756. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9757. sep = *sep_prefix ? " " : sep_prefix;
  9758. for (; ep < epend; ep++) {
  9759. const char *p;
  9760. const char *q;
  9761. p = strchrnul(*ep, '=');
  9762. q = nullstr;
  9763. if (*p)
  9764. q = single_quote(++p);
  9765. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9766. }
  9767. return 0;
  9768. }
  9769. /*
  9770. * The set command builtin.
  9771. */
  9772. static int FAST_FUNC
  9773. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9774. {
  9775. int retval;
  9776. if (!argv[1])
  9777. return showvars(nullstr, 0, VUNSET);
  9778. INT_OFF;
  9779. retval = options(/*cmdline:*/ 0);
  9780. if (retval == 0) { /* if no parse error... */
  9781. optschanged();
  9782. if (*argptr != NULL) {
  9783. setparam(argptr);
  9784. }
  9785. }
  9786. INT_ON;
  9787. return retval;
  9788. }
  9789. #if ENABLE_ASH_RANDOM_SUPPORT
  9790. static void FAST_FUNC
  9791. change_random(const char *value)
  9792. {
  9793. uint32_t t;
  9794. if (value == NULL) {
  9795. /* "get", generate */
  9796. t = next_random(&random_gen);
  9797. /* set without recursion */
  9798. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9799. vrandom.flags &= ~VNOFUNC;
  9800. } else {
  9801. /* set/reset */
  9802. t = strtoul(value, NULL, 10);
  9803. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9804. }
  9805. }
  9806. #endif
  9807. #if ENABLE_ASH_GETOPTS
  9808. static int
  9809. getopts(char *optstr, char *optvar, char **optfirst)
  9810. {
  9811. char *p, *q;
  9812. char c = '?';
  9813. int done = 0;
  9814. char sbuf[2];
  9815. char **optnext;
  9816. int ind = shellparam.optind;
  9817. int off = shellparam.optoff;
  9818. sbuf[1] = '\0';
  9819. shellparam.optind = -1;
  9820. optnext = optfirst + ind - 1;
  9821. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  9822. p = NULL;
  9823. else
  9824. p = optnext[-1] + off;
  9825. if (p == NULL || *p == '\0') {
  9826. /* Current word is done, advance */
  9827. p = *optnext;
  9828. if (p == NULL || *p != '-' || *++p == '\0') {
  9829. atend:
  9830. p = NULL;
  9831. done = 1;
  9832. goto out;
  9833. }
  9834. optnext++;
  9835. if (LONE_DASH(p)) /* check for "--" */
  9836. goto atend;
  9837. }
  9838. c = *p++;
  9839. for (q = optstr; *q != c;) {
  9840. if (*q == '\0') {
  9841. if (optstr[0] == ':') {
  9842. sbuf[0] = c;
  9843. /*sbuf[1] = '\0'; - already is */
  9844. setvar0("OPTARG", sbuf);
  9845. } else {
  9846. fprintf(stderr, "Illegal option -%c\n", c);
  9847. unsetvar("OPTARG");
  9848. }
  9849. c = '?';
  9850. goto out;
  9851. }
  9852. if (*++q == ':')
  9853. q++;
  9854. }
  9855. if (*++q == ':') {
  9856. if (*p == '\0' && (p = *optnext) == NULL) {
  9857. if (optstr[0] == ':') {
  9858. sbuf[0] = c;
  9859. /*sbuf[1] = '\0'; - already is */
  9860. setvar0("OPTARG", sbuf);
  9861. c = ':';
  9862. } else {
  9863. fprintf(stderr, "No arg for -%c option\n", c);
  9864. unsetvar("OPTARG");
  9865. c = '?';
  9866. }
  9867. goto out;
  9868. }
  9869. if (p == *optnext)
  9870. optnext++;
  9871. setvar0("OPTARG", p);
  9872. p = NULL;
  9873. } else
  9874. setvar0("OPTARG", nullstr);
  9875. out:
  9876. ind = optnext - optfirst + 1;
  9877. setvar("OPTIND", itoa(ind), VNOFUNC);
  9878. sbuf[0] = c;
  9879. /*sbuf[1] = '\0'; - already is */
  9880. setvar0(optvar, sbuf);
  9881. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  9882. shellparam.optind = ind;
  9883. return done;
  9884. }
  9885. /*
  9886. * The getopts builtin. Shellparam.optnext points to the next argument
  9887. * to be processed. Shellparam.optptr points to the next character to
  9888. * be processed in the current argument. If shellparam.optnext is NULL,
  9889. * then it's the first time getopts has been called.
  9890. */
  9891. static int FAST_FUNC
  9892. getoptscmd(int argc, char **argv)
  9893. {
  9894. char **optbase;
  9895. if (argc < 3)
  9896. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9897. if (argc == 3) {
  9898. optbase = shellparam.p;
  9899. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  9900. shellparam.optind = 1;
  9901. shellparam.optoff = -1;
  9902. }
  9903. } else {
  9904. optbase = &argv[3];
  9905. if ((unsigned)shellparam.optind > argc - 2) {
  9906. shellparam.optind = 1;
  9907. shellparam.optoff = -1;
  9908. }
  9909. }
  9910. return getopts(argv[1], argv[2], optbase);
  9911. }
  9912. #endif /* ASH_GETOPTS */
  9913. /* ============ Shell parser */
  9914. struct heredoc {
  9915. struct heredoc *next; /* next here document in list */
  9916. union node *here; /* redirection node */
  9917. char *eofmark; /* string indicating end of input */
  9918. smallint striptabs; /* if set, strip leading tabs */
  9919. };
  9920. static smallint tokpushback; /* last token pushed back */
  9921. static smallint quoteflag; /* set if (part of) last token was quoted */
  9922. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9923. static struct heredoc *heredoclist; /* list of here documents to read */
  9924. static char *wordtext; /* text of last word returned by readtoken */
  9925. static struct nodelist *backquotelist;
  9926. static union node *redirnode;
  9927. static struct heredoc *heredoc;
  9928. static const char *
  9929. tokname(char *buf, int tok)
  9930. {
  9931. if (tok < TSEMI)
  9932. return tokname_array[tok];
  9933. sprintf(buf, "\"%s\"", tokname_array[tok]);
  9934. return buf;
  9935. }
  9936. /* raise_error_unexpected_syntax:
  9937. * Called when an unexpected token is read during the parse. The argument
  9938. * is the token that is expected, or -1 if more than one type of token can
  9939. * occur at this point.
  9940. */
  9941. static void raise_error_unexpected_syntax(int) NORETURN;
  9942. static void
  9943. raise_error_unexpected_syntax(int token)
  9944. {
  9945. char msg[64];
  9946. char buf[16];
  9947. int l;
  9948. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  9949. if (token >= 0)
  9950. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  9951. raise_error_syntax(msg);
  9952. /* NOTREACHED */
  9953. }
  9954. #define EOFMARKLEN 79
  9955. /* parsing is heavily cross-recursive, need these forward decls */
  9956. static union node *andor(void);
  9957. static union node *pipeline(void);
  9958. static union node *parse_command(void);
  9959. static void parseheredoc(void);
  9960. static int peektoken(void);
  9961. static int readtoken(void);
  9962. static union node *
  9963. list(int nlflag)
  9964. {
  9965. union node *n1, *n2, *n3;
  9966. int tok;
  9967. n1 = NULL;
  9968. for (;;) {
  9969. switch (peektoken()) {
  9970. case TNL:
  9971. if (!(nlflag & 1))
  9972. break;
  9973. parseheredoc();
  9974. return n1;
  9975. case TEOF:
  9976. if (!n1 && (nlflag & 1))
  9977. n1 = NODE_EOF;
  9978. parseheredoc();
  9979. return n1;
  9980. }
  9981. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9982. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  9983. return n1;
  9984. nlflag |= 2;
  9985. n2 = andor();
  9986. tok = readtoken();
  9987. if (tok == TBACKGND) {
  9988. if (n2->type == NPIPE) {
  9989. n2->npipe.pipe_backgnd = 1;
  9990. } else {
  9991. if (n2->type != NREDIR) {
  9992. n3 = stzalloc(sizeof(struct nredir));
  9993. n3->nredir.n = n2;
  9994. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9995. n2 = n3;
  9996. }
  9997. n2->type = NBACKGND;
  9998. }
  9999. }
  10000. if (n1 == NULL) {
  10001. n1 = n2;
  10002. } else {
  10003. n3 = stzalloc(sizeof(struct nbinary));
  10004. n3->type = NSEMI;
  10005. n3->nbinary.ch1 = n1;
  10006. n3->nbinary.ch2 = n2;
  10007. n1 = n3;
  10008. }
  10009. switch (tok) {
  10010. case TNL:
  10011. case TEOF:
  10012. tokpushback = 1;
  10013. /* fall through */
  10014. case TBACKGND:
  10015. case TSEMI:
  10016. break;
  10017. default:
  10018. if ((nlflag & 1))
  10019. raise_error_unexpected_syntax(-1);
  10020. tokpushback = 1;
  10021. return n1;
  10022. }
  10023. }
  10024. }
  10025. static union node *
  10026. andor(void)
  10027. {
  10028. union node *n1, *n2, *n3;
  10029. int t;
  10030. n1 = pipeline();
  10031. for (;;) {
  10032. t = readtoken();
  10033. if (t == TAND) {
  10034. t = NAND;
  10035. } else if (t == TOR) {
  10036. t = NOR;
  10037. } else {
  10038. tokpushback = 1;
  10039. return n1;
  10040. }
  10041. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10042. n2 = pipeline();
  10043. n3 = stzalloc(sizeof(struct nbinary));
  10044. n3->type = t;
  10045. n3->nbinary.ch1 = n1;
  10046. n3->nbinary.ch2 = n2;
  10047. n1 = n3;
  10048. }
  10049. }
  10050. static union node *
  10051. pipeline(void)
  10052. {
  10053. union node *n1, *n2, *pipenode;
  10054. struct nodelist *lp, *prev;
  10055. int negate;
  10056. negate = 0;
  10057. TRACE(("pipeline: entered\n"));
  10058. if (readtoken() == TNOT) {
  10059. negate = !negate;
  10060. checkkwd = CHKKWD | CHKALIAS;
  10061. } else
  10062. tokpushback = 1;
  10063. n1 = parse_command();
  10064. if (readtoken() == TPIPE) {
  10065. pipenode = stzalloc(sizeof(struct npipe));
  10066. pipenode->type = NPIPE;
  10067. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10068. lp = stzalloc(sizeof(struct nodelist));
  10069. pipenode->npipe.cmdlist = lp;
  10070. lp->n = n1;
  10071. do {
  10072. prev = lp;
  10073. lp = stzalloc(sizeof(struct nodelist));
  10074. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10075. lp->n = parse_command();
  10076. prev->next = lp;
  10077. } while (readtoken() == TPIPE);
  10078. lp->next = NULL;
  10079. n1 = pipenode;
  10080. }
  10081. tokpushback = 1;
  10082. if (negate) {
  10083. n2 = stzalloc(sizeof(struct nnot));
  10084. n2->type = NNOT;
  10085. n2->nnot.com = n1;
  10086. return n2;
  10087. }
  10088. return n1;
  10089. }
  10090. static union node *
  10091. makename(void)
  10092. {
  10093. union node *n;
  10094. n = stzalloc(sizeof(struct narg));
  10095. n->type = NARG;
  10096. /*n->narg.next = NULL; - stzalloc did it */
  10097. n->narg.text = wordtext;
  10098. n->narg.backquote = backquotelist;
  10099. return n;
  10100. }
  10101. static void
  10102. fixredir(union node *n, const char *text, int err)
  10103. {
  10104. int fd;
  10105. TRACE(("Fix redir %s %d\n", text, err));
  10106. if (!err)
  10107. n->ndup.vname = NULL;
  10108. fd = bb_strtou(text, NULL, 10);
  10109. if (!errno && fd >= 0)
  10110. n->ndup.dupfd = fd;
  10111. else if (LONE_DASH(text))
  10112. n->ndup.dupfd = -1;
  10113. else {
  10114. if (err)
  10115. raise_error_syntax("bad fd number");
  10116. n->ndup.vname = makename();
  10117. }
  10118. }
  10119. /*
  10120. * Returns true if the text contains nothing to expand (no dollar signs
  10121. * or backquotes).
  10122. */
  10123. static int
  10124. noexpand(const char *text)
  10125. {
  10126. unsigned char c;
  10127. while ((c = *text++) != '\0') {
  10128. if (c == CTLQUOTEMARK)
  10129. continue;
  10130. if (c == CTLESC)
  10131. text++;
  10132. else if (SIT(c, BASESYNTAX) == CCTL)
  10133. return 0;
  10134. }
  10135. return 1;
  10136. }
  10137. static void
  10138. parsefname(void)
  10139. {
  10140. union node *n = redirnode;
  10141. if (readtoken() != TWORD)
  10142. raise_error_unexpected_syntax(-1);
  10143. if (n->type == NHERE) {
  10144. struct heredoc *here = heredoc;
  10145. struct heredoc *p;
  10146. int i;
  10147. if (quoteflag == 0)
  10148. n->type = NXHERE;
  10149. TRACE(("Here document %d\n", n->type));
  10150. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  10151. raise_error_syntax("illegal eof marker for << redirection");
  10152. rmescapes(wordtext, 0);
  10153. here->eofmark = wordtext;
  10154. here->next = NULL;
  10155. if (heredoclist == NULL)
  10156. heredoclist = here;
  10157. else {
  10158. for (p = heredoclist; p->next; p = p->next)
  10159. continue;
  10160. p->next = here;
  10161. }
  10162. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10163. fixredir(n, wordtext, 0);
  10164. } else {
  10165. n->nfile.fname = makename();
  10166. }
  10167. }
  10168. static union node *
  10169. simplecmd(void)
  10170. {
  10171. union node *args, **app;
  10172. union node *n = NULL;
  10173. union node *vars, **vpp;
  10174. union node **rpp, *redir;
  10175. int savecheckkwd;
  10176. #if BASH_TEST2
  10177. smallint double_brackets_flag = 0;
  10178. #endif
  10179. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10180. args = NULL;
  10181. app = &args;
  10182. vars = NULL;
  10183. vpp = &vars;
  10184. redir = NULL;
  10185. rpp = &redir;
  10186. savecheckkwd = CHKALIAS;
  10187. for (;;) {
  10188. int t;
  10189. checkkwd = savecheckkwd;
  10190. t = readtoken();
  10191. switch (t) {
  10192. #if BASH_FUNCTION
  10193. case TFUNCTION:
  10194. if (peektoken() != TWORD)
  10195. raise_error_unexpected_syntax(TWORD);
  10196. function_flag = 1;
  10197. break;
  10198. #endif
  10199. #if BASH_TEST2
  10200. case TAND: /* "&&" */
  10201. case TOR: /* "||" */
  10202. if (!double_brackets_flag) {
  10203. tokpushback = 1;
  10204. goto out;
  10205. }
  10206. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10207. #endif
  10208. case TWORD:
  10209. n = stzalloc(sizeof(struct narg));
  10210. n->type = NARG;
  10211. /*n->narg.next = NULL; - stzalloc did it */
  10212. n->narg.text = wordtext;
  10213. #if BASH_TEST2
  10214. if (strcmp("[[", wordtext) == 0)
  10215. double_brackets_flag = 1;
  10216. else if (strcmp("]]", wordtext) == 0)
  10217. double_brackets_flag = 0;
  10218. #endif
  10219. n->narg.backquote = backquotelist;
  10220. if (savecheckkwd && isassignment(wordtext)) {
  10221. *vpp = n;
  10222. vpp = &n->narg.next;
  10223. } else {
  10224. *app = n;
  10225. app = &n->narg.next;
  10226. savecheckkwd = 0;
  10227. }
  10228. #if BASH_FUNCTION
  10229. if (function_flag) {
  10230. checkkwd = CHKNL | CHKKWD;
  10231. switch (peektoken()) {
  10232. case TBEGIN:
  10233. case TIF:
  10234. case TCASE:
  10235. case TUNTIL:
  10236. case TWHILE:
  10237. case TFOR:
  10238. goto do_func;
  10239. case TLP:
  10240. function_flag = 0;
  10241. break;
  10242. case TWORD:
  10243. if (strcmp("[[", wordtext) == 0)
  10244. goto do_func;
  10245. /* fall through */
  10246. default:
  10247. raise_error_unexpected_syntax(-1);
  10248. }
  10249. }
  10250. #endif
  10251. break;
  10252. case TREDIR:
  10253. *rpp = n = redirnode;
  10254. rpp = &n->nfile.next;
  10255. parsefname(); /* read name of redirection file */
  10256. break;
  10257. case TLP:
  10258. IF_BASH_FUNCTION(do_func:)
  10259. if (args && app == &args->narg.next
  10260. && !vars && !redir
  10261. ) {
  10262. struct builtincmd *bcmd;
  10263. const char *name;
  10264. /* We have a function */
  10265. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10266. raise_error_unexpected_syntax(TRP);
  10267. name = n->narg.text;
  10268. if (!goodname(name)
  10269. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10270. ) {
  10271. raise_error_syntax("bad function name");
  10272. }
  10273. n->type = NDEFUN;
  10274. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10275. n->narg.next = parse_command();
  10276. return n;
  10277. }
  10278. IF_BASH_FUNCTION(function_flag = 0;)
  10279. /* fall through */
  10280. default:
  10281. tokpushback = 1;
  10282. goto out;
  10283. }
  10284. }
  10285. out:
  10286. *app = NULL;
  10287. *vpp = NULL;
  10288. *rpp = NULL;
  10289. n = stzalloc(sizeof(struct ncmd));
  10290. n->type = NCMD;
  10291. n->ncmd.args = args;
  10292. n->ncmd.assign = vars;
  10293. n->ncmd.redirect = redir;
  10294. return n;
  10295. }
  10296. static union node *
  10297. parse_command(void)
  10298. {
  10299. union node *n1, *n2;
  10300. union node *ap, **app;
  10301. union node *cp, **cpp;
  10302. union node *redir, **rpp;
  10303. union node **rpp2;
  10304. int t;
  10305. redir = NULL;
  10306. rpp2 = &redir;
  10307. switch (readtoken()) {
  10308. default:
  10309. raise_error_unexpected_syntax(-1);
  10310. /* NOTREACHED */
  10311. case TIF:
  10312. n1 = stzalloc(sizeof(struct nif));
  10313. n1->type = NIF;
  10314. n1->nif.test = list(0);
  10315. if (readtoken() != TTHEN)
  10316. raise_error_unexpected_syntax(TTHEN);
  10317. n1->nif.ifpart = list(0);
  10318. n2 = n1;
  10319. while (readtoken() == TELIF) {
  10320. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10321. n2 = n2->nif.elsepart;
  10322. n2->type = NIF;
  10323. n2->nif.test = list(0);
  10324. if (readtoken() != TTHEN)
  10325. raise_error_unexpected_syntax(TTHEN);
  10326. n2->nif.ifpart = list(0);
  10327. }
  10328. if (lasttoken == TELSE)
  10329. n2->nif.elsepart = list(0);
  10330. else {
  10331. n2->nif.elsepart = NULL;
  10332. tokpushback = 1;
  10333. }
  10334. t = TFI;
  10335. break;
  10336. case TWHILE:
  10337. case TUNTIL: {
  10338. int got;
  10339. n1 = stzalloc(sizeof(struct nbinary));
  10340. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10341. n1->nbinary.ch1 = list(0);
  10342. got = readtoken();
  10343. if (got != TDO) {
  10344. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10345. got == TWORD ? wordtext : ""));
  10346. raise_error_unexpected_syntax(TDO);
  10347. }
  10348. n1->nbinary.ch2 = list(0);
  10349. t = TDONE;
  10350. break;
  10351. }
  10352. case TFOR:
  10353. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10354. raise_error_syntax("bad for loop variable");
  10355. n1 = stzalloc(sizeof(struct nfor));
  10356. n1->type = NFOR;
  10357. n1->nfor.var = wordtext;
  10358. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10359. if (readtoken() == TIN) {
  10360. app = &ap;
  10361. while (readtoken() == TWORD) {
  10362. n2 = stzalloc(sizeof(struct narg));
  10363. n2->type = NARG;
  10364. /*n2->narg.next = NULL; - stzalloc did it */
  10365. n2->narg.text = wordtext;
  10366. n2->narg.backquote = backquotelist;
  10367. *app = n2;
  10368. app = &n2->narg.next;
  10369. }
  10370. *app = NULL;
  10371. n1->nfor.args = ap;
  10372. if (lasttoken != TNL && lasttoken != TSEMI)
  10373. raise_error_unexpected_syntax(-1);
  10374. } else {
  10375. n2 = stzalloc(sizeof(struct narg));
  10376. n2->type = NARG;
  10377. /*n2->narg.next = NULL; - stzalloc did it */
  10378. n2->narg.text = (char *)dolatstr;
  10379. /*n2->narg.backquote = NULL;*/
  10380. n1->nfor.args = n2;
  10381. /*
  10382. * Newline or semicolon here is optional (but note
  10383. * that the original Bourne shell only allowed NL).
  10384. */
  10385. if (lasttoken != TSEMI)
  10386. tokpushback = 1;
  10387. }
  10388. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10389. if (readtoken() != TDO)
  10390. raise_error_unexpected_syntax(TDO);
  10391. n1->nfor.body = list(0);
  10392. t = TDONE;
  10393. break;
  10394. case TCASE:
  10395. n1 = stzalloc(sizeof(struct ncase));
  10396. n1->type = NCASE;
  10397. if (readtoken() != TWORD)
  10398. raise_error_unexpected_syntax(TWORD);
  10399. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10400. n2->type = NARG;
  10401. /*n2->narg.next = NULL; - stzalloc did it */
  10402. n2->narg.text = wordtext;
  10403. n2->narg.backquote = backquotelist;
  10404. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10405. if (readtoken() != TIN)
  10406. raise_error_unexpected_syntax(TIN);
  10407. cpp = &n1->ncase.cases;
  10408. next_case:
  10409. checkkwd = CHKNL | CHKKWD;
  10410. t = readtoken();
  10411. while (t != TESAC) {
  10412. if (lasttoken == TLP)
  10413. readtoken();
  10414. *cpp = cp = stzalloc(sizeof(struct nclist));
  10415. cp->type = NCLIST;
  10416. app = &cp->nclist.pattern;
  10417. for (;;) {
  10418. *app = ap = stzalloc(sizeof(struct narg));
  10419. ap->type = NARG;
  10420. /*ap->narg.next = NULL; - stzalloc did it */
  10421. ap->narg.text = wordtext;
  10422. ap->narg.backquote = backquotelist;
  10423. if (readtoken() != TPIPE)
  10424. break;
  10425. app = &ap->narg.next;
  10426. readtoken();
  10427. }
  10428. //ap->narg.next = NULL;
  10429. if (lasttoken != TRP)
  10430. raise_error_unexpected_syntax(TRP);
  10431. cp->nclist.body = list(2);
  10432. cpp = &cp->nclist.next;
  10433. checkkwd = CHKNL | CHKKWD;
  10434. t = readtoken();
  10435. if (t != TESAC) {
  10436. if (t != TENDCASE)
  10437. raise_error_unexpected_syntax(TENDCASE);
  10438. goto next_case;
  10439. }
  10440. }
  10441. *cpp = NULL;
  10442. goto redir;
  10443. case TLP:
  10444. n1 = stzalloc(sizeof(struct nredir));
  10445. n1->type = NSUBSHELL;
  10446. n1->nredir.n = list(0);
  10447. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10448. t = TRP;
  10449. break;
  10450. case TBEGIN:
  10451. n1 = list(0);
  10452. t = TEND;
  10453. break;
  10454. IF_BASH_FUNCTION(case TFUNCTION:)
  10455. case TWORD:
  10456. case TREDIR:
  10457. tokpushback = 1;
  10458. return simplecmd();
  10459. }
  10460. if (readtoken() != t)
  10461. raise_error_unexpected_syntax(t);
  10462. redir:
  10463. /* Now check for redirection which may follow command */
  10464. checkkwd = CHKKWD | CHKALIAS;
  10465. rpp = rpp2;
  10466. while (readtoken() == TREDIR) {
  10467. *rpp = n2 = redirnode;
  10468. rpp = &n2->nfile.next;
  10469. parsefname();
  10470. }
  10471. tokpushback = 1;
  10472. *rpp = NULL;
  10473. if (redir) {
  10474. if (n1->type != NSUBSHELL) {
  10475. n2 = stzalloc(sizeof(struct nredir));
  10476. n2->type = NREDIR;
  10477. n2->nredir.n = n1;
  10478. n1 = n2;
  10479. }
  10480. n1->nredir.redirect = redir;
  10481. }
  10482. return n1;
  10483. }
  10484. #if BASH_DOLLAR_SQUOTE
  10485. static int
  10486. decode_dollar_squote(void)
  10487. {
  10488. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10489. int c, cnt;
  10490. char *p;
  10491. char buf[4];
  10492. c = pgetc();
  10493. p = strchr(C_escapes, c);
  10494. if (p) {
  10495. buf[0] = c;
  10496. p = buf;
  10497. cnt = 3;
  10498. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10499. do {
  10500. c = pgetc();
  10501. *++p = c;
  10502. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10503. pungetc();
  10504. } else if (c == 'x') { /* \xHH */
  10505. do {
  10506. c = pgetc();
  10507. *++p = c;
  10508. } while (isxdigit(c) && --cnt);
  10509. pungetc();
  10510. if (cnt == 3) { /* \x but next char is "bad" */
  10511. c = 'x';
  10512. goto unrecognized;
  10513. }
  10514. } else { /* simple seq like \\ or \t */
  10515. p++;
  10516. }
  10517. *p = '\0';
  10518. p = buf;
  10519. c = bb_process_escape_sequence((void*)&p);
  10520. } else { /* unrecognized "\z": print both chars unless ' or " */
  10521. if (c != '\'' && c != '"') {
  10522. unrecognized:
  10523. c |= 0x100; /* "please encode \, then me" */
  10524. }
  10525. }
  10526. return c;
  10527. }
  10528. #endif
  10529. /*
  10530. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10531. * is not NULL, read a here document. In the latter case, eofmark is the
  10532. * word which marks the end of the document and striptabs is true if
  10533. * leading tabs should be stripped from the document. The argument c
  10534. * is the first character of the input token or document.
  10535. *
  10536. * Because C does not have internal subroutines, I have simulated them
  10537. * using goto's to implement the subroutine linkage. The following macros
  10538. * will run code that appears at the end of readtoken1.
  10539. */
  10540. #define CHECKEND() {goto checkend; checkend_return:;}
  10541. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10542. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10543. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10544. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10545. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10546. static int
  10547. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10548. {
  10549. /* NB: syntax parameter fits into smallint */
  10550. /* c parameter is an unsigned char or PEOF or PEOA */
  10551. char *out;
  10552. size_t len;
  10553. char line[EOFMARKLEN + 1];
  10554. struct nodelist *bqlist;
  10555. smallint quotef;
  10556. smallint dblquote;
  10557. smallint oldstyle;
  10558. IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
  10559. smallint pssyntax; /* we are expanding a prompt string */
  10560. int varnest; /* levels of variables expansion */
  10561. IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
  10562. IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
  10563. int dqvarnest; /* levels of variables expansion within double quotes */
  10564. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10565. startlinno = g_parsefile->linno;
  10566. bqlist = NULL;
  10567. quotef = 0;
  10568. IF_FEATURE_SH_MATH(prevsyntax = 0;)
  10569. pssyntax = (syntax == PSSYNTAX);
  10570. if (pssyntax)
  10571. syntax = DQSYNTAX;
  10572. dblquote = (syntax == DQSYNTAX);
  10573. varnest = 0;
  10574. IF_FEATURE_SH_MATH(arinest = 0;)
  10575. IF_FEATURE_SH_MATH(parenlevel = 0;)
  10576. dqvarnest = 0;
  10577. STARTSTACKSTR(out);
  10578. loop:
  10579. /* For each line, until end of word */
  10580. CHECKEND(); /* set c to PEOF if at end of here document */
  10581. for (;;) { /* until end of line or end of word */
  10582. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10583. switch (SIT(c, syntax)) {
  10584. case CNL: /* '\n' */
  10585. if (syntax == BASESYNTAX)
  10586. goto endword; /* exit outer loop */
  10587. USTPUTC(c, out);
  10588. nlprompt();
  10589. c = pgetc();
  10590. goto loop; /* continue outer loop */
  10591. case CWORD:
  10592. USTPUTC(c, out);
  10593. break;
  10594. case CCTL:
  10595. #if BASH_DOLLAR_SQUOTE
  10596. if (c == '\\' && bash_dollar_squote) {
  10597. c = decode_dollar_squote();
  10598. if (c == '\0') {
  10599. /* skip $'\000', $'\x00' (like bash) */
  10600. break;
  10601. }
  10602. if (c & 0x100) {
  10603. /* Unknown escape. Encode as '\z' */
  10604. c = (unsigned char)c;
  10605. if (eofmark == NULL || dblquote)
  10606. USTPUTC(CTLESC, out);
  10607. USTPUTC('\\', out);
  10608. }
  10609. }
  10610. #endif
  10611. if (eofmark == NULL || dblquote)
  10612. USTPUTC(CTLESC, out);
  10613. USTPUTC(c, out);
  10614. break;
  10615. case CBACK: /* backslash */
  10616. c = pgetc_without_PEOA();
  10617. if (c == PEOF) {
  10618. USTPUTC(CTLESC, out);
  10619. USTPUTC('\\', out);
  10620. pungetc();
  10621. } else if (c == '\n') {
  10622. nlprompt();
  10623. } else {
  10624. if (c == '$' && pssyntax) {
  10625. USTPUTC(CTLESC, out);
  10626. USTPUTC('\\', out);
  10627. }
  10628. /* Backslash is retained if we are in "str" and next char isn't special */
  10629. if (dblquote
  10630. && c != '\\'
  10631. && c != '`'
  10632. && c != '$'
  10633. && (c != '"' || eofmark != NULL)
  10634. ) {
  10635. USTPUTC('\\', out);
  10636. }
  10637. USTPUTC(CTLESC, out);
  10638. USTPUTC(c, out);
  10639. quotef = 1;
  10640. }
  10641. break;
  10642. case CSQUOTE:
  10643. syntax = SQSYNTAX;
  10644. quotemark:
  10645. if (eofmark == NULL) {
  10646. USTPUTC(CTLQUOTEMARK, out);
  10647. }
  10648. break;
  10649. case CDQUOTE:
  10650. syntax = DQSYNTAX;
  10651. dblquote = 1;
  10652. goto quotemark;
  10653. case CENDQUOTE:
  10654. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  10655. if (eofmark != NULL && varnest == 0) {
  10656. USTPUTC(c, out);
  10657. } else {
  10658. if (dqvarnest == 0) {
  10659. syntax = BASESYNTAX;
  10660. dblquote = 0;
  10661. }
  10662. quotef = 1;
  10663. goto quotemark;
  10664. }
  10665. break;
  10666. case CVAR: /* '$' */
  10667. PARSESUB(); /* parse substitution */
  10668. break;
  10669. case CENDVAR: /* '}' */
  10670. if (varnest > 0) {
  10671. varnest--;
  10672. if (dqvarnest > 0) {
  10673. dqvarnest--;
  10674. }
  10675. c = CTLENDVAR;
  10676. }
  10677. USTPUTC(c, out);
  10678. break;
  10679. #if ENABLE_FEATURE_SH_MATH
  10680. case CLP: /* '(' in arithmetic */
  10681. parenlevel++;
  10682. USTPUTC(c, out);
  10683. break;
  10684. case CRP: /* ')' in arithmetic */
  10685. if (parenlevel > 0) {
  10686. parenlevel--;
  10687. } else {
  10688. if (pgetc_eatbnl() == ')') {
  10689. c = CTLENDARI;
  10690. if (--arinest == 0) {
  10691. syntax = prevsyntax;
  10692. }
  10693. } else {
  10694. /*
  10695. * unbalanced parens
  10696. * (don't 2nd guess - no error)
  10697. */
  10698. pungetc();
  10699. }
  10700. }
  10701. USTPUTC(c, out);
  10702. break;
  10703. #endif
  10704. case CBQUOTE: /* '`' */
  10705. PARSEBACKQOLD();
  10706. break;
  10707. case CENDFILE:
  10708. goto endword; /* exit outer loop */
  10709. case CIGN:
  10710. break;
  10711. default:
  10712. if (varnest == 0) {
  10713. #if BASH_REDIR_OUTPUT
  10714. if (c == '&') {
  10715. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  10716. if (pgetc() == '>')
  10717. c = 0x100 + '>'; /* flag &> */
  10718. pungetc();
  10719. }
  10720. #endif
  10721. goto endword; /* exit outer loop */
  10722. }
  10723. IF_ASH_ALIAS(if (c != PEOA))
  10724. USTPUTC(c, out);
  10725. }
  10726. c = pgetc();
  10727. } /* for (;;) */
  10728. endword:
  10729. #if ENABLE_FEATURE_SH_MATH
  10730. if (syntax == ARISYNTAX)
  10731. raise_error_syntax("missing '))'");
  10732. #endif
  10733. if (syntax != BASESYNTAX && eofmark == NULL)
  10734. raise_error_syntax("unterminated quoted string");
  10735. if (varnest != 0) {
  10736. startlinno = g_parsefile->linno;
  10737. /* { */
  10738. raise_error_syntax("missing '}'");
  10739. }
  10740. USTPUTC('\0', out);
  10741. len = out - (char *)stackblock();
  10742. out = stackblock();
  10743. if (eofmark == NULL) {
  10744. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  10745. && quotef == 0
  10746. ) {
  10747. if (isdigit_str9(out)) {
  10748. PARSEREDIR(); /* passed as params: out, c */
  10749. lasttoken = TREDIR;
  10750. return lasttoken;
  10751. }
  10752. /* else: non-number X seen, interpret it
  10753. * as "NNNX>file" = "NNNX >file" */
  10754. }
  10755. pungetc();
  10756. }
  10757. quoteflag = quotef;
  10758. backquotelist = bqlist;
  10759. grabstackblock(len);
  10760. wordtext = out;
  10761. lasttoken = TWORD;
  10762. return lasttoken;
  10763. /* end of readtoken routine */
  10764. /*
  10765. * Check to see whether we are at the end of the here document. When this
  10766. * is called, c is set to the first character of the next input line. If
  10767. * we are at the end of the here document, this routine sets the c to PEOF.
  10768. */
  10769. checkend: {
  10770. if (eofmark) {
  10771. #if ENABLE_ASH_ALIAS
  10772. if (c == PEOA)
  10773. c = pgetc_without_PEOA();
  10774. #endif
  10775. if (striptabs) {
  10776. while (c == '\t') {
  10777. c = pgetc_without_PEOA();
  10778. }
  10779. }
  10780. if (c == *eofmark) {
  10781. if (pfgets(line, sizeof(line)) != NULL) {
  10782. char *p, *q;
  10783. int cc;
  10784. p = line;
  10785. for (q = eofmark + 1;; p++, q++) {
  10786. cc = *p;
  10787. if (cc == '\n')
  10788. cc = 0;
  10789. if (!*q || cc != *q)
  10790. break;
  10791. }
  10792. if (cc == *q) {
  10793. c = PEOF;
  10794. nlnoprompt();
  10795. } else {
  10796. pushstring(line, NULL);
  10797. }
  10798. }
  10799. }
  10800. }
  10801. goto checkend_return;
  10802. }
  10803. /*
  10804. * Parse a redirection operator. The variable "out" points to a string
  10805. * specifying the fd to be redirected. The variable "c" contains the
  10806. * first character of the redirection operator.
  10807. */
  10808. parseredir: {
  10809. /* out is already checked to be a valid number or "" */
  10810. int fd = (*out == '\0' ? -1 : atoi(out));
  10811. union node *np;
  10812. np = stzalloc(sizeof(struct nfile));
  10813. if (c == '>') {
  10814. np->nfile.fd = 1;
  10815. c = pgetc();
  10816. if (c == '>')
  10817. np->type = NAPPEND;
  10818. else if (c == '|')
  10819. np->type = NCLOBBER;
  10820. else if (c == '&')
  10821. np->type = NTOFD;
  10822. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10823. else {
  10824. np->type = NTO;
  10825. pungetc();
  10826. }
  10827. }
  10828. #if BASH_REDIR_OUTPUT
  10829. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10830. np->nfile.fd = 1;
  10831. pgetc(); /* this is '>', no need to check */
  10832. np->type = NTO2;
  10833. }
  10834. #endif
  10835. else { /* c == '<' */
  10836. /*np->nfile.fd = 0; - stzalloc did it */
  10837. c = pgetc();
  10838. switch (c) {
  10839. case '<':
  10840. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10841. np = stzalloc(sizeof(struct nhere));
  10842. /*np->nfile.fd = 0; - stzalloc did it */
  10843. }
  10844. np->type = NHERE;
  10845. heredoc = stzalloc(sizeof(struct heredoc));
  10846. heredoc->here = np;
  10847. c = pgetc();
  10848. if (c == '-') {
  10849. heredoc->striptabs = 1;
  10850. } else {
  10851. /*heredoc->striptabs = 0; - stzalloc did it */
  10852. pungetc();
  10853. }
  10854. break;
  10855. case '&':
  10856. np->type = NFROMFD;
  10857. break;
  10858. case '>':
  10859. np->type = NFROMTO;
  10860. break;
  10861. default:
  10862. np->type = NFROM;
  10863. pungetc();
  10864. break;
  10865. }
  10866. }
  10867. if (fd >= 0)
  10868. np->nfile.fd = fd;
  10869. redirnode = np;
  10870. goto parseredir_return;
  10871. }
  10872. /*
  10873. * Parse a substitution. At this point, we have read the dollar sign
  10874. * and nothing else.
  10875. */
  10876. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10877. * (assuming ascii char codes, as the original implementation did) */
  10878. #define is_special(c) \
  10879. (((unsigned)(c) - 33 < 32) \
  10880. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10881. parsesub: {
  10882. unsigned char subtype;
  10883. int typeloc;
  10884. c = pgetc_eatbnl();
  10885. if (c > 255 /* PEOA or PEOF */
  10886. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10887. ) {
  10888. #if BASH_DOLLAR_SQUOTE
  10889. if (syntax != DQSYNTAX && c == '\'')
  10890. bash_dollar_squote = 1;
  10891. else
  10892. #endif
  10893. USTPUTC('$', out);
  10894. pungetc();
  10895. } else if (c == '(') {
  10896. /* $(command) or $((arith)) */
  10897. if (pgetc_eatbnl() == '(') {
  10898. #if ENABLE_FEATURE_SH_MATH
  10899. PARSEARITH();
  10900. #else
  10901. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10902. #endif
  10903. } else {
  10904. pungetc();
  10905. PARSEBACKQNEW();
  10906. }
  10907. } else {
  10908. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  10909. USTPUTC(CTLVAR, out);
  10910. typeloc = out - (char *)stackblock();
  10911. STADJUST(1, out);
  10912. subtype = VSNORMAL;
  10913. if (c == '{') {
  10914. c = pgetc_eatbnl();
  10915. subtype = 0;
  10916. }
  10917. varname:
  10918. if (is_name(c)) {
  10919. /* $[{[#]]NAME[}] */
  10920. do {
  10921. STPUTC(c, out);
  10922. c = pgetc_eatbnl();
  10923. } while (is_in_name(c));
  10924. } else if (isdigit(c)) {
  10925. /* $[{[#]]NUM[}] */
  10926. do {
  10927. STPUTC(c, out);
  10928. c = pgetc_eatbnl();
  10929. } while (isdigit(c));
  10930. } else if (is_special(c)) {
  10931. /* $[{[#]]<specialchar>[}] */
  10932. int cc = c;
  10933. c = pgetc_eatbnl();
  10934. if (!subtype && cc == '#') {
  10935. subtype = VSLENGTH;
  10936. if (c == '_' || isalnum(c))
  10937. goto varname;
  10938. cc = c;
  10939. c = pgetc_eatbnl();
  10940. if (cc == '}' || c != '}') {
  10941. pungetc();
  10942. subtype = 0;
  10943. c = cc;
  10944. cc = '#';
  10945. }
  10946. }
  10947. USTPUTC(cc, out);
  10948. } else {
  10949. goto badsub;
  10950. }
  10951. if (c != '}' && subtype == VSLENGTH) {
  10952. /* ${#VAR didn't end with } */
  10953. goto badsub;
  10954. }
  10955. if (subtype == 0) {
  10956. static const char types[] ALIGN1 = "}-+?=";
  10957. /* ${VAR...} but not $VAR or ${#VAR} */
  10958. /* c == first char after VAR */
  10959. switch (c) {
  10960. case ':':
  10961. c = pgetc_eatbnl();
  10962. #if BASH_SUBSTR
  10963. /* This check is only needed to not misinterpret
  10964. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  10965. * constructs.
  10966. */
  10967. if (!strchr(types, c)) {
  10968. subtype = VSSUBSTR;
  10969. pungetc();
  10970. break; /* "goto badsub" is bigger (!) */
  10971. }
  10972. #endif
  10973. subtype = VSNUL;
  10974. /*FALLTHROUGH*/
  10975. default: {
  10976. const char *p = strchr(types, c);
  10977. if (p == NULL)
  10978. break;
  10979. subtype |= p - types + VSNORMAL;
  10980. break;
  10981. }
  10982. case '%':
  10983. case '#': {
  10984. int cc = c;
  10985. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  10986. c = pgetc_eatbnl();
  10987. if (c != cc)
  10988. goto badsub;
  10989. subtype++;
  10990. break;
  10991. }
  10992. #if BASH_PATTERN_SUBST
  10993. case '/':
  10994. /* ${v/[/]pattern/repl} */
  10995. //TODO: encode pattern and repl separately.
  10996. // Currently ${v/$var_with_slash/repl} is horribly broken
  10997. subtype = VSREPLACE;
  10998. c = pgetc_eatbnl();
  10999. if (c != '/')
  11000. goto badsub;
  11001. subtype++; /* VSREPLACEALL */
  11002. break;
  11003. #endif
  11004. }
  11005. } else {
  11006. badsub:
  11007. pungetc();
  11008. }
  11009. ((unsigned char *)stackblock())[typeloc] = subtype;
  11010. if (subtype != VSNORMAL) {
  11011. varnest++;
  11012. if (dblquote)
  11013. dqvarnest++;
  11014. }
  11015. STPUTC('=', out);
  11016. }
  11017. goto parsesub_return;
  11018. }
  11019. /*
  11020. * Called to parse command substitutions. Newstyle is set if the command
  11021. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11022. * list of commands (passed by reference), and savelen is the number of
  11023. * characters on the top of the stack which must be preserved.
  11024. */
  11025. parsebackq: {
  11026. struct nodelist **nlpp;
  11027. union node *n;
  11028. char *str;
  11029. size_t savelen;
  11030. smallint saveprompt = 0;
  11031. str = NULL;
  11032. savelen = out - (char *)stackblock();
  11033. if (savelen > 0) {
  11034. /*
  11035. * FIXME: this can allocate very large block on stack and SEGV.
  11036. * Example:
  11037. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11038. * allocates 100kb for every command subst. With about
  11039. * a hundred command substitutions stack overflows.
  11040. * With larger prepended string, SEGV happens sooner.
  11041. */
  11042. str = alloca(savelen);
  11043. memcpy(str, stackblock(), savelen);
  11044. }
  11045. if (oldstyle) {
  11046. /* We must read until the closing backquote, giving special
  11047. * treatment to some slashes, and then push the string and
  11048. * reread it as input, interpreting it normally.
  11049. */
  11050. char *pout;
  11051. size_t psavelen;
  11052. char *pstr;
  11053. STARTSTACKSTR(pout);
  11054. for (;;) {
  11055. int pc;
  11056. setprompt_if(needprompt, 2);
  11057. pc = pgetc();
  11058. switch (pc) {
  11059. case '`':
  11060. goto done;
  11061. case '\\':
  11062. pc = pgetc();
  11063. if (pc == '\n') {
  11064. nlprompt();
  11065. /*
  11066. * If eating a newline, avoid putting
  11067. * the newline into the new character
  11068. * stream (via the STPUTC after the
  11069. * switch).
  11070. */
  11071. continue;
  11072. }
  11073. if (pc != '\\' && pc != '`' && pc != '$'
  11074. && (!dblquote || pc != '"')
  11075. ) {
  11076. STPUTC('\\', pout);
  11077. }
  11078. if (pc <= 255 /* not PEOA or PEOF */) {
  11079. break;
  11080. }
  11081. /* fall through */
  11082. case PEOF:
  11083. IF_ASH_ALIAS(case PEOA:)
  11084. startlinno = g_parsefile->linno;
  11085. raise_error_syntax("EOF in backquote substitution");
  11086. case '\n':
  11087. nlnoprompt();
  11088. break;
  11089. default:
  11090. break;
  11091. }
  11092. STPUTC(pc, pout);
  11093. }
  11094. done:
  11095. STPUTC('\0', pout);
  11096. psavelen = pout - (char *)stackblock();
  11097. if (psavelen > 0) {
  11098. pstr = grabstackstr(pout);
  11099. setinputstring(pstr);
  11100. }
  11101. }
  11102. nlpp = &bqlist;
  11103. while (*nlpp)
  11104. nlpp = &(*nlpp)->next;
  11105. *nlpp = stzalloc(sizeof(**nlpp));
  11106. /* (*nlpp)->next = NULL; - stzalloc did it */
  11107. if (oldstyle) {
  11108. saveprompt = doprompt;
  11109. doprompt = 0;
  11110. }
  11111. n = list(2);
  11112. if (oldstyle)
  11113. doprompt = saveprompt;
  11114. else if (readtoken() != TRP)
  11115. raise_error_unexpected_syntax(TRP);
  11116. (*nlpp)->n = n;
  11117. if (oldstyle) {
  11118. /*
  11119. * Start reading from old file again, ignoring any pushed back
  11120. * tokens left from the backquote parsing
  11121. */
  11122. popfile();
  11123. tokpushback = 0;
  11124. }
  11125. while (stackblocksize() <= savelen)
  11126. growstackblock();
  11127. STARTSTACKSTR(out);
  11128. if (str) {
  11129. memcpy(out, str, savelen);
  11130. STADJUST(savelen, out);
  11131. }
  11132. USTPUTC(CTLBACKQ, out);
  11133. if (oldstyle)
  11134. goto parsebackq_oldreturn;
  11135. goto parsebackq_newreturn;
  11136. }
  11137. #if ENABLE_FEATURE_SH_MATH
  11138. /*
  11139. * Parse an arithmetic expansion (indicate start of one and set state)
  11140. */
  11141. parsearith: {
  11142. if (++arinest == 1) {
  11143. prevsyntax = syntax;
  11144. syntax = ARISYNTAX;
  11145. }
  11146. USTPUTC(CTLARI, out);
  11147. goto parsearith_return;
  11148. }
  11149. #endif
  11150. } /* end of readtoken */
  11151. /*
  11152. * Read the next input token.
  11153. * If the token is a word, we set backquotelist to the list of cmds in
  11154. * backquotes. We set quoteflag to true if any part of the word was
  11155. * quoted.
  11156. * If the token is TREDIR, then we set redirnode to a structure containing
  11157. * the redirection.
  11158. * In all cases, the variable startlinno is set to the number of the line
  11159. * on which the token starts.
  11160. *
  11161. * [Change comment: here documents and internal procedures]
  11162. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11163. * word parsing code into a separate routine. In this case, readtoken
  11164. * doesn't need to have any internal procedures, but parseword does.
  11165. * We could also make parseoperator in essence the main routine, and
  11166. * have parseword (readtoken1?) handle both words and redirection.]
  11167. */
  11168. #define NEW_xxreadtoken
  11169. #ifdef NEW_xxreadtoken
  11170. /* singles must be first! */
  11171. static const char xxreadtoken_chars[7] ALIGN1 = {
  11172. '\n', '(', ')', /* singles */
  11173. '&', '|', ';', /* doubles */
  11174. 0
  11175. };
  11176. #define xxreadtoken_singles 3
  11177. #define xxreadtoken_doubles 3
  11178. static const char xxreadtoken_tokens[] ALIGN1 = {
  11179. TNL, TLP, TRP, /* only single occurrence allowed */
  11180. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11181. TEOF, /* corresponds to trailing nul */
  11182. TAND, TOR, TENDCASE /* if double occurrence */
  11183. };
  11184. static int
  11185. xxreadtoken(void)
  11186. {
  11187. int c;
  11188. if (tokpushback) {
  11189. tokpushback = 0;
  11190. return lasttoken;
  11191. }
  11192. setprompt_if(needprompt, 2);
  11193. startlinno = g_parsefile->linno;
  11194. for (;;) { /* until token or start of word found */
  11195. c = pgetc();
  11196. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11197. continue;
  11198. if (c == '#') {
  11199. while ((c = pgetc()) != '\n' && c != PEOF)
  11200. continue;
  11201. pungetc();
  11202. } else if (c == '\\') {
  11203. if (pgetc() != '\n') {
  11204. pungetc();
  11205. break; /* return readtoken1(...) */
  11206. }
  11207. nlprompt();
  11208. } else {
  11209. const char *p;
  11210. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11211. if (c != PEOF) {
  11212. if (c == '\n') {
  11213. nlnoprompt();
  11214. }
  11215. p = strchr(xxreadtoken_chars, c);
  11216. if (p == NULL)
  11217. break; /* return readtoken1(...) */
  11218. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11219. int cc = pgetc();
  11220. if (cc == c) { /* double occurrence? */
  11221. p += xxreadtoken_doubles + 1;
  11222. } else {
  11223. pungetc();
  11224. #if BASH_REDIR_OUTPUT
  11225. if (c == '&' && cc == '>') /* &> */
  11226. break; /* return readtoken1(...) */
  11227. #endif
  11228. }
  11229. }
  11230. }
  11231. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11232. return lasttoken;
  11233. }
  11234. } /* for (;;) */
  11235. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11236. }
  11237. #else /* old xxreadtoken */
  11238. #define RETURN(token) return lasttoken = token
  11239. static int
  11240. xxreadtoken(void)
  11241. {
  11242. int c;
  11243. if (tokpushback) {
  11244. tokpushback = 0;
  11245. return lasttoken;
  11246. }
  11247. setprompt_if(needprompt, 2);
  11248. startlinno = g_parsefile->linno;
  11249. for (;;) { /* until token or start of word found */
  11250. c = pgetc();
  11251. switch (c) {
  11252. case ' ': case '\t':
  11253. IF_ASH_ALIAS(case PEOA:)
  11254. continue;
  11255. case '#':
  11256. while ((c = pgetc()) != '\n' && c != PEOF)
  11257. continue;
  11258. pungetc();
  11259. continue;
  11260. case '\\':
  11261. if (pgetc() == '\n') {
  11262. nlprompt();
  11263. continue;
  11264. }
  11265. pungetc();
  11266. goto breakloop;
  11267. case '\n':
  11268. nlnoprompt();
  11269. RETURN(TNL);
  11270. case PEOF:
  11271. RETURN(TEOF);
  11272. case '&':
  11273. if (pgetc() == '&')
  11274. RETURN(TAND);
  11275. pungetc();
  11276. RETURN(TBACKGND);
  11277. case '|':
  11278. if (pgetc() == '|')
  11279. RETURN(TOR);
  11280. pungetc();
  11281. RETURN(TPIPE);
  11282. case ';':
  11283. if (pgetc() == ';')
  11284. RETURN(TENDCASE);
  11285. pungetc();
  11286. RETURN(TSEMI);
  11287. case '(':
  11288. RETURN(TLP);
  11289. case ')':
  11290. RETURN(TRP);
  11291. default:
  11292. goto breakloop;
  11293. }
  11294. }
  11295. breakloop:
  11296. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11297. #undef RETURN
  11298. }
  11299. #endif /* old xxreadtoken */
  11300. static int
  11301. readtoken(void)
  11302. {
  11303. int t;
  11304. int kwd = checkkwd;
  11305. #if DEBUG
  11306. smallint alreadyseen = tokpushback;
  11307. #endif
  11308. #if ENABLE_ASH_ALIAS
  11309. top:
  11310. #endif
  11311. t = xxreadtoken();
  11312. /*
  11313. * eat newlines
  11314. */
  11315. if (kwd & CHKNL) {
  11316. while (t == TNL) {
  11317. parseheredoc();
  11318. t = xxreadtoken();
  11319. }
  11320. }
  11321. if (t != TWORD || quoteflag) {
  11322. goto out;
  11323. }
  11324. /*
  11325. * check for keywords
  11326. */
  11327. if (kwd & CHKKWD) {
  11328. const char *const *pp;
  11329. pp = findkwd(wordtext);
  11330. if (pp) {
  11331. lasttoken = t = pp - tokname_array;
  11332. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11333. goto out;
  11334. }
  11335. }
  11336. if (checkkwd & CHKALIAS) {
  11337. #if ENABLE_ASH_ALIAS
  11338. struct alias *ap;
  11339. ap = lookupalias(wordtext, 1);
  11340. if (ap != NULL) {
  11341. if (*ap->val) {
  11342. pushstring(ap->val, ap);
  11343. }
  11344. goto top;
  11345. }
  11346. #endif
  11347. }
  11348. out:
  11349. checkkwd = 0;
  11350. #if DEBUG
  11351. if (!alreadyseen)
  11352. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11353. else
  11354. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11355. #endif
  11356. return t;
  11357. }
  11358. static int
  11359. peektoken(void)
  11360. {
  11361. int t;
  11362. t = readtoken();
  11363. tokpushback = 1;
  11364. return t;
  11365. }
  11366. /*
  11367. * Read and parse a command. Returns NODE_EOF on end of file.
  11368. * (NULL is a valid parse tree indicating a blank line.)
  11369. */
  11370. static union node *
  11371. parsecmd(int interact)
  11372. {
  11373. tokpushback = 0;
  11374. checkkwd = 0;
  11375. heredoclist = 0;
  11376. doprompt = interact;
  11377. setprompt_if(doprompt, doprompt);
  11378. needprompt = 0;
  11379. return list(1);
  11380. }
  11381. /*
  11382. * Input any here documents.
  11383. */
  11384. static void
  11385. parseheredoc(void)
  11386. {
  11387. struct heredoc *here;
  11388. union node *n;
  11389. here = heredoclist;
  11390. heredoclist = NULL;
  11391. while (here) {
  11392. setprompt_if(needprompt, 2);
  11393. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11394. here->eofmark, here->striptabs);
  11395. n = stzalloc(sizeof(struct narg));
  11396. n->narg.type = NARG;
  11397. /*n->narg.next = NULL; - stzalloc did it */
  11398. n->narg.text = wordtext;
  11399. n->narg.backquote = backquotelist;
  11400. here->here->nhere.doc = n;
  11401. here = here->next;
  11402. }
  11403. }
  11404. /*
  11405. * called by editline -- any expansions to the prompt should be added here.
  11406. */
  11407. static const char *
  11408. expandstr(const char *ps)
  11409. {
  11410. union node n;
  11411. int saveprompt;
  11412. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  11413. * and token processing _can_ alter it (delete NULs etc). */
  11414. setinputstring((char *)ps);
  11415. saveprompt = doprompt;
  11416. doprompt = 0;
  11417. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  11418. doprompt = saveprompt;
  11419. popfile();
  11420. n.narg.type = NARG;
  11421. n.narg.next = NULL;
  11422. n.narg.text = wordtext;
  11423. n.narg.backquote = backquotelist;
  11424. expandarg(&n, NULL, EXP_QUOTED);
  11425. return stackblock();
  11426. }
  11427. /*
  11428. * Execute a command or commands contained in a string.
  11429. */
  11430. static int
  11431. evalstring(char *s, int flags)
  11432. {
  11433. struct jmploc *volatile savehandler;
  11434. struct jmploc jmploc;
  11435. int ex;
  11436. union node *n;
  11437. struct stackmark smark;
  11438. int status;
  11439. s = sstrdup(s);
  11440. setinputstring(s);
  11441. setstackmark(&smark);
  11442. status = 0;
  11443. /* On exception inside execution loop, we must popfile().
  11444. * Try interactively:
  11445. * readonly a=a
  11446. * command eval "a=b" # throws "is read only" error
  11447. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11448. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11449. */
  11450. savehandler = exception_handler;
  11451. ex = setjmp(jmploc.loc);
  11452. if (ex)
  11453. goto out;
  11454. exception_handler = &jmploc;
  11455. while ((n = parsecmd(0)) != NODE_EOF) {
  11456. int i;
  11457. i = evaltree(n, flags);
  11458. if (n)
  11459. status = i;
  11460. popstackmark(&smark);
  11461. if (evalskip)
  11462. break;
  11463. }
  11464. out:
  11465. popstackmark(&smark);
  11466. popfile();
  11467. stunalloc(s);
  11468. exception_handler = savehandler;
  11469. if (ex)
  11470. longjmp(exception_handler->loc, ex);
  11471. return status;
  11472. }
  11473. /*
  11474. * The eval command.
  11475. */
  11476. static int FAST_FUNC
  11477. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11478. {
  11479. char *p;
  11480. char *concat;
  11481. if (argv[1]) {
  11482. p = argv[1];
  11483. argv += 2;
  11484. if (argv[0]) {
  11485. STARTSTACKSTR(concat);
  11486. for (;;) {
  11487. concat = stack_putstr(p, concat);
  11488. p = *argv++;
  11489. if (p == NULL)
  11490. break;
  11491. STPUTC(' ', concat);
  11492. }
  11493. STPUTC('\0', concat);
  11494. p = grabstackstr(concat);
  11495. }
  11496. return evalstring(p, flags & EV_TESTED);
  11497. }
  11498. return 0;
  11499. }
  11500. /*
  11501. * Read and execute commands.
  11502. * "Top" is nonzero for the top level command loop;
  11503. * it turns on prompting if the shell is interactive.
  11504. */
  11505. static int
  11506. cmdloop(int top)
  11507. {
  11508. union node *n;
  11509. struct stackmark smark;
  11510. int inter;
  11511. int status = 0;
  11512. int numeof = 0;
  11513. TRACE(("cmdloop(%d) called\n", top));
  11514. for (;;) {
  11515. int skip;
  11516. setstackmark(&smark);
  11517. #if JOBS
  11518. if (doing_jobctl)
  11519. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11520. #endif
  11521. inter = 0;
  11522. if (iflag && top) {
  11523. inter++;
  11524. chkmail();
  11525. }
  11526. n = parsecmd(inter);
  11527. #if DEBUG
  11528. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11529. showtree(n);
  11530. #endif
  11531. if (n == NODE_EOF) {
  11532. if (!top || numeof >= 50)
  11533. break;
  11534. if (!stoppedjobs()) {
  11535. if (!Iflag)
  11536. break;
  11537. out2str("\nUse \"exit\" to leave shell.\n");
  11538. }
  11539. numeof++;
  11540. } else if (nflag == 0) {
  11541. int i;
  11542. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11543. job_warning >>= 1;
  11544. numeof = 0;
  11545. i = evaltree(n, 0);
  11546. if (n)
  11547. status = i;
  11548. }
  11549. popstackmark(&smark);
  11550. skip = evalskip;
  11551. if (skip) {
  11552. evalskip &= ~SKIPFUNC;
  11553. break;
  11554. }
  11555. }
  11556. return status;
  11557. }
  11558. /*
  11559. * Take commands from a file. To be compatible we should do a path
  11560. * search for the file, which is necessary to find sub-commands.
  11561. */
  11562. static char *
  11563. find_dot_file(char *name)
  11564. {
  11565. char *fullname;
  11566. const char *path = pathval();
  11567. struct stat statb;
  11568. /* don't try this for absolute or relative paths */
  11569. if (strchr(name, '/'))
  11570. return name;
  11571. while ((fullname = path_advance(&path, name)) != NULL) {
  11572. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11573. /*
  11574. * Don't bother freeing here, since it will
  11575. * be freed by the caller.
  11576. */
  11577. return fullname;
  11578. }
  11579. if (fullname != name)
  11580. stunalloc(fullname);
  11581. }
  11582. /* not found in the PATH */
  11583. ash_msg_and_raise_error("%s: not found", name);
  11584. /* NOTREACHED */
  11585. }
  11586. static int FAST_FUNC
  11587. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  11588. {
  11589. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11590. int status = 0;
  11591. char *fullname;
  11592. char **argv;
  11593. char *args_need_save;
  11594. struct strlist *sp;
  11595. volatile struct shparam saveparam;
  11596. for (sp = cmdenviron; sp; sp = sp->next)
  11597. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11598. nextopt(nullstr); /* handle possible "--" */
  11599. argv = argptr;
  11600. if (!argv[0]) {
  11601. /* bash says: "bash: .: filename argument required" */
  11602. return 2; /* bash compat */
  11603. }
  11604. /* This aborts if file isn't found, which is POSIXly correct.
  11605. * bash returns exitcode 1 instead.
  11606. */
  11607. fullname = find_dot_file(argv[0]);
  11608. argv++;
  11609. args_need_save = argv[0];
  11610. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  11611. int argc;
  11612. saveparam = shellparam;
  11613. shellparam.malloced = 0;
  11614. argc = 1;
  11615. while (argv[argc])
  11616. argc++;
  11617. shellparam.nparam = argc;
  11618. shellparam.p = argv;
  11619. };
  11620. /* This aborts if file can't be opened, which is POSIXly correct.
  11621. * bash returns exitcode 1 instead.
  11622. */
  11623. setinputfile(fullname, INPUT_PUSH_FILE);
  11624. commandname = fullname;
  11625. status = cmdloop(0);
  11626. popfile();
  11627. if (args_need_save) {
  11628. freeparam(&shellparam);
  11629. shellparam = saveparam;
  11630. };
  11631. return status;
  11632. }
  11633. static int FAST_FUNC
  11634. exitcmd(int argc UNUSED_PARAM, char **argv)
  11635. {
  11636. if (stoppedjobs())
  11637. return 0;
  11638. if (argv[1])
  11639. exitstatus = number(argv[1]);
  11640. raise_exception(EXEXIT);
  11641. /* NOTREACHED */
  11642. }
  11643. /*
  11644. * Read a file containing shell functions.
  11645. */
  11646. static void
  11647. readcmdfile(char *name)
  11648. {
  11649. setinputfile(name, INPUT_PUSH_FILE);
  11650. cmdloop(0);
  11651. popfile();
  11652. }
  11653. /* ============ find_command inplementation */
  11654. /*
  11655. * Resolve a command name. If you change this routine, you may have to
  11656. * change the shellexec routine as well.
  11657. */
  11658. static void
  11659. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11660. {
  11661. struct tblentry *cmdp;
  11662. int idx;
  11663. int prev;
  11664. char *fullname;
  11665. struct stat statb;
  11666. int e;
  11667. int updatetbl;
  11668. struct builtincmd *bcmd;
  11669. /* If name contains a slash, don't use PATH or hash table */
  11670. if (strchr(name, '/') != NULL) {
  11671. entry->u.index = -1;
  11672. if (act & DO_ABS) {
  11673. while (stat(name, &statb) < 0) {
  11674. #ifdef SYSV
  11675. if (errno == EINTR)
  11676. continue;
  11677. #endif
  11678. entry->cmdtype = CMDUNKNOWN;
  11679. return;
  11680. }
  11681. }
  11682. entry->cmdtype = CMDNORMAL;
  11683. return;
  11684. }
  11685. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11686. updatetbl = (path == pathval());
  11687. if (!updatetbl) {
  11688. act |= DO_ALTPATH;
  11689. if (strstr(path, "%builtin") != NULL)
  11690. act |= DO_ALTBLTIN;
  11691. }
  11692. /* If name is in the table, check answer will be ok */
  11693. cmdp = cmdlookup(name, 0);
  11694. if (cmdp != NULL) {
  11695. int bit;
  11696. switch (cmdp->cmdtype) {
  11697. default:
  11698. #if DEBUG
  11699. abort();
  11700. #endif
  11701. case CMDNORMAL:
  11702. bit = DO_ALTPATH;
  11703. break;
  11704. case CMDFUNCTION:
  11705. bit = DO_NOFUNC;
  11706. break;
  11707. case CMDBUILTIN:
  11708. bit = DO_ALTBLTIN;
  11709. break;
  11710. }
  11711. if (act & bit) {
  11712. updatetbl = 0;
  11713. cmdp = NULL;
  11714. } else if (cmdp->rehash == 0)
  11715. /* if not invalidated by cd, we're done */
  11716. goto success;
  11717. }
  11718. /* If %builtin not in path, check for builtin next */
  11719. bcmd = find_builtin(name);
  11720. if (bcmd) {
  11721. if (IS_BUILTIN_REGULAR(bcmd))
  11722. goto builtin_success;
  11723. if (act & DO_ALTPATH) {
  11724. if (!(act & DO_ALTBLTIN))
  11725. goto builtin_success;
  11726. } else if (builtinloc <= 0) {
  11727. goto builtin_success;
  11728. }
  11729. }
  11730. #if ENABLE_FEATURE_SH_STANDALONE
  11731. {
  11732. int applet_no = find_applet_by_name(name);
  11733. if (applet_no >= 0) {
  11734. entry->cmdtype = CMDNORMAL;
  11735. entry->u.index = -2 - applet_no;
  11736. return;
  11737. }
  11738. }
  11739. #endif
  11740. /* We have to search path. */
  11741. prev = -1; /* where to start */
  11742. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11743. if (cmdp->cmdtype == CMDBUILTIN)
  11744. prev = builtinloc;
  11745. else
  11746. prev = cmdp->param.index;
  11747. }
  11748. e = ENOENT;
  11749. idx = -1;
  11750. loop:
  11751. while ((fullname = path_advance(&path, name)) != NULL) {
  11752. stunalloc(fullname);
  11753. /* NB: code below will still use fullname
  11754. * despite it being "unallocated" */
  11755. idx++;
  11756. if (pathopt) {
  11757. if (prefix(pathopt, "builtin")) {
  11758. if (bcmd)
  11759. goto builtin_success;
  11760. continue;
  11761. }
  11762. if ((act & DO_NOFUNC)
  11763. || !prefix(pathopt, "func")
  11764. ) { /* ignore unimplemented options */
  11765. continue;
  11766. }
  11767. }
  11768. /* if rehash, don't redo absolute path names */
  11769. if (fullname[0] == '/' && idx <= prev) {
  11770. if (idx < prev)
  11771. continue;
  11772. TRACE(("searchexec \"%s\": no change\n", name));
  11773. goto success;
  11774. }
  11775. while (stat(fullname, &statb) < 0) {
  11776. #ifdef SYSV
  11777. if (errno == EINTR)
  11778. continue;
  11779. #endif
  11780. if (errno != ENOENT && errno != ENOTDIR)
  11781. e = errno;
  11782. goto loop;
  11783. }
  11784. e = EACCES; /* if we fail, this will be the error */
  11785. if (!S_ISREG(statb.st_mode))
  11786. continue;
  11787. if (pathopt) { /* this is a %func directory */
  11788. stalloc(strlen(fullname) + 1);
  11789. /* NB: stalloc will return space pointed by fullname
  11790. * (because we don't have any intervening allocations
  11791. * between stunalloc above and this stalloc) */
  11792. readcmdfile(fullname);
  11793. cmdp = cmdlookup(name, 0);
  11794. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11795. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11796. stunalloc(fullname);
  11797. goto success;
  11798. }
  11799. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11800. if (!updatetbl) {
  11801. entry->cmdtype = CMDNORMAL;
  11802. entry->u.index = idx;
  11803. return;
  11804. }
  11805. INT_OFF;
  11806. cmdp = cmdlookup(name, 1);
  11807. cmdp->cmdtype = CMDNORMAL;
  11808. cmdp->param.index = idx;
  11809. INT_ON;
  11810. goto success;
  11811. }
  11812. /* We failed. If there was an entry for this command, delete it */
  11813. if (cmdp && updatetbl)
  11814. delete_cmd_entry();
  11815. if (act & DO_ERR)
  11816. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11817. entry->cmdtype = CMDUNKNOWN;
  11818. return;
  11819. builtin_success:
  11820. if (!updatetbl) {
  11821. entry->cmdtype = CMDBUILTIN;
  11822. entry->u.cmd = bcmd;
  11823. return;
  11824. }
  11825. INT_OFF;
  11826. cmdp = cmdlookup(name, 1);
  11827. cmdp->cmdtype = CMDBUILTIN;
  11828. cmdp->param.cmd = bcmd;
  11829. INT_ON;
  11830. success:
  11831. cmdp->rehash = 0;
  11832. entry->cmdtype = cmdp->cmdtype;
  11833. entry->u = cmdp->param;
  11834. }
  11835. /*
  11836. * The trap builtin.
  11837. */
  11838. static int FAST_FUNC
  11839. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11840. {
  11841. char *action;
  11842. char **ap;
  11843. int signo, exitcode;
  11844. nextopt(nullstr);
  11845. ap = argptr;
  11846. if (!*ap) {
  11847. for (signo = 0; signo < NSIG; signo++) {
  11848. char *tr = trap_ptr[signo];
  11849. if (tr) {
  11850. /* note: bash adds "SIG", but only if invoked
  11851. * as "bash". If called as "sh", or if set -o posix,
  11852. * then it prints short signal names.
  11853. * We are printing short names: */
  11854. out1fmt("trap -- %s %s\n",
  11855. single_quote(tr),
  11856. get_signame(signo));
  11857. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11858. * In this case, we will exit very soon, no need to free(). */
  11859. /* if (trap_ptr != trap && tp[0]) */
  11860. /* free(tr); */
  11861. }
  11862. }
  11863. /*
  11864. if (trap_ptr != trap) {
  11865. free(trap_ptr);
  11866. trap_ptr = trap;
  11867. }
  11868. */
  11869. return 0;
  11870. }
  11871. action = NULL;
  11872. if (ap[1])
  11873. action = *ap++;
  11874. exitcode = 0;
  11875. while (*ap) {
  11876. signo = get_signum(*ap);
  11877. if (signo < 0 || signo >= NSIG) {
  11878. /* Mimic bash message exactly */
  11879. ash_msg("%s: invalid signal specification", *ap);
  11880. exitcode = 1;
  11881. goto next;
  11882. }
  11883. INT_OFF;
  11884. if (action) {
  11885. if (LONE_DASH(action))
  11886. action = NULL;
  11887. else {
  11888. if (action[0]) /* not NULL and not "" and not "-" */
  11889. may_have_traps = 1;
  11890. action = ckstrdup(action);
  11891. }
  11892. }
  11893. free(trap[signo]);
  11894. trap[signo] = action;
  11895. if (signo != 0)
  11896. setsignal(signo);
  11897. INT_ON;
  11898. next:
  11899. ap++;
  11900. }
  11901. return exitcode;
  11902. }
  11903. /* ============ Builtins */
  11904. #if ENABLE_ASH_HELP
  11905. static int FAST_FUNC
  11906. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11907. {
  11908. unsigned col;
  11909. unsigned i;
  11910. out1fmt(
  11911. "Built-in commands:\n"
  11912. "------------------\n");
  11913. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11914. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11915. builtintab[i].name + 1);
  11916. if (col > 60) {
  11917. out1fmt("\n");
  11918. col = 0;
  11919. }
  11920. }
  11921. # if ENABLE_FEATURE_SH_STANDALONE
  11922. {
  11923. const char *a = applet_names;
  11924. while (*a) {
  11925. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11926. if (col > 60) {
  11927. out1fmt("\n");
  11928. col = 0;
  11929. }
  11930. while (*a++ != '\0')
  11931. continue;
  11932. }
  11933. }
  11934. # endif
  11935. newline_and_flush(stdout);
  11936. return EXIT_SUCCESS;
  11937. }
  11938. #endif
  11939. #if MAX_HISTORY
  11940. static int FAST_FUNC
  11941. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11942. {
  11943. show_history(line_input_state);
  11944. return EXIT_SUCCESS;
  11945. }
  11946. #endif
  11947. /*
  11948. * The export and readonly commands.
  11949. */
  11950. static int FAST_FUNC
  11951. exportcmd(int argc UNUSED_PARAM, char **argv)
  11952. {
  11953. struct var *vp;
  11954. char *name;
  11955. const char *p;
  11956. char **aptr;
  11957. char opt;
  11958. int flag;
  11959. int flag_off;
  11960. /* "readonly" in bash accepts, but ignores -n.
  11961. * We do the same: it saves a conditional in nextopt's param.
  11962. */
  11963. flag_off = 0;
  11964. while ((opt = nextopt("np")) != '\0') {
  11965. if (opt == 'n')
  11966. flag_off = VEXPORT;
  11967. }
  11968. flag = VEXPORT;
  11969. if (argv[0][0] == 'r') {
  11970. flag = VREADONLY;
  11971. flag_off = 0; /* readonly ignores -n */
  11972. }
  11973. flag_off = ~flag_off;
  11974. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  11975. {
  11976. aptr = argptr;
  11977. name = *aptr;
  11978. if (name) {
  11979. do {
  11980. p = strchr(name, '=');
  11981. if (p != NULL) {
  11982. p++;
  11983. } else {
  11984. vp = *findvar(hashvar(name), name);
  11985. if (vp) {
  11986. vp->flags = ((vp->flags | flag) & flag_off);
  11987. continue;
  11988. }
  11989. }
  11990. setvar(name, p, (flag & flag_off));
  11991. } while ((name = *++aptr) != NULL);
  11992. return 0;
  11993. }
  11994. }
  11995. /* No arguments. Show the list of exported or readonly vars.
  11996. * -n is ignored.
  11997. */
  11998. showvars(argv[0], flag, 0);
  11999. return 0;
  12000. }
  12001. /*
  12002. * Delete a function if it exists.
  12003. */
  12004. static void
  12005. unsetfunc(const char *name)
  12006. {
  12007. struct tblentry *cmdp;
  12008. cmdp = cmdlookup(name, 0);
  12009. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12010. delete_cmd_entry();
  12011. }
  12012. /*
  12013. * The unset builtin command. We unset the function before we unset the
  12014. * variable to allow a function to be unset when there is a readonly variable
  12015. * with the same name.
  12016. */
  12017. static int FAST_FUNC
  12018. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12019. {
  12020. char **ap;
  12021. int i;
  12022. int flag = 0;
  12023. int ret = 0;
  12024. while ((i = nextopt("vf")) != 0) {
  12025. flag = i;
  12026. }
  12027. for (ap = argptr; *ap; ap++) {
  12028. if (flag != 'f') {
  12029. i = unsetvar(*ap);
  12030. ret |= i;
  12031. if (!(i & 2))
  12032. continue;
  12033. }
  12034. if (flag != 'v')
  12035. unsetfunc(*ap);
  12036. }
  12037. return ret & 1;
  12038. }
  12039. static const unsigned char timescmd_str[] ALIGN1 = {
  12040. ' ', offsetof(struct tms, tms_utime),
  12041. '\n', offsetof(struct tms, tms_stime),
  12042. ' ', offsetof(struct tms, tms_cutime),
  12043. '\n', offsetof(struct tms, tms_cstime),
  12044. 0
  12045. };
  12046. static int FAST_FUNC
  12047. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12048. {
  12049. unsigned long clk_tck, s, t;
  12050. const unsigned char *p;
  12051. struct tms buf;
  12052. clk_tck = bb_clk_tck();
  12053. times(&buf);
  12054. p = timescmd_str;
  12055. do {
  12056. t = *(clock_t *)(((char *) &buf) + p[1]);
  12057. s = t / clk_tck;
  12058. t = t % clk_tck;
  12059. out1fmt("%lum%lu.%03lus%c",
  12060. s / 60, s % 60,
  12061. (t * 1000) / clk_tck,
  12062. p[0]);
  12063. p += 2;
  12064. } while (*p);
  12065. return 0;
  12066. }
  12067. #if ENABLE_FEATURE_SH_MATH
  12068. /*
  12069. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12070. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12071. *
  12072. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12073. */
  12074. static int FAST_FUNC
  12075. letcmd(int argc UNUSED_PARAM, char **argv)
  12076. {
  12077. arith_t i;
  12078. argv++;
  12079. if (!*argv)
  12080. ash_msg_and_raise_error("expression expected");
  12081. do {
  12082. i = ash_arith(*argv);
  12083. } while (*++argv);
  12084. return !i;
  12085. }
  12086. #endif
  12087. /*
  12088. * The read builtin. Options:
  12089. * -r Do not interpret '\' specially
  12090. * -s Turn off echo (tty only)
  12091. * -n NCHARS Read NCHARS max
  12092. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12093. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12094. * -u FD Read from given FD instead of fd 0
  12095. * This uses unbuffered input, which may be avoidable in some cases.
  12096. * TODO: bash also has:
  12097. * -a ARRAY Read into array[0],[1],etc
  12098. * -d DELIM End on DELIM char, not newline
  12099. * -e Use line editing (tty only)
  12100. */
  12101. static int FAST_FUNC
  12102. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12103. {
  12104. char *opt_n = NULL;
  12105. char *opt_p = NULL;
  12106. char *opt_t = NULL;
  12107. char *opt_u = NULL;
  12108. int read_flags = 0;
  12109. const char *r;
  12110. int i;
  12111. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  12112. switch (i) {
  12113. case 'p':
  12114. opt_p = optionarg;
  12115. break;
  12116. case 'n':
  12117. opt_n = optionarg;
  12118. break;
  12119. case 's':
  12120. read_flags |= BUILTIN_READ_SILENT;
  12121. break;
  12122. case 't':
  12123. opt_t = optionarg;
  12124. break;
  12125. case 'r':
  12126. read_flags |= BUILTIN_READ_RAW;
  12127. break;
  12128. case 'u':
  12129. opt_u = optionarg;
  12130. break;
  12131. default:
  12132. break;
  12133. }
  12134. }
  12135. /* "read -s" needs to save/restore termios, can't allow ^C
  12136. * to jump out of it.
  12137. */
  12138. again:
  12139. INT_OFF;
  12140. r = shell_builtin_read(setvar0,
  12141. argptr,
  12142. bltinlookup("IFS"), /* can be NULL */
  12143. read_flags,
  12144. opt_n,
  12145. opt_p,
  12146. opt_t,
  12147. opt_u
  12148. );
  12149. INT_ON;
  12150. if ((uintptr_t)r == 1 && errno == EINTR) {
  12151. /* to get SIGCHLD: sleep 1 & read x; echo $x */
  12152. if (pending_sig == 0)
  12153. goto again;
  12154. }
  12155. if ((uintptr_t)r > 1)
  12156. ash_msg_and_raise_error(r);
  12157. return (uintptr_t)r;
  12158. }
  12159. static int FAST_FUNC
  12160. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12161. {
  12162. static const char permuser[3] ALIGN1 = "ogu";
  12163. mode_t mask;
  12164. int symbolic_mode = 0;
  12165. while (nextopt("S") != '\0') {
  12166. symbolic_mode = 1;
  12167. }
  12168. INT_OFF;
  12169. mask = umask(0);
  12170. umask(mask);
  12171. INT_ON;
  12172. if (*argptr == NULL) {
  12173. if (symbolic_mode) {
  12174. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12175. char *p = buf;
  12176. int i;
  12177. i = 2;
  12178. for (;;) {
  12179. *p++ = ',';
  12180. *p++ = permuser[i];
  12181. *p++ = '=';
  12182. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12183. if (!(mask & 0400)) *p++ = 'r';
  12184. if (!(mask & 0200)) *p++ = 'w';
  12185. if (!(mask & 0100)) *p++ = 'x';
  12186. mask <<= 3;
  12187. if (--i < 0)
  12188. break;
  12189. }
  12190. *p = '\0';
  12191. puts(buf + 1);
  12192. } else {
  12193. out1fmt("%04o\n", mask);
  12194. }
  12195. } else {
  12196. char *modestr = *argptr;
  12197. /* numeric umasks are taken as-is */
  12198. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12199. if (!isdigit(modestr[0]))
  12200. mask ^= 0777;
  12201. mask = bb_parse_mode(modestr, mask);
  12202. if ((unsigned)mask > 0777) {
  12203. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12204. }
  12205. if (!isdigit(modestr[0]))
  12206. mask ^= 0777;
  12207. umask(mask);
  12208. }
  12209. return 0;
  12210. }
  12211. static int FAST_FUNC
  12212. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12213. {
  12214. return shell_builtin_ulimit(argv);
  12215. }
  12216. /* ============ main() and helpers */
  12217. /*
  12218. * Called to exit the shell.
  12219. */
  12220. static void
  12221. exitshell(void)
  12222. {
  12223. struct jmploc loc;
  12224. char *p;
  12225. int status;
  12226. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12227. save_history(line_input_state);
  12228. #endif
  12229. status = exitstatus;
  12230. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12231. if (setjmp(loc.loc)) {
  12232. if (exception_type == EXEXIT)
  12233. status = exitstatus;
  12234. goto out;
  12235. }
  12236. exception_handler = &loc;
  12237. p = trap[0];
  12238. if (p) {
  12239. trap[0] = NULL;
  12240. evalskip = 0;
  12241. evalstring(p, 0);
  12242. /*free(p); - we'll exit soon */
  12243. }
  12244. out:
  12245. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12246. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12247. */
  12248. setjobctl(0);
  12249. flush_stdout_stderr();
  12250. _exit(status);
  12251. /* NOTREACHED */
  12252. }
  12253. static void
  12254. init(void)
  12255. {
  12256. /* we will never free this */
  12257. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12258. sigmode[SIGCHLD - 1] = S_DFL;
  12259. setsignal(SIGCHLD);
  12260. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12261. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12262. */
  12263. signal(SIGHUP, SIG_DFL);
  12264. {
  12265. char **envp;
  12266. const char *p;
  12267. struct stat st1, st2;
  12268. initvar();
  12269. for (envp = environ; envp && *envp; envp++) {
  12270. p = endofname(*envp);
  12271. if (p != *envp && *p == '=') {
  12272. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12273. }
  12274. }
  12275. setvareq((char*)defoptindvar, VTEXTFIXED);
  12276. setvar0("PPID", utoa(getppid()));
  12277. #if BASH_SHLVL_VAR
  12278. p = lookupvar("SHLVL");
  12279. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12280. #endif
  12281. #if BASH_HOSTNAME_VAR
  12282. if (!lookupvar("HOSTNAME")) {
  12283. struct utsname uts;
  12284. uname(&uts);
  12285. setvar0("HOSTNAME", uts.nodename);
  12286. }
  12287. #endif
  12288. p = lookupvar("PWD");
  12289. if (p) {
  12290. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12291. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12292. ) {
  12293. p = NULL;
  12294. }
  12295. }
  12296. setpwd(p, 0);
  12297. }
  12298. }
  12299. //usage:#define ash_trivial_usage
  12300. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  12301. //usage:#define ash_full_usage "\n\n"
  12302. //usage: "Unix shell interpreter"
  12303. /*
  12304. * Process the shell command line arguments.
  12305. */
  12306. static void
  12307. procargs(char **argv)
  12308. {
  12309. int i;
  12310. const char *xminusc;
  12311. char **xargv;
  12312. xargv = argv;
  12313. arg0 = xargv[0];
  12314. /* if (xargv[0]) - mmm, this is always true! */
  12315. xargv++;
  12316. for (i = 0; i < NOPTS; i++)
  12317. optlist[i] = 2;
  12318. argptr = xargv;
  12319. if (options(/*cmdline:*/ 1)) {
  12320. /* it already printed err message */
  12321. raise_exception(EXERROR);
  12322. }
  12323. xargv = argptr;
  12324. xminusc = minusc;
  12325. if (*xargv == NULL) {
  12326. if (xminusc)
  12327. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12328. sflag = 1;
  12329. }
  12330. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12331. iflag = 1;
  12332. if (mflag == 2)
  12333. mflag = iflag;
  12334. for (i = 0; i < NOPTS; i++)
  12335. if (optlist[i] == 2)
  12336. optlist[i] = 0;
  12337. #if DEBUG == 2
  12338. debug = 1;
  12339. #endif
  12340. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12341. if (xminusc) {
  12342. minusc = *xargv++;
  12343. if (*xargv)
  12344. goto setarg0;
  12345. } else if (!sflag) {
  12346. setinputfile(*xargv, 0);
  12347. setarg0:
  12348. arg0 = *xargv++;
  12349. commandname = arg0;
  12350. }
  12351. shellparam.p = xargv;
  12352. #if ENABLE_ASH_GETOPTS
  12353. shellparam.optind = 1;
  12354. shellparam.optoff = -1;
  12355. #endif
  12356. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12357. while (*xargv) {
  12358. shellparam.nparam++;
  12359. xargv++;
  12360. }
  12361. optschanged();
  12362. }
  12363. /*
  12364. * Read /etc/profile, ~/.profile, $ENV.
  12365. */
  12366. static void
  12367. read_profile(const char *name)
  12368. {
  12369. name = expandstr(name);
  12370. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12371. return;
  12372. cmdloop(0);
  12373. popfile();
  12374. }
  12375. /*
  12376. * This routine is called when an error or an interrupt occurs in an
  12377. * interactive shell and control is returned to the main command loop.
  12378. * (In dash, this function is auto-generated by build machinery).
  12379. */
  12380. static void
  12381. reset(void)
  12382. {
  12383. /* from eval.c: */
  12384. evalskip = 0;
  12385. loopnest = 0;
  12386. /* from expand.c: */
  12387. ifsfree();
  12388. /* from input.c: */
  12389. g_parsefile->left_in_buffer = 0;
  12390. g_parsefile->left_in_line = 0; /* clear input buffer */
  12391. popallfiles();
  12392. /* from redir.c: */
  12393. while (redirlist)
  12394. popredir(/*drop:*/ 0, /*restore:*/ 0);
  12395. }
  12396. #if PROFILE
  12397. static short profile_buf[16384];
  12398. extern int etext();
  12399. #endif
  12400. /*
  12401. * Main routine. We initialize things, parse the arguments, execute
  12402. * profiles if we're a login shell, and then call cmdloop to execute
  12403. * commands. The setjmp call sets up the location to jump to when an
  12404. * exception occurs. When an exception occurs the variable "state"
  12405. * is used to figure out how far we had gotten.
  12406. */
  12407. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12408. int ash_main(int argc UNUSED_PARAM, char **argv)
  12409. {
  12410. volatile smallint state;
  12411. struct jmploc jmploc;
  12412. struct stackmark smark;
  12413. /* Initialize global data */
  12414. INIT_G_misc();
  12415. INIT_G_memstack();
  12416. INIT_G_var();
  12417. #if ENABLE_ASH_ALIAS
  12418. INIT_G_alias();
  12419. #endif
  12420. INIT_G_cmdtable();
  12421. #if PROFILE
  12422. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12423. #endif
  12424. #if ENABLE_FEATURE_EDITING
  12425. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12426. #endif
  12427. state = 0;
  12428. if (setjmp(jmploc.loc)) {
  12429. smallint e;
  12430. smallint s;
  12431. reset();
  12432. e = exception_type;
  12433. s = state;
  12434. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12435. exitshell();
  12436. }
  12437. if (e == EXINT) {
  12438. newline_and_flush(stderr);
  12439. }
  12440. popstackmark(&smark);
  12441. FORCE_INT_ON; /* enable interrupts */
  12442. if (s == 1)
  12443. goto state1;
  12444. if (s == 2)
  12445. goto state2;
  12446. if (s == 3)
  12447. goto state3;
  12448. goto state4;
  12449. }
  12450. exception_handler = &jmploc;
  12451. rootpid = getpid();
  12452. init();
  12453. setstackmark(&smark);
  12454. procargs(argv);
  12455. #if DEBUG
  12456. TRACE(("Shell args: "));
  12457. trace_puts_args(argv);
  12458. #endif
  12459. if (argv[0] && argv[0][0] == '-')
  12460. isloginsh = 1;
  12461. if (isloginsh) {
  12462. const char *hp;
  12463. state = 1;
  12464. read_profile("/etc/profile");
  12465. state1:
  12466. state = 2;
  12467. hp = lookupvar("HOME");
  12468. if (hp)
  12469. read_profile("$HOME/.profile");
  12470. }
  12471. state2:
  12472. state = 3;
  12473. if (
  12474. #ifndef linux
  12475. getuid() == geteuid() && getgid() == getegid() &&
  12476. #endif
  12477. iflag
  12478. ) {
  12479. const char *shinit = lookupvar("ENV");
  12480. if (shinit != NULL && *shinit != '\0')
  12481. read_profile(shinit);
  12482. }
  12483. popstackmark(&smark);
  12484. state3:
  12485. state = 4;
  12486. if (minusc) {
  12487. /* evalstring pushes parsefile stack.
  12488. * Ensure we don't falsely claim that 0 (stdin)
  12489. * is one of stacked source fds.
  12490. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12491. // if (!sflag) g_parsefile->pf_fd = -1;
  12492. // ^^ not necessary since now we special-case fd 0
  12493. // in is_hidden_fd() to not be considered "hidden fd"
  12494. evalstring(minusc, 0);
  12495. }
  12496. if (sflag || minusc == NULL) {
  12497. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12498. if (iflag) {
  12499. const char *hp = lookupvar("HISTFILE");
  12500. if (!hp) {
  12501. hp = lookupvar("HOME");
  12502. if (hp) {
  12503. INT_OFF;
  12504. hp = concat_path_file(hp, ".ash_history");
  12505. setvar0("HISTFILE", hp);
  12506. free((char*)hp);
  12507. INT_ON;
  12508. hp = lookupvar("HISTFILE");
  12509. }
  12510. }
  12511. if (hp)
  12512. line_input_state->hist_file = hp;
  12513. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12514. hp = lookupvar("HISTFILESIZE");
  12515. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12516. # endif
  12517. }
  12518. #endif
  12519. state4: /* XXX ??? - why isn't this before the "if" statement */
  12520. cmdloop(1);
  12521. }
  12522. #if PROFILE
  12523. monitor(0);
  12524. #endif
  12525. #ifdef GPROF
  12526. {
  12527. extern void _mcleanup(void);
  12528. _mcleanup();
  12529. }
  12530. #endif
  12531. TRACE(("End of main reached\n"));
  12532. exitshell();
  12533. /* NOTREACHED */
  12534. }
  12535. /*-
  12536. * Copyright (c) 1989, 1991, 1993, 1994
  12537. * The Regents of the University of California. All rights reserved.
  12538. *
  12539. * This code is derived from software contributed to Berkeley by
  12540. * Kenneth Almquist.
  12541. *
  12542. * Redistribution and use in source and binary forms, with or without
  12543. * modification, are permitted provided that the following conditions
  12544. * are met:
  12545. * 1. Redistributions of source code must retain the above copyright
  12546. * notice, this list of conditions and the following disclaimer.
  12547. * 2. Redistributions in binary form must reproduce the above copyright
  12548. * notice, this list of conditions and the following disclaimer in the
  12549. * documentation and/or other materials provided with the distribution.
  12550. * 3. Neither the name of the University nor the names of its contributors
  12551. * may be used to endorse or promote products derived from this software
  12552. * without specific prior written permission.
  12553. *
  12554. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12555. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12556. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12557. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12558. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12559. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12560. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12561. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12562. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12563. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12564. * SUCH DAMAGE.
  12565. */