ash.c 334 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854
  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 SHELL_ASH
  19. //config: bool #hidden option
  20. //config: depends on !NOMMU
  21. //config:
  22. //config:config ASH
  23. //config: bool "ash (80 kb)"
  24. //config: default y
  25. //config: depends on !NOMMU
  26. //config: select SHELL_ASH
  27. //config: help
  28. //config: The most complete and most pedantically correct shell included with
  29. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  30. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  31. //config: (written by Kenneth Almquist) from NetBSD.
  32. //config:
  33. //config:# ash options
  34. //config:# note: Don't remove !NOMMU part in the next line; it would break
  35. //config:# menuconfig's indenting.
  36. //config:if !NOMMU && (SHELL_ASH || ASH || SH_IS_ASH || BASH_IS_ASH)
  37. //config:
  38. //config:config ASH_OPTIMIZE_FOR_SIZE
  39. //config: bool "Optimize for size instead of speed"
  40. //config: default y
  41. //config: depends on SHELL_ASH
  42. //config:
  43. //config:config ASH_INTERNAL_GLOB
  44. //config: bool "Use internal glob() implementation"
  45. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  46. //config: depends on SHELL_ASH
  47. //config: help
  48. //config: Do not use glob() function from libc, use internal implementation.
  49. //config: Use this if you are getting "glob.h: No such file or directory"
  50. //config: or similar build errors.
  51. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  52. //config: which would break ash if you select N here.
  53. //config:
  54. //config:config ASH_BASH_COMPAT
  55. //config: bool "bash-compatible extensions"
  56. //config: default y
  57. //config: depends on SHELL_ASH
  58. //config:
  59. //config:config ASH_BASH_SOURCE_CURDIR
  60. //config: bool "'source' and '.' builtins search current directory after $PATH"
  61. //config: default n # do not encourage non-standard behavior
  62. //config: depends on ASH_BASH_COMPAT
  63. //config: help
  64. //config: This is not compliant with standards. Avoid if possible.
  65. //config:
  66. //config:config ASH_BASH_NOT_FOUND_HOOK
  67. //config: bool "command_not_found_handle hook support"
  68. //config: default y
  69. //config: depends on ASH_BASH_COMPAT
  70. //config: help
  71. //config: Enable support for the 'command_not_found_handle' hook function,
  72. //config: from GNU bash, which allows for alternative command not found
  73. //config: handling.
  74. //config:
  75. //config:config ASH_JOB_CONTROL
  76. //config: bool "Job control"
  77. //config: default y
  78. //config: depends on SHELL_ASH
  79. //config:
  80. //config:config ASH_ALIAS
  81. //config: bool "Alias support"
  82. //config: default y
  83. //config: depends on SHELL_ASH
  84. //config:
  85. //config:config ASH_RANDOM_SUPPORT
  86. //config: bool "Pseudorandom generator and $RANDOM variable"
  87. //config: default y
  88. //config: depends on SHELL_ASH
  89. //config: help
  90. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  91. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  92. //config: You can reset the generator by using a specified start value.
  93. //config: After "unset RANDOM" the generator will switch off and this
  94. //config: variable will no longer have special treatment.
  95. //config:
  96. //config:config ASH_EXPAND_PRMT
  97. //config: bool "Expand prompt string"
  98. //config: default y
  99. //config: depends on SHELL_ASH
  100. //config: help
  101. //config: $PS# may contain volatile content, such as backquote commands.
  102. //config: This option recreates the prompt string from the environment
  103. //config: variable each time it is displayed.
  104. //config:
  105. //config:config ASH_IDLE_TIMEOUT
  106. //config: bool "Idle timeout variable $TMOUT"
  107. //config: default y
  108. //config: depends on SHELL_ASH
  109. //config: help
  110. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  111. //config:
  112. //config:config ASH_MAIL
  113. //config: bool "Check for new mail in interactive shell"
  114. //config: default y
  115. //config: depends on SHELL_ASH
  116. //config: help
  117. //config: Enable "check for new mail" function:
  118. //config: if set, $MAIL file and $MAILPATH list of files
  119. //config: are checked for mtime changes, and "you have mail"
  120. //config: message is printed if change is detected.
  121. //config:
  122. //config:config ASH_ECHO
  123. //config: bool "echo builtin"
  124. //config: default y
  125. //config: depends on SHELL_ASH
  126. //config:
  127. //config:config ASH_PRINTF
  128. //config: bool "printf builtin"
  129. //config: default y
  130. //config: depends on SHELL_ASH
  131. //config:
  132. //config:config ASH_TEST
  133. //config: bool "test builtin"
  134. //config: default y
  135. //config: depends on SHELL_ASH
  136. //config:
  137. //
  138. ////config:config ASH_SLEEP
  139. ////config: bool "sleep builtin"
  140. ////config: default y
  141. ////config: depends on SHELL_ASH
  142. ////config:
  143. //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  144. //Disabled for now. Has a few annoying problems:
  145. // * sleepcmd() -> sleep_main(), the parsing of bad arguments exits the shell.
  146. // * sleep_for_duration() in sleep_main() has to be interruptible for
  147. // ^C traps to work, which may be a problem for other users
  148. // of sleep_for_duration().
  149. // * BUT, if sleep_for_duration() is interruptible, then SIGCHLD interrupts it
  150. // as well (try "/bin/sleep 1 & sleep 10").
  151. // * sleep_main() must not allocate anything as ^C in ash longjmp's.
  152. // (currently, allocations are only on error paths, in message printing).
  153. //
  154. //config:config ASH_HELP
  155. //config: bool "help builtin"
  156. //config: default y
  157. //config: depends on SHELL_ASH
  158. //config:
  159. //config:config ASH_GETOPTS
  160. //config: bool "getopts builtin"
  161. //config: default y
  162. //config: depends on SHELL_ASH
  163. //config:
  164. //config:config ASH_CMDCMD
  165. //config: bool "command builtin"
  166. //config: default y
  167. //config: depends on SHELL_ASH
  168. //config: help
  169. //config: Enable support for the 'command' builtin, which allows
  170. //config: you to run the specified command or builtin,
  171. //config: even when there is a function with the same name.
  172. //config:
  173. //config:endif # ash options
  174. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  175. // APPLET_ODDNAME:name main location suid_type help
  176. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  177. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  178. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  179. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  180. /*
  181. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  182. * DEBUG=2 to compile in and turn on debugging.
  183. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  184. * debugging info is written to ./trace, quit signal generates core dump.
  185. */
  186. #define DEBUG 0
  187. /* Tweak debug output verbosity here */
  188. #define DEBUG_TIME 0
  189. #define DEBUG_PID 1
  190. #define DEBUG_SIG 1
  191. #define DEBUG_INTONOFF 0
  192. #define PROFILE 0
  193. #define JOBS ENABLE_ASH_JOB_CONTROL
  194. #include <fnmatch.h>
  195. #include <sys/times.h>
  196. #include <sys/utsname.h> /* for setting $HOSTNAME */
  197. #include "busybox.h" /* for applet_names */
  198. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  199. # include "embedded_scripts.h"
  200. #else
  201. # define NUM_SCRIPTS 0
  202. #endif
  203. /* So far, all bash compat is controlled by one config option */
  204. /* Separate defines document which part of code implements what */
  205. /* function keyword */
  206. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  207. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  208. /* &>file */
  209. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  210. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  211. /* $'...' */
  212. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  213. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  214. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  215. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  216. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  217. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  218. /* BASH_TEST2: [[ EXPR ]]
  219. * Status of [[ support:
  220. * && and || work as they should
  221. * = is glob match operator, not equality operator: STR = GLOB
  222. * == same as =
  223. * =~ is regex match operator: STR =~ REGEX
  224. * TODO:
  225. * singleword+noglob expansion:
  226. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  227. * [[ /bin/n* ]]; echo 0:$?
  228. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  229. * ( ) < > should not have special meaning (IOW: should not require quoting)
  230. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  231. */
  232. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  233. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  234. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  235. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  236. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  237. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  238. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  239. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  240. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  241. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  242. /* <(...) and >(...) */
  243. #if HAVE_DEV_FD
  244. # define BASH_PROCESS_SUBST ENABLE_ASH_BASH_COMPAT
  245. # define IF_BASH_PROCESS_SUBST IF_ASH_BASH_COMPAT
  246. #else
  247. # define BASH_PROCESS_SUBST 0
  248. # define IF_BASH_PROCESS_SUBST(...)
  249. #endif
  250. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  251. /* Bionic at least up to version 24 has no glob() */
  252. # undef ENABLE_ASH_INTERNAL_GLOB
  253. # define ENABLE_ASH_INTERNAL_GLOB 1
  254. #endif
  255. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  256. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  257. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  258. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  259. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  260. # error fails to match dirname, subsequently not expanding <pattern> in it.
  261. // Testcase:
  262. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  263. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  264. #endif
  265. #if !ENABLE_ASH_INTERNAL_GLOB
  266. # include <glob.h>
  267. #endif
  268. #include "unicode.h"
  269. #include "shell_common.h"
  270. #if ENABLE_FEATURE_SH_MATH
  271. # include "math.h"
  272. #else
  273. typedef long arith_t;
  274. # define ARITH_FMT "%ld"
  275. #endif
  276. #if ENABLE_ASH_RANDOM_SUPPORT
  277. # include "random.h"
  278. #else
  279. # define CLEAR_RANDOM_T(rnd) ((void)0)
  280. #endif
  281. #include "NUM_APPLETS.h"
  282. #if NUM_APPLETS == 1
  283. /* STANDALONE does not make sense, and won't compile */
  284. # undef CONFIG_FEATURE_SH_STANDALONE
  285. # undef ENABLE_FEATURE_SH_STANDALONE
  286. # undef IF_FEATURE_SH_STANDALONE
  287. # undef IF_NOT_FEATURE_SH_STANDALONE
  288. # define ENABLE_FEATURE_SH_STANDALONE 0
  289. # define IF_FEATURE_SH_STANDALONE(...)
  290. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  291. #endif
  292. #ifndef F_DUPFD_CLOEXEC
  293. # define F_DUPFD_CLOEXEC F_DUPFD
  294. #endif
  295. #ifndef O_CLOEXEC
  296. # define O_CLOEXEC 0
  297. #endif
  298. #ifndef PIPE_BUF
  299. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  300. #endif
  301. #ifndef unlikely
  302. # define unlikely(cond) (cond)
  303. #endif
  304. #if !BB_MMU
  305. # error "Do not even bother, ash will not run on NOMMU machine"
  306. #endif
  307. /* ============ Hash table sizes. Configurable. */
  308. #define VTABSIZE 39
  309. #define ATABSIZE 39
  310. #define CMDTABLESIZE 31 /* should be prime */
  311. /* ============ Shell options */
  312. /* If you add/change options hare, update --help text too */
  313. static const char *const optletters_optnames[] ALIGN_PTR = {
  314. "e" "errexit",
  315. "f" "noglob",
  316. /* bash has '-o ignoreeof', but no short synonym -I for it */
  317. /* (in bash, set -I disables invisible variables (what's that?)) */
  318. "I" "ignoreeof",
  319. /* The below allowed this invocation:
  320. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  321. * to be ^C-ed and get to interactive ash prompt.
  322. * bash does not support such "set -i".
  323. * In our code, this is denoted by empty long name:
  324. */
  325. "i" "",
  326. /* (removing "i" altogether would remove it from "$-", not good) */
  327. "m" "monitor",
  328. "n" "noexec",
  329. /* Ditto: bash has no "set -s", "set -c" */
  330. "s" "",
  331. "c" "",
  332. "x" "xtrace",
  333. "v" "verbose",
  334. "C" "noclobber",
  335. "a" "allexport",
  336. "b" "notify",
  337. "u" "nounset",
  338. "E" "errtrace",
  339. "\0" "vi"
  340. #if BASH_PIPEFAIL
  341. ,"\0" "pipefail"
  342. #endif
  343. #if DEBUG
  344. ,"\0" "nolog"
  345. ,"\0" "debug"
  346. #endif
  347. };
  348. //bash 4.4.23 also has these opts (with these defaults):
  349. //braceexpand on
  350. //emacs on
  351. //errtrace off
  352. //functrace off
  353. //hashall on
  354. //histexpand off
  355. //history on
  356. //interactive-comments on
  357. //keyword off
  358. //onecmd off
  359. //physical off
  360. //posix off
  361. //privileged off
  362. #define optletters(n) optletters_optnames[n][0]
  363. #define optnames(n) (optletters_optnames[n] + 1)
  364. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  365. /* ============ Misc data */
  366. #define msg_illnum "Illegal number: %s"
  367. /*
  368. * We enclose jmp_buf in a structure so that we can declare pointers to
  369. * jump locations. The global variable handler contains the location to
  370. * jump to when an exception occurs, and the global variable exception_type
  371. * contains a code identifying the exception. To implement nested
  372. * exception handlers, the user should save the value of handler on entry
  373. * to an inner scope, set handler to point to a jmploc structure for the
  374. * inner scope, and restore handler on exit from the scope.
  375. */
  376. struct jmploc {
  377. jmp_buf loc;
  378. };
  379. struct globals_misc {
  380. uint8_t exitstatus; /* exit status of last command */
  381. uint8_t back_exitstatus;/* exit status of backquoted command */
  382. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  383. smallint inps4; /* Prevent PS4 nesting. */
  384. int savestatus; /* exit status of last command outside traps */
  385. int rootpid; /* pid of main shell */
  386. /* shell level: 0 for the main shell, 1 for its children, and so on */
  387. int shlvl;
  388. #define rootshell (!shlvl)
  389. int errlinno;
  390. char *minusc; /* argument to -c option */
  391. char *curdir; // = nullstr; /* current working directory */
  392. char *physdir; // = nullstr; /* physical working directory */
  393. char *arg0; /* value of $0 */
  394. struct jmploc *exception_handler;
  395. /*volatile*/ int suppress_int; /* counter */
  396. /* ^^^^^^^ removed "volatile" since on x86, gcc turns suppress_int++
  397. * into ridiculous 3-insn sequence otherwise.
  398. * We don't change suppress_int asyncronously (in a signal handler),
  399. * but we do read it async.
  400. */
  401. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  402. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  403. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  404. smallint exception_type; /* kind of exception: */
  405. #define EXINT 0 /* SIGINT received */
  406. #define EXERROR 1 /* a generic error */
  407. #define EXEND 3 /* exit the shell */
  408. #define EXEXIT 4 /* exit the shell via exitcmd */
  409. char nullstr[1]; /* zero length string */
  410. char optlist[NOPTS];
  411. #define eflag optlist[0]
  412. #define fflag optlist[1]
  413. #define Iflag optlist[2]
  414. #define iflag optlist[3]
  415. #define mflag optlist[4]
  416. #define nflag optlist[5]
  417. #define sflag optlist[6]
  418. #define cflag optlist[7]
  419. #define xflag optlist[8]
  420. #define vflag optlist[9]
  421. #define Cflag optlist[10]
  422. #define aflag optlist[11]
  423. #define bflag optlist[12]
  424. #define uflag optlist[13]
  425. #define Eflag optlist[14]
  426. #define viflag optlist[15]
  427. #if BASH_PIPEFAIL
  428. # define pipefail optlist[16]
  429. #else
  430. # define pipefail 0
  431. #endif
  432. #if DEBUG
  433. # define nolog optlist[16 + BASH_PIPEFAIL]
  434. # define debug optlist[17 + BASH_PIPEFAIL]
  435. #endif
  436. /* trap handler commands */
  437. /*
  438. * Sigmode records the current value of the signal handlers for the various
  439. * modes. A value of zero means that the current handler is not known.
  440. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  441. */
  442. char sigmode[NSIG - 1];
  443. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  444. #define S_CATCH 2 /* signal is caught */
  445. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  446. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  447. /* indicates specified signal received */
  448. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  449. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  450. char *trap[NSIG + 1];
  451. /* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */
  452. #define NTRAP_ERR NSIG
  453. #define NTRAP_LAST NSIG
  454. char **trap_ptr; /* used only by "trap hack" */
  455. /* Rarely referenced stuff */
  456. #if ENABLE_ASH_RANDOM_SUPPORT
  457. random_t random_gen;
  458. #endif
  459. pid_t backgndpid; /* pid of last background process */
  460. };
  461. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  462. #define G_misc (*ash_ptr_to_globals_misc)
  463. #define exitstatus (G_misc.exitstatus )
  464. #define back_exitstatus (G_misc.back_exitstatus )
  465. #define job_warning (G_misc.job_warning)
  466. #define inps4 (G_misc.inps4 )
  467. #define savestatus (G_misc.savestatus )
  468. #define rootpid (G_misc.rootpid )
  469. #define shlvl (G_misc.shlvl )
  470. #define errlinno (G_misc.errlinno )
  471. #define minusc (G_misc.minusc )
  472. #define curdir (G_misc.curdir )
  473. #define physdir (G_misc.physdir )
  474. #define arg0 (G_misc.arg0 )
  475. #define exception_handler (G_misc.exception_handler)
  476. #define exception_type (G_misc.exception_type )
  477. #define suppress_int (G_misc.suppress_int )
  478. #define pending_int (G_misc.pending_int )
  479. #define got_sigchld (G_misc.got_sigchld )
  480. #define pending_sig (G_misc.pending_sig )
  481. #define nullstr (G_misc.nullstr )
  482. #define optlist (G_misc.optlist )
  483. #define sigmode (G_misc.sigmode )
  484. #define gotsig (G_misc.gotsig )
  485. #define may_have_traps (G_misc.may_have_traps )
  486. #define trap (G_misc.trap )
  487. #define trap_ptr (G_misc.trap_ptr )
  488. #define random_gen (G_misc.random_gen )
  489. #define backgndpid (G_misc.backgndpid )
  490. #define INIT_G_misc() do { \
  491. XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \
  492. savestatus = -1; \
  493. curdir = nullstr; \
  494. physdir = nullstr; \
  495. trap_ptr = trap; \
  496. } while (0)
  497. /* ============ DEBUG */
  498. #if DEBUG
  499. static void trace_printf(const char *fmt, ...);
  500. static void trace_vprintf(const char *fmt, va_list va);
  501. # define TRACE(param) trace_printf param
  502. # define TRACEV(param) trace_vprintf param
  503. # define close(fd) do { \
  504. int dfd = (fd); \
  505. if (close(dfd) < 0) \
  506. bb_error_msg("bug on %d: closing %d(0x%x)", \
  507. __LINE__, dfd, dfd); \
  508. } while (0)
  509. #else
  510. # define TRACE(param)
  511. # define TRACEV(param)
  512. #endif
  513. /* ============ Utility functions */
  514. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  515. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  516. static int
  517. isdigit_str9(const char *str)
  518. {
  519. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  520. while (--maxlen && isdigit(*str))
  521. str++;
  522. return (*str == '\0');
  523. }
  524. static const char *
  525. var_end(const char *var)
  526. {
  527. while (*var)
  528. if (*var++ == '=')
  529. break;
  530. return var;
  531. }
  532. /* ============ Parser data */
  533. /*
  534. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  535. */
  536. struct strlist {
  537. struct strlist *next;
  538. char *text;
  539. };
  540. struct alias;
  541. struct strpush {
  542. struct strpush *prev; /* preceding string on stack */
  543. char *prev_string;
  544. int prev_left_in_line;
  545. #if ENABLE_ASH_ALIAS
  546. struct alias *ap; /* if push was associated with an alias */
  547. #endif
  548. char *string; /* remember the string since it may change */
  549. /* Delay freeing so we can stop nested aliases. */
  550. struct strpush *spfree;
  551. /* Remember last two characters for pungetc. */
  552. int lastc[2];
  553. /* Number of outstanding calls to pungetc. */
  554. int unget;
  555. };
  556. /*
  557. * The parsefile structure pointed to by the global variable parsefile
  558. * contains information about the current file being read.
  559. */
  560. struct parsefile {
  561. struct parsefile *prev; /* preceding file on stack */
  562. int linno; /* current line */
  563. int pf_fd; /* file descriptor (or -1 if string) */
  564. int left_in_line; /* number of chars left in this line */
  565. int left_in_buffer; /* number of chars left in this buffer past the line */
  566. char *next_to_pgetc; /* next char in buffer */
  567. char *buf; /* input buffer */
  568. struct strpush *strpush; /* for pushing strings at this level */
  569. struct strpush basestrpush; /* so pushing one is fast */
  570. /* Delay freeing so we can stop nested aliases. */
  571. struct strpush *spfree;
  572. /* Remember last two characters for pungetc. */
  573. int lastc[2];
  574. /* Number of outstanding calls to pungetc. */
  575. int unget;
  576. };
  577. static struct parsefile basepf; /* top level input file */
  578. static struct parsefile *g_parsefile = &basepf; /* current input file */
  579. static char *commandname; /* currently executing command */
  580. /* ============ Interrupts / exceptions */
  581. static void exitshell(void) NORETURN;
  582. /*
  583. * These macros allow the user to suspend the handling of interrupt signals
  584. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  585. * much more efficient and portable. (But hacking the kernel is so much
  586. * more fun than worrying about efficiency and portability. :-))
  587. */
  588. #if DEBUG_INTONOFF
  589. # define INT_OFF do { \
  590. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  591. suppress_int++; \
  592. barrier(); \
  593. } while (0)
  594. #else
  595. # define INT_OFF do { \
  596. suppress_int++; \
  597. barrier(); \
  598. } while (0)
  599. #endif
  600. /*
  601. * Called to raise an exception. Since C doesn't include exceptions, we
  602. * just do a longjmp to the exception handler. The type of exception is
  603. * stored in the global variable "exception_type".
  604. */
  605. static void raise_exception(int) NORETURN;
  606. static void
  607. raise_exception(int e)
  608. {
  609. #if DEBUG
  610. if (exception_handler == NULL)
  611. abort();
  612. #endif
  613. INT_OFF;
  614. exception_type = e;
  615. longjmp(exception_handler->loc, 1);
  616. }
  617. #if DEBUG
  618. #define raise_exception(e) do { \
  619. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  620. raise_exception(e); \
  621. } while (0)
  622. #endif
  623. /*
  624. * Called when a SIGINT is received. (If the user specifies
  625. * that SIGINT is to be trapped or ignored using the trap builtin, then
  626. * this routine is not called.) suppress_int is nonzero when interrupts
  627. * are held using the INT_OFF macro. (The test for iflag is just
  628. * defensive programming.)
  629. */
  630. static void raise_interrupt(void) NORETURN;
  631. static void
  632. raise_interrupt(void)
  633. {
  634. pending_int = 0;
  635. /* Signal is not automatically unmasked after it is raised,
  636. * do it ourself - unmask all signals */
  637. sigprocmask_allsigs(SIG_UNBLOCK);
  638. /* pending_sig = 0; - now done in signal_handler() */
  639. if (!(rootshell && iflag)) {
  640. /* Kill ourself with SIGINT */
  641. signal(SIGINT, SIG_DFL);
  642. raise(SIGINT);
  643. }
  644. /* bash: ^C even on empty command line sets $? */
  645. exitstatus = SIGINT + 128;
  646. raise_exception(EXINT);
  647. /* NOTREACHED */
  648. }
  649. #if DEBUG
  650. #define raise_interrupt() do { \
  651. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  652. raise_interrupt(); \
  653. } while (0)
  654. #endif
  655. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  656. int_on(void)
  657. {
  658. barrier();
  659. if (--suppress_int == 0 && pending_int)
  660. raise_interrupt(); /* does not return */
  661. barrier();
  662. }
  663. #if DEBUG_INTONOFF
  664. # define INT_ON do { \
  665. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  666. int_on(); \
  667. } while (0)
  668. #else
  669. # define INT_ON int_on()
  670. #endif
  671. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  672. force_int_on(void)
  673. {
  674. barrier();
  675. suppress_int = 0;
  676. if (pending_int)
  677. raise_interrupt(); /* does not return */
  678. barrier();
  679. }
  680. #define FORCE_INT_ON force_int_on()
  681. #define SAVE_INT(v) ((v) = suppress_int)
  682. #define RESTORE_INT(v) do { \
  683. barrier(); \
  684. suppress_int = (v); \
  685. if (suppress_int == 0 && pending_int) \
  686. raise_interrupt(); /* does not return */ \
  687. barrier(); \
  688. } while (0)
  689. /* ============ Stdout/stderr output */
  690. static void
  691. outstr(const char *p, FILE *file)
  692. {
  693. INT_OFF;
  694. fputs(p, file);
  695. INT_ON;
  696. }
  697. static void
  698. flush_stdout_stderr(void)
  699. {
  700. INT_OFF;
  701. fflush_all();
  702. INT_ON;
  703. }
  704. /* Was called outcslow(c,FILE*), but c was always '\n' */
  705. static void
  706. newline_and_flush(FILE *dest)
  707. {
  708. INT_OFF;
  709. putc('\n', dest);
  710. fflush(dest);
  711. INT_ON;
  712. }
  713. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  714. static int
  715. out1fmt(const char *fmt, ...)
  716. {
  717. va_list ap;
  718. int r;
  719. INT_OFF;
  720. va_start(ap, fmt);
  721. r = vprintf(fmt, ap);
  722. va_end(ap);
  723. INT_ON;
  724. return r;
  725. }
  726. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  727. static int
  728. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  729. {
  730. va_list ap;
  731. int ret;
  732. INT_OFF;
  733. va_start(ap, fmt);
  734. ret = vsnprintf(outbuf, length, fmt, ap);
  735. va_end(ap);
  736. INT_ON;
  737. return ret > (int)length ? length : ret;
  738. }
  739. static void
  740. out1str(const char *p)
  741. {
  742. outstr(p, stdout);
  743. }
  744. static void
  745. out2str(const char *p)
  746. {
  747. outstr(p, stderr);
  748. flush_stdout_stderr();
  749. }
  750. /* ============ Parser structures */
  751. /* control characters in argument strings */
  752. #define CTL_FIRST CTLESC
  753. #define CTLESC ((unsigned char)'\201') /* escape next character */
  754. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  755. #define CTLENDVAR ((unsigned char)'\203')
  756. #define CTLBACKQ ((unsigned char)'\204')
  757. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  758. #define CTLENDARI ((unsigned char)'\207')
  759. #define CTLQUOTEMARK ((unsigned char)'\210')
  760. #define CTL_LAST CTLQUOTEMARK
  761. #if BASH_PROCESS_SUBST
  762. # define CTLTOPROC ((unsigned char)'\211')
  763. # define CTLFROMPROC ((unsigned char)'\212')
  764. # undef CTL_LAST
  765. # define CTL_LAST CTLFROMPROC
  766. #endif
  767. /* variable substitution byte (follows CTLVAR) */
  768. #define VSTYPE 0x0f /* type of variable substitution */
  769. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  770. /* values of VSTYPE field */
  771. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  772. #define VSMINUS 0x2 /* ${var-text} */
  773. #define VSPLUS 0x3 /* ${var+text} */
  774. #define VSQUESTION 0x4 /* ${var?message} */
  775. #define VSASSIGN 0x5 /* ${var=text} */
  776. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  777. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  778. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  779. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  780. #define VSLENGTH 0xa /* ${#var} */
  781. #if BASH_SUBSTR
  782. #define VSSUBSTR 0xc /* ${var:position:length} */
  783. #endif
  784. #if BASH_PATTERN_SUBST
  785. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  786. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  787. #endif
  788. static const char dolatstr[] ALIGN1 = {
  789. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  790. };
  791. #define DOLATSTRLEN 6
  792. #define NCMD 0
  793. #define NPIPE 1
  794. #define NREDIR 2
  795. #define NBACKGND 3
  796. #define NSUBSHELL 4
  797. #define NAND 5
  798. #define NOR 6
  799. #define NSEMI 7
  800. #define NIF 8
  801. #define NWHILE 9
  802. #define NUNTIL 10
  803. #define NFOR 11
  804. #define NCASE 12
  805. #define NCLIST 13
  806. #define NDEFUN 14
  807. #define NARG 15
  808. #define NTO 16
  809. #if BASH_REDIR_OUTPUT
  810. #define NTO2 17
  811. #endif
  812. #define NCLOBBER 18
  813. #define NFROM 19
  814. #define NFROMTO 20
  815. #define NAPPEND 21
  816. #define NTOFD 22
  817. #define NFROMFD 23
  818. #define NHERE 24
  819. #define NXHERE 25
  820. #define NNOT 26
  821. #define N_NUMBER 27
  822. union node;
  823. struct ncmd {
  824. smallint type; /* Nxxxx */
  825. int linno;
  826. union node *assign;
  827. union node *args;
  828. union node *redirect;
  829. };
  830. struct npipe {
  831. smallint type;
  832. smallint pipe_backgnd;
  833. struct nodelist *cmdlist;
  834. };
  835. struct nredir {
  836. smallint type;
  837. int linno;
  838. union node *n;
  839. union node *redirect;
  840. };
  841. struct nbinary {
  842. smallint type;
  843. union node *ch1;
  844. union node *ch2;
  845. };
  846. struct nif {
  847. smallint type;
  848. union node *test;
  849. union node *ifpart;
  850. union node *elsepart;
  851. };
  852. struct nfor {
  853. smallint type;
  854. int linno;
  855. union node *args;
  856. union node *body;
  857. char *var;
  858. };
  859. struct ncase {
  860. smallint type;
  861. int linno;
  862. union node *expr;
  863. union node *cases;
  864. };
  865. struct nclist {
  866. smallint type;
  867. union node *next;
  868. union node *pattern;
  869. union node *body;
  870. };
  871. struct ndefun {
  872. smallint type;
  873. int linno;
  874. char *text;
  875. union node *body;
  876. };
  877. struct narg {
  878. smallint type;
  879. union node *next;
  880. char *text;
  881. struct nodelist *backquote;
  882. };
  883. /* nfile and ndup layout must match!
  884. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  885. * that it is actually NTO2 (>&file), and change its type.
  886. */
  887. struct nfile {
  888. smallint type;
  889. union node *next;
  890. int fd;
  891. int _unused_dupfd;
  892. union node *fname;
  893. char *expfname;
  894. };
  895. struct ndup {
  896. smallint type;
  897. union node *next;
  898. int fd;
  899. int dupfd;
  900. union node *vname;
  901. char *_unused_expfname;
  902. };
  903. struct nhere {
  904. smallint type;
  905. union node *next;
  906. int fd;
  907. union node *doc;
  908. };
  909. struct nnot {
  910. smallint type;
  911. union node *com;
  912. };
  913. union node {
  914. smallint type;
  915. struct ncmd ncmd;
  916. struct npipe npipe;
  917. struct nredir nredir;
  918. struct nbinary nbinary;
  919. struct nif nif;
  920. struct nfor nfor;
  921. struct ncase ncase;
  922. struct nclist nclist;
  923. struct ndefun ndefun;
  924. struct narg narg;
  925. struct nfile nfile;
  926. struct ndup ndup;
  927. struct nhere nhere;
  928. struct nnot nnot;
  929. };
  930. /*
  931. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  932. * It must be distinct from NULL.
  933. */
  934. #define NODE_EOF ((union node *) -1L)
  935. struct nodelist {
  936. struct nodelist *next;
  937. union node *n;
  938. };
  939. struct funcnode {
  940. int count;
  941. union node n;
  942. };
  943. /*
  944. * Free a parse tree.
  945. */
  946. static void
  947. freefunc(struct funcnode *f)
  948. {
  949. if (f && --f->count < 0)
  950. free(f);
  951. }
  952. /* ============ Debugging output */
  953. #if DEBUG
  954. static FILE *tracefile;
  955. static void
  956. trace_printf(const char *fmt, ...)
  957. {
  958. va_list va;
  959. if (debug != 1)
  960. return;
  961. if (DEBUG_TIME)
  962. fprintf(tracefile, "%u ", (int) time(NULL));
  963. if (DEBUG_PID)
  964. fprintf(tracefile, "[%u] ", (int) getpid());
  965. if (DEBUG_SIG)
  966. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  967. va_start(va, fmt);
  968. vfprintf(tracefile, fmt, va);
  969. va_end(va);
  970. }
  971. static void
  972. trace_vprintf(const char *fmt, va_list va)
  973. {
  974. if (debug != 1)
  975. return;
  976. vfprintf(tracefile, fmt, va);
  977. fprintf(tracefile, "\n");
  978. }
  979. static void
  980. trace_puts(const char *s)
  981. {
  982. if (debug != 1)
  983. return;
  984. fputs(s, tracefile);
  985. }
  986. static void
  987. trace_puts_quoted(char *s)
  988. {
  989. char *p;
  990. char c;
  991. if (debug != 1)
  992. return;
  993. putc('"', tracefile);
  994. for (p = s; *p; p++) {
  995. switch ((unsigned char)*p) {
  996. case '\n': c = 'n'; goto backslash;
  997. case '\t': c = 't'; goto backslash;
  998. case '\r': c = 'r'; goto backslash;
  999. case '\"': c = '\"'; goto backslash;
  1000. case '\\': c = '\\'; goto backslash;
  1001. case CTLESC: c = 'e'; goto backslash;
  1002. case CTLVAR: c = 'v'; goto backslash;
  1003. case CTLBACKQ: c = 'q'; goto backslash;
  1004. #if BASH_PROCESS_SUBST
  1005. case CTLTOPROC: c = 'p'; goto backslash;
  1006. case CTLFROMPROC: c = 'P'; goto backslash;
  1007. #endif
  1008. backslash:
  1009. putc('\\', tracefile);
  1010. putc(c, tracefile);
  1011. break;
  1012. default:
  1013. if (*p >= ' ' && *p <= '~')
  1014. putc(*p, tracefile);
  1015. else {
  1016. putc('\\', tracefile);
  1017. putc((*p >> 6) & 03, tracefile);
  1018. putc((*p >> 3) & 07, tracefile);
  1019. putc(*p & 07, tracefile);
  1020. }
  1021. break;
  1022. }
  1023. }
  1024. putc('"', tracefile);
  1025. }
  1026. static void
  1027. trace_puts_args(char **ap)
  1028. {
  1029. if (debug != 1)
  1030. return;
  1031. if (!*ap)
  1032. return;
  1033. while (1) {
  1034. trace_puts_quoted(*ap);
  1035. if (!*++ap) {
  1036. putc('\n', tracefile);
  1037. break;
  1038. }
  1039. putc(' ', tracefile);
  1040. }
  1041. }
  1042. static void
  1043. opentrace(void)
  1044. {
  1045. char s[100];
  1046. #ifdef O_APPEND
  1047. int flags;
  1048. #endif
  1049. if (debug != 1) {
  1050. if (tracefile)
  1051. fflush(tracefile);
  1052. /* leave open because libedit might be using it */
  1053. return;
  1054. }
  1055. strcpy(s, "./trace");
  1056. if (tracefile) {
  1057. if (!freopen(s, "a", tracefile)) {
  1058. fprintf(stderr, "Can't re-open %s\n", s);
  1059. debug = 0;
  1060. return;
  1061. }
  1062. } else {
  1063. tracefile = fopen(s, "a");
  1064. if (tracefile == NULL) {
  1065. fprintf(stderr, "Can't open %s\n", s);
  1066. debug = 0;
  1067. return;
  1068. }
  1069. }
  1070. #ifdef O_APPEND
  1071. flags = fcntl(fileno(tracefile), F_GETFL);
  1072. if (flags >= 0)
  1073. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1074. #endif
  1075. setlinebuf(tracefile);
  1076. fputs("\nTracing started.\n", tracefile);
  1077. }
  1078. static void
  1079. indent(int amount, char *pfx, FILE *fp)
  1080. {
  1081. int i;
  1082. for (i = 0; i < amount; i++) {
  1083. if (pfx && i == amount - 1)
  1084. fputs(pfx, fp);
  1085. putc('\t', fp);
  1086. }
  1087. }
  1088. /* little circular references here... */
  1089. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1090. static void
  1091. sharg(union node *arg, FILE *fp)
  1092. {
  1093. char *p;
  1094. struct nodelist *bqlist;
  1095. unsigned char subtype;
  1096. if (arg->type != NARG) {
  1097. out1fmt("<node type %d>\n", arg->type);
  1098. abort();
  1099. }
  1100. bqlist = arg->narg.backquote;
  1101. for (p = arg->narg.text; *p; p++) {
  1102. switch ((unsigned char)*p) {
  1103. case CTLESC:
  1104. p++;
  1105. putc(*p, fp);
  1106. break;
  1107. case CTLVAR:
  1108. putc('$', fp);
  1109. putc('{', fp);
  1110. subtype = *++p;
  1111. if (subtype == VSLENGTH)
  1112. putc('#', fp);
  1113. while (*p != '=') {
  1114. putc(*p, fp);
  1115. p++;
  1116. }
  1117. if (subtype & VSNUL)
  1118. putc(':', fp);
  1119. switch (subtype & VSTYPE) {
  1120. case VSNORMAL:
  1121. putc('}', fp);
  1122. break;
  1123. case VSMINUS:
  1124. putc('-', fp);
  1125. break;
  1126. case VSPLUS:
  1127. putc('+', fp);
  1128. break;
  1129. case VSQUESTION:
  1130. putc('?', fp);
  1131. break;
  1132. case VSASSIGN:
  1133. putc('=', fp);
  1134. break;
  1135. case VSTRIMLEFT:
  1136. putc('#', fp);
  1137. break;
  1138. case VSTRIMLEFTMAX:
  1139. putc('#', fp);
  1140. putc('#', fp);
  1141. break;
  1142. case VSTRIMRIGHT:
  1143. putc('%', fp);
  1144. break;
  1145. case VSTRIMRIGHTMAX:
  1146. putc('%', fp);
  1147. putc('%', fp);
  1148. break;
  1149. case VSLENGTH:
  1150. break;
  1151. default:
  1152. out1fmt("<subtype %d>", subtype);
  1153. }
  1154. break;
  1155. case CTLENDVAR:
  1156. putc('}', fp);
  1157. break;
  1158. #if BASH_PROCESS_SUBST
  1159. case CTLTOPROC:
  1160. putc('>', fp);
  1161. goto backq;
  1162. case CTLFROMPROC:
  1163. putc('<', fp);
  1164. goto backq;
  1165. #endif
  1166. case CTLBACKQ:
  1167. putc('$', fp);
  1168. IF_BASH_PROCESS_SUBST(backq:)
  1169. putc('(', fp);
  1170. shtree(bqlist->n, -1, NULL, fp);
  1171. putc(')', fp);
  1172. break;
  1173. default:
  1174. putc(*p, fp);
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. static void
  1180. shcmd(union node *cmd, FILE *fp)
  1181. {
  1182. union node *np;
  1183. int first;
  1184. const char *s;
  1185. int dftfd;
  1186. first = 1;
  1187. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1188. if (!first)
  1189. putc(' ', fp);
  1190. sharg(np, fp);
  1191. first = 0;
  1192. }
  1193. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1194. if (!first)
  1195. putc(' ', fp);
  1196. dftfd = 0;
  1197. switch (np->nfile.type) {
  1198. case NTO: s = ">>"+1; dftfd = 1; break;
  1199. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1200. case NAPPEND: s = ">>"; dftfd = 1; break;
  1201. #if BASH_REDIR_OUTPUT
  1202. case NTO2:
  1203. #endif
  1204. case NTOFD: s = ">&"; dftfd = 1; break;
  1205. case NFROM: s = "<"; break;
  1206. case NFROMFD: s = "<&"; break;
  1207. case NFROMTO: s = "<>"; break;
  1208. default: s = "*error*"; break;
  1209. }
  1210. if (np->nfile.fd != dftfd)
  1211. fprintf(fp, "%d", np->nfile.fd);
  1212. fputs(s, fp);
  1213. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1214. fprintf(fp, "%d", np->ndup.dupfd);
  1215. } else {
  1216. sharg(np->nfile.fname, fp);
  1217. }
  1218. first = 0;
  1219. }
  1220. }
  1221. static void
  1222. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1223. {
  1224. struct nodelist *lp;
  1225. const char *s;
  1226. if (n == NULL)
  1227. return;
  1228. indent(ind, pfx, fp);
  1229. if (n == NODE_EOF) {
  1230. fputs("<EOF>", fp);
  1231. return;
  1232. }
  1233. switch (n->type) {
  1234. case NSEMI:
  1235. s = "; ";
  1236. goto binop;
  1237. case NAND:
  1238. s = " && ";
  1239. goto binop;
  1240. case NOR:
  1241. s = " || ";
  1242. binop:
  1243. shtree(n->nbinary.ch1, ind, NULL, fp);
  1244. /* if (ind < 0) */
  1245. fputs(s, fp);
  1246. shtree(n->nbinary.ch2, ind, NULL, fp);
  1247. break;
  1248. case NCMD:
  1249. shcmd(n, fp);
  1250. if (ind >= 0)
  1251. putc('\n', fp);
  1252. break;
  1253. case NPIPE:
  1254. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1255. shtree(lp->n, 0, NULL, fp);
  1256. if (lp->next)
  1257. fputs(" | ", fp);
  1258. }
  1259. if (n->npipe.pipe_backgnd)
  1260. fputs(" &", fp);
  1261. if (ind >= 0)
  1262. putc('\n', fp);
  1263. break;
  1264. default:
  1265. fprintf(fp, "<node type %d>", n->type);
  1266. if (ind >= 0)
  1267. putc('\n', fp);
  1268. break;
  1269. }
  1270. }
  1271. static void
  1272. showtree(union node *n)
  1273. {
  1274. trace_puts("showtree called\n");
  1275. shtree(n, 1, NULL, stderr);
  1276. }
  1277. #endif /* DEBUG */
  1278. /* ============ Message printing */
  1279. static void
  1280. ash_vmsg(const char *msg, va_list ap)
  1281. {
  1282. fprintf(stderr, "%s: ", arg0);
  1283. if (commandname) {
  1284. if (strcmp(arg0, commandname))
  1285. fprintf(stderr, "%s: ", commandname);
  1286. if (!iflag || g_parsefile->pf_fd > 0)
  1287. fprintf(stderr, "line %d: ", errlinno);
  1288. }
  1289. vfprintf(stderr, msg, ap);
  1290. newline_and_flush(stderr);
  1291. }
  1292. /*
  1293. * Exverror is called to raise the error exception. If the second argument
  1294. * is not NULL then error prints an error message using printf style
  1295. * formatting. It then raises the error exception.
  1296. */
  1297. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1298. static void
  1299. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1300. {
  1301. #if DEBUG
  1302. if (msg) {
  1303. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1304. TRACEV((msg, ap));
  1305. } else
  1306. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1307. if (msg)
  1308. #endif
  1309. ash_vmsg(msg, ap);
  1310. flush_stdout_stderr();
  1311. raise_exception(cond);
  1312. /* NOTREACHED */
  1313. }
  1314. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1315. static void
  1316. ash_msg_and_raise_error(const char *msg, ...)
  1317. {
  1318. va_list ap;
  1319. exitstatus = 2;
  1320. va_start(ap, msg);
  1321. ash_vmsg_and_raise(EXERROR, msg, ap);
  1322. /* NOTREACHED */
  1323. va_end(ap);
  1324. }
  1325. /*
  1326. * 'fmt' must be a string literal.
  1327. */
  1328. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1329. static void raise_error_syntax(const char *) NORETURN;
  1330. static void
  1331. raise_error_syntax(const char *msg)
  1332. {
  1333. errlinno = g_parsefile->linno;
  1334. ash_msg_and_raise_error("syntax error: %s", msg);
  1335. /* NOTREACHED */
  1336. }
  1337. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1338. static void
  1339. ash_msg_and_raise(int cond, const char *msg, ...)
  1340. {
  1341. va_list ap;
  1342. va_start(ap, msg);
  1343. ash_vmsg_and_raise(cond, msg, ap);
  1344. /* NOTREACHED */
  1345. va_end(ap);
  1346. }
  1347. /*
  1348. * error/warning routines for external builtins
  1349. */
  1350. static void
  1351. ash_msg(const char *fmt, ...)
  1352. {
  1353. va_list ap;
  1354. va_start(ap, fmt);
  1355. ash_vmsg(fmt, ap);
  1356. va_end(ap);
  1357. }
  1358. /*
  1359. * Return a string describing an error. The returned string may be a
  1360. * pointer to a static buffer that will be overwritten on the next call.
  1361. * Action describes the operation that got the error.
  1362. */
  1363. static const char *
  1364. errmsg(int e, const char *em)
  1365. {
  1366. if (e == ENOENT || e == ENOTDIR) {
  1367. return em;
  1368. }
  1369. return strerror(e);
  1370. }
  1371. /* ============ Memory allocation */
  1372. #if 0
  1373. /* I consider these wrappers nearly useless:
  1374. * ok, they return you to nearest exception handler, but
  1375. * how much memory do you leak in the process, making
  1376. * memory starvation worse?
  1377. */
  1378. static void *
  1379. ckrealloc(void * p, size_t nbytes)
  1380. {
  1381. p = realloc(p, nbytes);
  1382. if (!p)
  1383. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1384. return p;
  1385. }
  1386. static void *
  1387. ckmalloc(size_t nbytes)
  1388. {
  1389. return ckrealloc(NULL, nbytes);
  1390. }
  1391. static void *
  1392. ckzalloc(size_t nbytes)
  1393. {
  1394. return memset(ckmalloc(nbytes), 0, nbytes);
  1395. }
  1396. static char *
  1397. ckstrdup(const char *s)
  1398. {
  1399. char *p = strdup(s);
  1400. if (!p)
  1401. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1402. return p;
  1403. }
  1404. #else
  1405. /* Using bbox equivalents. They exit if out of memory */
  1406. # define ckrealloc xrealloc
  1407. # define ckmalloc xmalloc
  1408. # define ckzalloc xzalloc
  1409. # define ckstrdup xstrdup
  1410. #endif
  1411. /*
  1412. * It appears that grabstackstr() will barf with such alignments
  1413. * because stalloc() will return a string allocated in a new stackblock.
  1414. */
  1415. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1416. enum {
  1417. /* Most machines require the value returned from malloc to be aligned
  1418. * in some way. The following macro will get this right
  1419. * on many machines. */
  1420. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1421. /* Minimum size of a block */
  1422. MINSIZE = SHELL_ALIGN(504),
  1423. };
  1424. struct stack_block {
  1425. struct stack_block *prev;
  1426. char space[MINSIZE];
  1427. };
  1428. struct stackmark {
  1429. struct stack_block *stackp;
  1430. char *stacknxt;
  1431. size_t stacknleft;
  1432. };
  1433. struct globals_memstack {
  1434. struct stack_block *g_stackp; // = &stackbase;
  1435. char *g_stacknxt; // = stackbase.space;
  1436. char *sstrend; // = stackbase.space + MINSIZE;
  1437. size_t g_stacknleft; // = MINSIZE;
  1438. struct stack_block stackbase;
  1439. };
  1440. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1441. #define G_memstack (*ash_ptr_to_globals_memstack)
  1442. #define g_stackp (G_memstack.g_stackp )
  1443. #define g_stacknxt (G_memstack.g_stacknxt )
  1444. #define sstrend (G_memstack.sstrend )
  1445. #define g_stacknleft (G_memstack.g_stacknleft)
  1446. #define stackbase (G_memstack.stackbase )
  1447. #define INIT_G_memstack() do { \
  1448. XZALLOC_CONST_PTR(&ash_ptr_to_globals_memstack, sizeof(G_memstack)); \
  1449. g_stackp = &stackbase; \
  1450. g_stacknxt = stackbase.space; \
  1451. g_stacknleft = MINSIZE; \
  1452. sstrend = stackbase.space + MINSIZE; \
  1453. } while (0)
  1454. #define stackblock() ((void *)g_stacknxt)
  1455. #define stackblocksize() g_stacknleft
  1456. /*
  1457. * Parse trees for commands are allocated in lifo order, so we use a stack
  1458. * to make this more efficient, and also to avoid all sorts of exception
  1459. * handling code to handle interrupts in the middle of a parse.
  1460. *
  1461. * The size 504 was chosen because the Ultrix malloc handles that size
  1462. * well.
  1463. */
  1464. static void *
  1465. stalloc(size_t nbytes)
  1466. {
  1467. char *p;
  1468. size_t aligned;
  1469. aligned = SHELL_ALIGN(nbytes);
  1470. if (aligned > g_stacknleft) {
  1471. size_t len;
  1472. size_t blocksize;
  1473. struct stack_block *sp;
  1474. blocksize = aligned;
  1475. if (blocksize < MINSIZE)
  1476. blocksize = MINSIZE;
  1477. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1478. if (len < blocksize)
  1479. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1480. INT_OFF;
  1481. sp = ckmalloc(len);
  1482. sp->prev = g_stackp;
  1483. g_stacknxt = sp->space;
  1484. g_stacknleft = blocksize;
  1485. sstrend = g_stacknxt + blocksize;
  1486. g_stackp = sp;
  1487. INT_ON;
  1488. }
  1489. p = g_stacknxt;
  1490. g_stacknxt += aligned;
  1491. g_stacknleft -= aligned;
  1492. return p;
  1493. }
  1494. static void *
  1495. stzalloc(size_t nbytes)
  1496. {
  1497. return memset(stalloc(nbytes), 0, nbytes);
  1498. }
  1499. static void
  1500. stunalloc(void *p)
  1501. {
  1502. #if DEBUG
  1503. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1504. write(STDERR_FILENO, "stunalloc\n", 10);
  1505. abort();
  1506. }
  1507. #endif
  1508. g_stacknleft += g_stacknxt - (char *)p;
  1509. g_stacknxt = p;
  1510. }
  1511. /*
  1512. * Like strdup but works with the ash stack.
  1513. */
  1514. static char *
  1515. sstrdup(const char *p)
  1516. {
  1517. size_t len = strlen(p) + 1;
  1518. return memcpy(stalloc(len), p, len);
  1519. }
  1520. static ALWAYS_INLINE void
  1521. grabstackblock(size_t len)
  1522. {
  1523. stalloc(len);
  1524. }
  1525. static void
  1526. pushstackmark(struct stackmark *mark, size_t len)
  1527. {
  1528. mark->stackp = g_stackp;
  1529. mark->stacknxt = g_stacknxt;
  1530. mark->stacknleft = g_stacknleft;
  1531. grabstackblock(len);
  1532. }
  1533. static void
  1534. setstackmark(struct stackmark *mark)
  1535. {
  1536. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1537. }
  1538. static void
  1539. popstackmark(struct stackmark *mark)
  1540. {
  1541. struct stack_block *sp;
  1542. if (!mark->stackp)
  1543. return;
  1544. INT_OFF;
  1545. while (g_stackp != mark->stackp) {
  1546. sp = g_stackp;
  1547. g_stackp = sp->prev;
  1548. free(sp);
  1549. }
  1550. g_stacknxt = mark->stacknxt;
  1551. g_stacknleft = mark->stacknleft;
  1552. sstrend = mark->stacknxt + mark->stacknleft;
  1553. INT_ON;
  1554. }
  1555. /*
  1556. * When the parser reads in a string, it wants to stick the string on the
  1557. * stack and only adjust the stack pointer when it knows how big the
  1558. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1559. * of space on top of the stack and stackblocklen returns the length of
  1560. * this block. Growstackblock will grow this space by at least one byte,
  1561. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1562. * part of the block that has been used.
  1563. */
  1564. static void
  1565. growstackblock(size_t min)
  1566. {
  1567. size_t newlen;
  1568. newlen = g_stacknleft * 2;
  1569. if (newlen < g_stacknleft)
  1570. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1571. min = SHELL_ALIGN(min | 128);
  1572. if (newlen < min)
  1573. newlen += min;
  1574. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1575. struct stack_block *sp;
  1576. struct stack_block *prevstackp;
  1577. size_t grosslen;
  1578. INT_OFF;
  1579. sp = g_stackp;
  1580. prevstackp = sp->prev;
  1581. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1582. sp = ckrealloc(sp, grosslen);
  1583. sp->prev = prevstackp;
  1584. g_stackp = sp;
  1585. g_stacknxt = sp->space;
  1586. g_stacknleft = newlen;
  1587. sstrend = sp->space + newlen;
  1588. INT_ON;
  1589. } else {
  1590. char *oldspace = g_stacknxt;
  1591. size_t oldlen = g_stacknleft;
  1592. char *p = stalloc(newlen);
  1593. /* free the space we just allocated */
  1594. g_stacknxt = memcpy(p, oldspace, oldlen);
  1595. g_stacknleft += newlen;
  1596. }
  1597. }
  1598. /*
  1599. * The following routines are somewhat easier to use than the above.
  1600. * The user declares a variable of type STACKSTR, which may be declared
  1601. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1602. * the user uses the macro STPUTC to add characters to the string. In
  1603. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1604. * grown as necessary. When the user is done, she can just leave the
  1605. * string there and refer to it using stackblock(). Or she can allocate
  1606. * the space for it using grabstackstr(). If it is necessary to allow
  1607. * someone else to use the stack temporarily and then continue to grow
  1608. * the string, the user should use grabstack to allocate the space, and
  1609. * then call ungrabstr(p) to return to the previous mode of operation.
  1610. *
  1611. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1612. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1613. * is space for at least one character.
  1614. */
  1615. static void *
  1616. growstackstr(void)
  1617. {
  1618. size_t len = stackblocksize();
  1619. growstackblock(0);
  1620. return (char *)stackblock() + len;
  1621. }
  1622. static char *
  1623. growstackto(size_t len)
  1624. {
  1625. if (stackblocksize() < len)
  1626. growstackblock(len);
  1627. return stackblock();
  1628. }
  1629. /*
  1630. * Called from CHECKSTRSPACE.
  1631. */
  1632. static char *
  1633. makestrspace(size_t newlen, char *p)
  1634. {
  1635. size_t len = p - g_stacknxt;
  1636. return growstackto(len + newlen) + len;
  1637. }
  1638. static char *
  1639. stnputs(const char *s, size_t n, char *p)
  1640. {
  1641. p = makestrspace(n, p);
  1642. p = (char *)mempcpy(p, s, n);
  1643. return p;
  1644. }
  1645. static char *
  1646. stack_putstr(const char *s, char *p)
  1647. {
  1648. return stnputs(s, strlen(s), p);
  1649. }
  1650. static char *
  1651. _STPUTC(int c, char *p)
  1652. {
  1653. if (p == sstrend)
  1654. p = growstackstr();
  1655. *p++ = c;
  1656. return p;
  1657. }
  1658. #define STARTSTACKSTR(p) ((p) = stackblock())
  1659. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1660. #define CHECKSTRSPACE(n, p) do { \
  1661. char *q = (p); \
  1662. size_t l = (n); \
  1663. size_t m = sstrend - q; \
  1664. if (l > m) \
  1665. (p) = makestrspace(l, q); \
  1666. } while (0)
  1667. #define USTPUTC(c, p) (*(p)++ = (c))
  1668. #define STACKSTRNUL(p) do { \
  1669. if ((p) == sstrend) \
  1670. (p) = growstackstr(); \
  1671. *(p) = '\0'; \
  1672. } while (0)
  1673. #define STUNPUTC(p) (--(p))
  1674. #define STTOPC(p) ((p)[-1])
  1675. #define STADJUST(amount, p) ((p) += (amount))
  1676. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1677. #define ungrabstackstr(s, p) stunalloc(s)
  1678. #define stackstrend() ((void *)sstrend)
  1679. /* ============ String helpers */
  1680. /*
  1681. * prefix -- see if pfx is a prefix of string.
  1682. */
  1683. static ALWAYS_INLINE char *
  1684. prefix(const char *string, const char *pfx)
  1685. {
  1686. return is_prefixed_with(string, pfx);
  1687. #if 0 /* dash implementation: */
  1688. while (*pfx) {
  1689. if (*pfx++ != *string++)
  1690. return NULL;
  1691. }
  1692. return (char *) string;
  1693. #endif
  1694. }
  1695. /*
  1696. * Check for a valid number. This should be elsewhere.
  1697. */
  1698. static int
  1699. is_number(const char *p)
  1700. {
  1701. do {
  1702. if (!isdigit(*p))
  1703. return 0;
  1704. } while (*++p != '\0');
  1705. return 1;
  1706. }
  1707. /*
  1708. * Convert a string of digits to an integer, printing an error message on
  1709. * failure.
  1710. */
  1711. static int
  1712. number(const char *s)
  1713. {
  1714. if (!is_number(s))
  1715. ash_msg_and_raise_error(msg_illnum, s);
  1716. return atoi(s);
  1717. }
  1718. /*
  1719. * Produce a single quoted string suitable as input to the shell.
  1720. * The return string is allocated on the stack.
  1721. */
  1722. static char *
  1723. single_quote(const char *s)
  1724. {
  1725. char *p;
  1726. STARTSTACKSTR(p);
  1727. do {
  1728. char *q;
  1729. size_t len;
  1730. len = strchrnul(s, '\'') - s;
  1731. q = p = makestrspace(len + 3, p);
  1732. *q++ = '\'';
  1733. q = (char *)mempcpy(q, s, len);
  1734. *q++ = '\'';
  1735. s += len;
  1736. STADJUST(q - p, p);
  1737. if (*s != '\'')
  1738. break;
  1739. len = 0;
  1740. do len++; while (*++s == '\'');
  1741. q = p = makestrspace(len + 3, p);
  1742. *q++ = '"';
  1743. q = (char *)mempcpy(q, s - len, len);
  1744. *q++ = '"';
  1745. STADJUST(q - p, p);
  1746. } while (*s);
  1747. USTPUTC('\0', p);
  1748. return stackblock();
  1749. }
  1750. /*
  1751. * Produce a possibly single quoted string suitable as input to the shell.
  1752. * If quoting was done, the return string is allocated on the stack,
  1753. * otherwise a pointer to the original string is returned.
  1754. */
  1755. static const char *
  1756. maybe_single_quote(const char *s)
  1757. {
  1758. const char *p = s;
  1759. while (*p) {
  1760. /* Assuming ACSII */
  1761. /* quote ctrl_chars space !"#$%&'()* */
  1762. if (*p < '+')
  1763. goto need_quoting;
  1764. /* quote ;<=>? */
  1765. if (*p >= ';' && *p <= '?')
  1766. goto need_quoting;
  1767. /* quote `[\ */
  1768. if (*p == '`')
  1769. goto need_quoting;
  1770. if (*p == '[')
  1771. goto need_quoting;
  1772. if (*p == '\\')
  1773. goto need_quoting;
  1774. /* quote {|}~ DEL and high bytes */
  1775. if (*p > 'z')
  1776. goto need_quoting;
  1777. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1778. /* TODO: maybe avoid quoting % */
  1779. p++;
  1780. }
  1781. return s;
  1782. need_quoting:
  1783. return single_quote(s);
  1784. }
  1785. /* ============ nextopt */
  1786. static char **argptr; /* argument list for builtin commands */
  1787. static char *optionarg; /* set by nextopt (like getopt) */
  1788. static char *optptr; /* used by nextopt */
  1789. /*
  1790. * XXX - should get rid of. Have all builtins use getopt(3).
  1791. * The library getopt must have the BSD extension static variable
  1792. * "optreset", otherwise it can't be used within the shell safely.
  1793. *
  1794. * Standard option processing (a la getopt) for builtin routines.
  1795. * The only argument that is passed to nextopt is the option string;
  1796. * the other arguments are unnecessary. It returns the character,
  1797. * or '\0' on end of input.
  1798. */
  1799. static int
  1800. nextopt(const char *optstring)
  1801. {
  1802. char *p;
  1803. const char *q;
  1804. char c;
  1805. p = optptr;
  1806. if (p == NULL || *p == '\0') {
  1807. /* We ate entire "-param", take next one */
  1808. p = *argptr;
  1809. if (p == NULL)
  1810. return '\0';
  1811. if (*p != '-')
  1812. return '\0';
  1813. if (*++p == '\0') /* just "-" ? */
  1814. return '\0';
  1815. argptr++;
  1816. if (LONE_DASH(p)) /* "--" ? */
  1817. return '\0';
  1818. /* p => next "-param" */
  1819. }
  1820. /* p => some option char in the middle of a "-param" */
  1821. c = *p++;
  1822. for (q = optstring; *q != c;) {
  1823. if (*q == '\0')
  1824. ash_msg_and_raise_error("illegal option -%c", c);
  1825. if (*++q == ':')
  1826. q++;
  1827. }
  1828. if (*++q == ':') {
  1829. if (*p == '\0') {
  1830. p = *argptr++;
  1831. if (p == NULL)
  1832. ash_msg_and_raise_error("no arg for -%c option", c);
  1833. }
  1834. optionarg = p;
  1835. p = NULL;
  1836. }
  1837. optptr = p;
  1838. return c;
  1839. }
  1840. /* ============ Shell variables */
  1841. struct shparam {
  1842. int nparam; /* # of positional parameters (without $0) */
  1843. #if ENABLE_ASH_GETOPTS
  1844. int optind; /* next parameter to be processed by getopts */
  1845. int optoff; /* used by getopts */
  1846. #endif
  1847. unsigned char malloced; /* if parameter list dynamically allocated */
  1848. char **p; /* parameter list */
  1849. };
  1850. /*
  1851. * Free the list of positional parameters.
  1852. */
  1853. static void
  1854. freeparam(volatile struct shparam *param)
  1855. {
  1856. if (param->malloced) {
  1857. char **ap, **ap1;
  1858. ap = ap1 = param->p;
  1859. while (*ap)
  1860. free(*ap++);
  1861. free(ap1);
  1862. }
  1863. }
  1864. #if ENABLE_ASH_GETOPTS
  1865. static void FAST_FUNC getoptsreset(const char *value);
  1866. #endif
  1867. struct var {
  1868. struct var *next; /* next entry in hash list */
  1869. int flags; /* flags are defined above */
  1870. const char *var_text; /* name=value */
  1871. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1872. /* the variable gets set/unset */
  1873. };
  1874. struct localvar {
  1875. struct localvar *next; /* next local variable in list */
  1876. struct var *vp; /* the variable that was made local */
  1877. int flags; /* saved flags */
  1878. const char *text; /* saved text */
  1879. };
  1880. /* flags */
  1881. #define VEXPORT 0x01 /* variable is exported */
  1882. #define VREADONLY 0x02 /* variable cannot be modified */
  1883. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1884. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1885. #define VSTACK 0x10 /* text is allocated on the stack */
  1886. #define VUNSET 0x20 /* the variable is not set */
  1887. #define VNOFUNC 0x40 /* don't call the callback function */
  1888. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1889. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1890. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  1891. # define VDYNAMIC 0x200 /* dynamic variable */
  1892. #else
  1893. # define VDYNAMIC 0
  1894. #endif
  1895. /* Need to be before varinit_data[] */
  1896. #if ENABLE_LOCALE_SUPPORT
  1897. static void FAST_FUNC
  1898. change_lc_all(const char *value)
  1899. {
  1900. if (value && *value != '\0')
  1901. setlocale(LC_ALL, value);
  1902. }
  1903. static void FAST_FUNC
  1904. change_lc_ctype(const char *value)
  1905. {
  1906. if (value && *value != '\0')
  1907. setlocale(LC_CTYPE, value);
  1908. }
  1909. #endif
  1910. #if ENABLE_ASH_MAIL
  1911. static void changemail(const char *var_value) FAST_FUNC;
  1912. #endif
  1913. static void changepath(const char *) FAST_FUNC;
  1914. #if ENABLE_ASH_RANDOM_SUPPORT
  1915. static void change_random(const char *) FAST_FUNC;
  1916. #endif
  1917. #if BASH_EPOCH_VARS
  1918. static void change_seconds(const char *) FAST_FUNC;
  1919. static void change_realtime(const char *) FAST_FUNC;
  1920. #endif
  1921. static const struct {
  1922. int flags;
  1923. const char *var_text;
  1924. void (*var_func)(const char *) FAST_FUNC;
  1925. } varinit_data[] ALIGN_PTR = {
  1926. /*
  1927. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1928. * some environment strings may be constant.
  1929. */
  1930. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1931. #if ENABLE_ASH_MAIL
  1932. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1933. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1934. #endif
  1935. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1936. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1937. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1938. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1939. #if ENABLE_ASH_GETOPTS
  1940. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1941. #endif
  1942. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1943. { VSTRFIXED|VTEXTFIXED , NULL /* inited to funcnamevar */, NULL },
  1944. #if ENABLE_ASH_RANDOM_SUPPORT
  1945. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1946. #endif
  1947. #if BASH_EPOCH_VARS
  1948. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1949. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1950. #endif
  1951. #if ENABLE_LOCALE_SUPPORT
  1952. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1953. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1954. #endif
  1955. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1956. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1957. #endif
  1958. };
  1959. struct redirtab;
  1960. struct globals_var {
  1961. struct shparam shellparam; /* $@ current positional parameters */
  1962. struct redirtab *redirlist;
  1963. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1964. struct var *vartab[VTABSIZE];
  1965. struct var varinit[ARRAY_SIZE(varinit_data)];
  1966. int lineno;
  1967. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1968. char funcnamevar[sizeof("FUNCNAME=") + 64];
  1969. char *funcname;
  1970. unsigned trap_depth;
  1971. bool in_trap_ERR; /* ERR cannot recurse, no need to be a counter */
  1972. };
  1973. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1974. #define G_var (*ash_ptr_to_globals_var)
  1975. #define shellparam (G_var.shellparam )
  1976. //#define redirlist (G_var.redirlist )
  1977. #define preverrout_fd (G_var.preverrout_fd)
  1978. #define vartab (G_var.vartab )
  1979. #define varinit (G_var.varinit )
  1980. #define lineno (G_var.lineno )
  1981. #define linenovar (G_var.linenovar )
  1982. #define funcnamevar (G_var.funcnamevar )
  1983. #define funcname (G_var.funcname )
  1984. #define trap_depth (G_var.trap_depth )
  1985. #define in_trap_ERR (G_var.in_trap_ERR )
  1986. #define vifs varinit[0]
  1987. #if ENABLE_ASH_MAIL
  1988. # define vmail varinit[1]
  1989. # define vmpath varinit[2]
  1990. #endif
  1991. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1992. #define vpath varinit[VAR_OFFSET1 + 1]
  1993. #define vps1 varinit[VAR_OFFSET1 + 2]
  1994. #define vps2 varinit[VAR_OFFSET1 + 3]
  1995. #define vps4 varinit[VAR_OFFSET1 + 4]
  1996. #if ENABLE_ASH_GETOPTS
  1997. # define voptind varinit[VAR_OFFSET1 + 5]
  1998. #endif
  1999. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  2000. #define vlineno varinit[VAR_OFFSET2 + 5]
  2001. #define vfuncname varinit[VAR_OFFSET2 + 6]
  2002. #if ENABLE_ASH_RANDOM_SUPPORT
  2003. # define vrandom varinit[VAR_OFFSET2 + 7]
  2004. #endif
  2005. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  2006. #if BASH_EPOCH_VARS
  2007. # define vepochs varinit[VAR_OFFSET3 + 7]
  2008. # define vepochr varinit[VAR_OFFSET3 + 8]
  2009. #endif
  2010. #define INIT_G_var() do { \
  2011. unsigned i; \
  2012. XZALLOC_CONST_PTR(&ash_ptr_to_globals_var, sizeof(G_var)); \
  2013. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  2014. varinit[i].flags = varinit_data[i].flags; \
  2015. varinit[i].var_text = varinit_data[i].var_text; \
  2016. varinit[i].var_func = varinit_data[i].var_func; \
  2017. } \
  2018. strcpy(linenovar, "LINENO="); \
  2019. vlineno.var_text = linenovar; \
  2020. strcpy(funcnamevar, "FUNCNAME="); \
  2021. vfuncname.var_text = funcnamevar; \
  2022. } while (0)
  2023. /*
  2024. * The following macros access the values of the above variables.
  2025. * They have to skip over the name. They return the null string
  2026. * for unset variables.
  2027. */
  2028. #define ifsval() (vifs.var_text + 4)
  2029. #define ifsset() ((vifs.flags & VUNSET) == 0)
  2030. #if ENABLE_ASH_MAIL
  2031. # define mailval() (vmail.var_text + 5)
  2032. # define mpathval() (vmpath.var_text + 9)
  2033. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  2034. #endif
  2035. #define pathval() (vpath.var_text + 5)
  2036. #define ps1val() (vps1.var_text + 4)
  2037. #define ps2val() (vps2.var_text + 4)
  2038. #define ps4val() (vps4.var_text + 4)
  2039. #if ENABLE_ASH_GETOPTS
  2040. # define optindval() (voptind.var_text + 7)
  2041. #endif
  2042. #if ENABLE_ASH_GETOPTS
  2043. static void FAST_FUNC
  2044. getoptsreset(const char *value)
  2045. {
  2046. shellparam.optind = 1;
  2047. if (is_number(value))
  2048. shellparam.optind = number(value) ?: 1;
  2049. shellparam.optoff = -1;
  2050. }
  2051. #endif
  2052. /*
  2053. * Find the appropriate entry in the hash table from the name.
  2054. */
  2055. static struct var **
  2056. hashvar(const char *p)
  2057. {
  2058. unsigned hashval;
  2059. hashval = ((unsigned char) *p) << 4;
  2060. while (*p && *p != '=')
  2061. hashval += (unsigned char) *p++;
  2062. return &vartab[hashval % VTABSIZE];
  2063. }
  2064. static int
  2065. vpcmp(const void *a, const void *b)
  2066. {
  2067. return varcmp(*(const char **)a, *(const char **)b);
  2068. }
  2069. /*
  2070. * This routine initializes the builtin variables.
  2071. */
  2072. static void
  2073. initvar(void)
  2074. {
  2075. struct var *vp;
  2076. struct var *end;
  2077. struct var **vpp;
  2078. /*
  2079. * PS1 depends on uid
  2080. */
  2081. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2082. vps1.var_text = "PS1=\\w \\$ ";
  2083. #else
  2084. if (!geteuid())
  2085. vps1.var_text = "PS1=# ";
  2086. #endif
  2087. vp = varinit;
  2088. end = vp + ARRAY_SIZE(varinit);
  2089. do {
  2090. vpp = hashvar(vp->var_text);
  2091. vp->next = *vpp;
  2092. *vpp = vp;
  2093. } while (++vp < end);
  2094. }
  2095. static struct var **
  2096. findvar(struct var **vpp, const char *name)
  2097. {
  2098. for (; *vpp; vpp = &(*vpp)->next) {
  2099. if (varcmp((*vpp)->var_text, name) == 0) {
  2100. break;
  2101. }
  2102. }
  2103. return vpp;
  2104. }
  2105. /*
  2106. * Find the value of a variable. Returns NULL if not set.
  2107. */
  2108. static const char* FAST_FUNC
  2109. lookupvar(const char *name)
  2110. {
  2111. struct var *v;
  2112. v = *findvar(hashvar(name), name);
  2113. if (v) {
  2114. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2115. /*
  2116. * Dynamic variables are implemented roughly the same way they are
  2117. * in bash. Namely, they're "special" so long as they aren't unset.
  2118. * As soon as they're unset, they're no longer dynamic, and dynamic
  2119. * lookup will no longer happen at that point. -- PFM.
  2120. */
  2121. if (v->flags & VDYNAMIC)
  2122. v->var_func(NULL);
  2123. #endif
  2124. if (!(v->flags & VUNSET)) {
  2125. if (v->var_text == linenovar) {
  2126. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2127. } else
  2128. if (v->var_text == funcnamevar) {
  2129. safe_strncpy(funcnamevar+9, funcname ? funcname : "", sizeof(funcnamevar)-9);
  2130. }
  2131. return var_end(v->var_text);
  2132. }
  2133. }
  2134. return NULL;
  2135. }
  2136. #if ENABLE_UNICODE_SUPPORT
  2137. static void
  2138. reinit_unicode_for_ash(void)
  2139. {
  2140. /* Unicode support should be activated even if LANG is set
  2141. * _during_ shell execution, not only if it was set when
  2142. * shell was started. Therefore, re-check LANG every time:
  2143. */
  2144. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2145. || ENABLE_UNICODE_USING_LOCALE
  2146. ) {
  2147. const char *s = lookupvar("LC_ALL");
  2148. if (!s) s = lookupvar("LC_CTYPE");
  2149. if (!s) s = lookupvar("LANG");
  2150. reinit_unicode(s);
  2151. }
  2152. }
  2153. #else
  2154. # define reinit_unicode_for_ash() ((void)0)
  2155. #endif
  2156. /*
  2157. * Search the environment of a builtin command.
  2158. */
  2159. static ALWAYS_INLINE const char *
  2160. bltinlookup(const char *name)
  2161. {
  2162. return lookupvar(name);
  2163. }
  2164. /*
  2165. * Same as setvar except that the variable and value are passed in
  2166. * the first argument as name=value. Since the first argument will
  2167. * be actually stored in the table, it should not be a string that
  2168. * will go away.
  2169. * Called with interrupts off.
  2170. */
  2171. static struct var *
  2172. setvareq(char *s, int flags)
  2173. {
  2174. struct var *vp, **vpp;
  2175. vpp = hashvar(s);
  2176. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2177. vpp = findvar(vpp, s);
  2178. vp = *vpp;
  2179. if (vp) {
  2180. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2181. const char *n;
  2182. if (flags & VNOSAVE)
  2183. free(s);
  2184. n = vp->var_text;
  2185. exitstatus = 1;
  2186. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2187. }
  2188. if (flags & VNOSET)
  2189. goto out;
  2190. if (vp->var_func && !(flags & VNOFUNC))
  2191. vp->var_func(var_end(s));
  2192. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2193. free((char*)vp->var_text);
  2194. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2195. *vpp = vp->next;
  2196. free(vp);
  2197. out_free:
  2198. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2199. free(s);
  2200. goto out;
  2201. }
  2202. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2203. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2204. if (flags & VUNSET)
  2205. flags &= ~VDYNAMIC;
  2206. #endif
  2207. } else {
  2208. /* variable s is not found */
  2209. if (flags & VNOSET)
  2210. goto out;
  2211. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2212. goto out_free;
  2213. vp = ckzalloc(sizeof(*vp));
  2214. vp->next = *vpp;
  2215. /*vp->func = NULL; - ckzalloc did it */
  2216. *vpp = vp;
  2217. }
  2218. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2219. s = ckstrdup(s);
  2220. vp->var_text = s;
  2221. vp->flags = flags;
  2222. out:
  2223. return vp;
  2224. }
  2225. /*
  2226. * Set the value of a variable. The flags argument is ored with the
  2227. * flags of the variable. If val is NULL, the variable is unset.
  2228. */
  2229. static struct var *
  2230. setvar(const char *name, const char *val, int flags)
  2231. {
  2232. const char *q;
  2233. char *p;
  2234. char *nameeq;
  2235. size_t namelen;
  2236. size_t vallen;
  2237. struct var *vp;
  2238. q = endofname(name);
  2239. p = strchrnul(q, '=');
  2240. namelen = p - name;
  2241. if (!namelen || p != q)
  2242. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2243. vallen = 0;
  2244. if (val == NULL) {
  2245. flags |= VUNSET;
  2246. } else {
  2247. vallen = strlen(val);
  2248. }
  2249. INT_OFF;
  2250. nameeq = ckzalloc(namelen + vallen + 2);
  2251. p = mempcpy(nameeq, name, namelen);
  2252. if (val) {
  2253. *p++ = '=';
  2254. strcpy(p, val);
  2255. }
  2256. vp = setvareq(nameeq, flags | VNOSAVE);
  2257. INT_ON;
  2258. return vp;
  2259. }
  2260. static void FAST_FUNC
  2261. setvar0(const char *name, const char *val)
  2262. {
  2263. setvar(name, val, 0);
  2264. }
  2265. /*
  2266. * Unset the specified variable.
  2267. */
  2268. static void
  2269. unsetvar(const char *s)
  2270. {
  2271. setvar(s, NULL, 0);
  2272. }
  2273. /*
  2274. * Generate a list of variables satisfying the given conditions.
  2275. */
  2276. #if !ENABLE_FEATURE_SH_NOFORK
  2277. # define listvars(on, off, lp, end) listvars(on, off, end)
  2278. #endif
  2279. static char **
  2280. listvars(int on, int off, struct strlist *lp, char ***end)
  2281. {
  2282. struct var **vpp;
  2283. struct var *vp;
  2284. char **ep;
  2285. int mask;
  2286. STARTSTACKSTR(ep);
  2287. vpp = vartab;
  2288. mask = on | off;
  2289. do {
  2290. for (vp = *vpp; vp; vp = vp->next) {
  2291. if ((vp->flags & mask) == on) {
  2292. #if ENABLE_FEATURE_SH_NOFORK
  2293. /* If variable with the same name is both
  2294. * exported and temporarily set for a command:
  2295. * export ZVAR=5
  2296. * ZVAR=6 printenv
  2297. * then "ZVAR=6" will be both in vartab and
  2298. * lp lists. Do not pass it twice to printenv.
  2299. */
  2300. struct strlist *lp1 = lp;
  2301. while (lp1) {
  2302. if (strcmp(lp1->text, vp->var_text) == 0)
  2303. goto skip;
  2304. lp1 = lp1->next;
  2305. }
  2306. #endif
  2307. if (ep == stackstrend())
  2308. ep = growstackstr();
  2309. *ep++ = (char*)vp->var_text;
  2310. #if ENABLE_FEATURE_SH_NOFORK
  2311. skip: ;
  2312. #endif
  2313. }
  2314. }
  2315. } while (++vpp < vartab + VTABSIZE);
  2316. #if ENABLE_FEATURE_SH_NOFORK
  2317. while (lp) {
  2318. if (ep == stackstrend())
  2319. ep = growstackstr();
  2320. *ep++ = lp->text;
  2321. lp = lp->next;
  2322. }
  2323. #endif
  2324. if (ep == stackstrend())
  2325. ep = growstackstr();
  2326. if (end)
  2327. *end = ep;
  2328. *ep++ = NULL;
  2329. return grabstackstr(ep);
  2330. }
  2331. /* ============ Path search helper */
  2332. static const char *
  2333. legal_pathopt(const char *opt, const char *term, int magic)
  2334. {
  2335. switch (magic) {
  2336. case 0:
  2337. opt = NULL;
  2338. break;
  2339. case 1:
  2340. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2341. break;
  2342. default:
  2343. opt += strcspn(opt, term);
  2344. break;
  2345. }
  2346. if (opt && *opt == '%')
  2347. opt++;
  2348. return opt;
  2349. }
  2350. /*
  2351. * The variable path (passed by reference) should be set to the start
  2352. * of the path before the first call; padvance will update
  2353. * this value as it proceeds. Successive calls to padvance will return
  2354. * the possible path expansions in sequence. If an option (indicated by
  2355. * a percent sign) appears in the path entry then the global variable
  2356. * pathopt will be set to point to it; otherwise pathopt will be set to
  2357. * NULL.
  2358. *
  2359. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2360. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2361. * pathopt.
  2362. */
  2363. static const char *pathopt; /* set by padvance */
  2364. static int
  2365. padvance_magic(const char **path, const char *name, int magic)
  2366. {
  2367. const char *term = "%:";
  2368. const char *lpathopt;
  2369. const char *p;
  2370. char *q;
  2371. const char *start;
  2372. size_t qlen;
  2373. size_t len;
  2374. if (*path == NULL)
  2375. return -1;
  2376. lpathopt = NULL;
  2377. start = *path;
  2378. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2379. lpathopt = start + 1;
  2380. start = p;
  2381. term = ":";
  2382. }
  2383. len = strcspn(start, term);
  2384. p = start + len;
  2385. if (*p == '%') {
  2386. size_t extra = strchrnul(p, ':') - p;
  2387. if (legal_pathopt(p + 1, term, magic))
  2388. lpathopt = p + 1;
  2389. else
  2390. len += extra;
  2391. p += extra;
  2392. }
  2393. pathopt = lpathopt;
  2394. *path = *p == ':' ? p + 1 : NULL;
  2395. /* "2" is for '/' and '\0' */
  2396. qlen = len + strlen(name) + 2;
  2397. q = growstackto(qlen);
  2398. if (len) {
  2399. q = mempcpy(q, start, len);
  2400. *q++ = '/';
  2401. }
  2402. strcpy(q, name);
  2403. return qlen;
  2404. }
  2405. static int
  2406. padvance(const char **path, const char *name)
  2407. {
  2408. return padvance_magic(path, name, 1);
  2409. }
  2410. /* ============ Prompt */
  2411. static smallint doprompt; /* if set, prompt the user */
  2412. static smallint needprompt; /* true if interactive and at start of line */
  2413. #if ENABLE_FEATURE_EDITING
  2414. static line_input_t *line_input_state;
  2415. static const char *cmdedit_prompt;
  2416. static void
  2417. putprompt(const char *s)
  2418. {
  2419. if (ENABLE_ASH_EXPAND_PRMT) {
  2420. free((char*)cmdedit_prompt);
  2421. cmdedit_prompt = ckstrdup(s);
  2422. return;
  2423. }
  2424. cmdedit_prompt = s;
  2425. }
  2426. #else
  2427. static void
  2428. putprompt(const char *s)
  2429. {
  2430. out2str(s);
  2431. }
  2432. #endif
  2433. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2434. static const char *expandstr(const char *ps, int syntax_type);
  2435. /* Values for syntax param */
  2436. #define BASESYNTAX 0 /* not in quotes */
  2437. #define DQSYNTAX 1 /* in double quotes */
  2438. #define SQSYNTAX 2 /* in single quotes */
  2439. #define ARISYNTAX 3 /* in arithmetic */
  2440. #if ENABLE_ASH_EXPAND_PRMT
  2441. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2442. #endif
  2443. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2444. /*
  2445. * called by editline -- any expansions to the prompt should be added here.
  2446. */
  2447. static void
  2448. setprompt_if(smallint do_set, int whichprompt)
  2449. {
  2450. const char *prompt;
  2451. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2452. if (!do_set)
  2453. return;
  2454. needprompt = 0;
  2455. switch (whichprompt) {
  2456. case 1:
  2457. prompt = ps1val();
  2458. break;
  2459. case 2:
  2460. prompt = ps2val();
  2461. break;
  2462. default: /* 0 */
  2463. prompt = nullstr;
  2464. }
  2465. #if ENABLE_ASH_EXPAND_PRMT
  2466. pushstackmark(&smark, stackblocksize());
  2467. putprompt(expandstr(prompt, PSSYNTAX));
  2468. popstackmark(&smark);
  2469. #else
  2470. putprompt(prompt);
  2471. #endif
  2472. }
  2473. /* ============ The cd and pwd commands */
  2474. #define CD_PHYSICAL 1
  2475. #define CD_PRINT 2
  2476. static int
  2477. cdopt(void)
  2478. {
  2479. int flags = 0;
  2480. int i, j;
  2481. j = 'L';
  2482. while ((i = nextopt("LP")) != '\0') {
  2483. if (i != j) {
  2484. flags ^= CD_PHYSICAL;
  2485. j = i;
  2486. }
  2487. }
  2488. return flags;
  2489. }
  2490. /*
  2491. * Update curdir (the name of the current directory) in response to a
  2492. * cd command.
  2493. */
  2494. static const char *
  2495. updatepwd(const char *dir)
  2496. {
  2497. char *new;
  2498. char *p;
  2499. char *cdcomppath;
  2500. const char *lim;
  2501. cdcomppath = sstrdup(dir);
  2502. STARTSTACKSTR(new);
  2503. if (*dir != '/') {
  2504. if (curdir == nullstr)
  2505. return 0;
  2506. new = stack_putstr(curdir, new);
  2507. }
  2508. new = makestrspace(strlen(dir) + 2, new);
  2509. lim = (char *)stackblock() + 1;
  2510. if (*dir != '/') {
  2511. if (new[-1] != '/')
  2512. USTPUTC('/', new);
  2513. if (new > lim && *lim == '/')
  2514. lim++;
  2515. } else {
  2516. USTPUTC('/', new);
  2517. cdcomppath++;
  2518. if (dir[1] == '/' && dir[2] != '/') {
  2519. USTPUTC('/', new);
  2520. cdcomppath++;
  2521. lim++;
  2522. }
  2523. }
  2524. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2525. while (p) {
  2526. switch (*p) {
  2527. case '.':
  2528. if (p[1] == '.' && p[2] == '\0') {
  2529. while (new > lim) {
  2530. STUNPUTC(new);
  2531. if (new[-1] == '/')
  2532. break;
  2533. }
  2534. break;
  2535. }
  2536. if (p[1] == '\0')
  2537. break;
  2538. /* fall through */
  2539. default:
  2540. new = stack_putstr(p, new);
  2541. USTPUTC('/', new);
  2542. }
  2543. p = strtok_r(NULL, "/", &cdcomppath);
  2544. }
  2545. if (new > lim)
  2546. STUNPUTC(new);
  2547. *new = 0;
  2548. return stackblock();
  2549. }
  2550. /*
  2551. * Find out what the current directory is. If we already know the current
  2552. * directory, this routine returns immediately.
  2553. */
  2554. static char *
  2555. getpwd(void)
  2556. {
  2557. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2558. return dir ? dir : nullstr;
  2559. }
  2560. static void
  2561. setpwd(const char *val, int setold)
  2562. {
  2563. char *oldcur, *dir;
  2564. oldcur = dir = curdir;
  2565. if (setold) {
  2566. setvar("OLDPWD", oldcur, VEXPORT);
  2567. }
  2568. INT_OFF;
  2569. if (physdir != nullstr) {
  2570. if (physdir != oldcur)
  2571. free(physdir);
  2572. physdir = nullstr;
  2573. }
  2574. if (oldcur == val || !val) {
  2575. char *s = getpwd();
  2576. physdir = s;
  2577. if (!val)
  2578. dir = s;
  2579. } else
  2580. dir = ckstrdup(val);
  2581. if (oldcur != dir && oldcur != nullstr) {
  2582. free(oldcur);
  2583. }
  2584. curdir = dir;
  2585. INT_ON;
  2586. setvar("PWD", dir, VEXPORT);
  2587. }
  2588. static void hashcd(void);
  2589. /*
  2590. * Actually do the chdir. We also call hashcd to let other routines
  2591. * know that the current directory has changed.
  2592. */
  2593. static int
  2594. docd(const char *dest, int flags)
  2595. {
  2596. const char *dir = NULL;
  2597. int err;
  2598. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2599. INT_OFF;
  2600. if (!(flags & CD_PHYSICAL)) {
  2601. dir = updatepwd(dest);
  2602. if (dir)
  2603. dest = dir;
  2604. }
  2605. err = chdir(dest);
  2606. if (err)
  2607. goto out;
  2608. setpwd(dir, 1);
  2609. hashcd();
  2610. out:
  2611. INT_ON;
  2612. return err;
  2613. }
  2614. static int FAST_FUNC
  2615. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2616. {
  2617. const char *dest;
  2618. const char *path;
  2619. const char *p;
  2620. char c;
  2621. struct stat statb;
  2622. int flags;
  2623. int len;
  2624. flags = cdopt();
  2625. dest = *argptr;
  2626. if (!dest)
  2627. dest = bltinlookup("HOME");
  2628. else if (LONE_DASH(dest)) {
  2629. dest = bltinlookup("OLDPWD");
  2630. flags |= CD_PRINT;
  2631. }
  2632. if (!dest)
  2633. dest = nullstr;
  2634. if (*dest == '/')
  2635. goto step6;
  2636. if (*dest == '.') {
  2637. c = dest[1];
  2638. dotdot:
  2639. switch (c) {
  2640. case '\0':
  2641. case '/':
  2642. goto step6;
  2643. case '.':
  2644. c = dest[2];
  2645. if (c != '.')
  2646. goto dotdot;
  2647. }
  2648. }
  2649. if (!*dest)
  2650. dest = ".";
  2651. path = bltinlookup("CDPATH");
  2652. while (p = path, (len = padvance_magic(&path, dest, 0)) >= 0) {
  2653. c = *p;
  2654. p = stalloc(len);
  2655. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2656. if (c && c != ':')
  2657. flags |= CD_PRINT;
  2658. docd:
  2659. if (!docd(p, flags))
  2660. goto out;
  2661. goto err;
  2662. }
  2663. }
  2664. step6:
  2665. p = dest;
  2666. goto docd;
  2667. err:
  2668. ash_msg_and_raise_perror("can't cd to %s", dest);
  2669. /* NOTREACHED */
  2670. out:
  2671. if (flags & CD_PRINT)
  2672. out1fmt("%s\n", curdir);
  2673. return 0;
  2674. }
  2675. static int FAST_FUNC
  2676. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2677. {
  2678. int flags;
  2679. const char *dir = curdir;
  2680. flags = cdopt();
  2681. if (flags) {
  2682. if (physdir == nullstr)
  2683. setpwd(dir, 0);
  2684. dir = physdir;
  2685. }
  2686. out1fmt("%s\n", dir);
  2687. return 0;
  2688. }
  2689. /* ============ ... */
  2690. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2691. /* Syntax classes */
  2692. #define CWORD 0 /* character is nothing special */
  2693. #define CNL 1 /* newline character */
  2694. #define CBACK 2 /* a backslash character */
  2695. #define CSQUOTE 3 /* single quote */
  2696. #define CDQUOTE 4 /* double quote */
  2697. #define CENDQUOTE 5 /* a terminating quote */
  2698. #define CBQUOTE 6 /* backwards single quote */
  2699. #define CVAR 7 /* a dollar sign */
  2700. #define CENDVAR 8 /* a '}' character */
  2701. #define CLP 9 /* a left paren in arithmetic */
  2702. #define CRP 10 /* a right paren in arithmetic */
  2703. #define CENDFILE 11 /* end of file */
  2704. #define CCTL 12 /* like CWORD, except it must be escaped */
  2705. #define CSPCL 13 /* these terminate a word */
  2706. #define PEOF 256
  2707. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2708. #if ENABLE_FEATURE_SH_MATH
  2709. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2710. #else
  2711. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2712. #endif
  2713. static const uint16_t S_I_T[] ALIGN2 = {
  2714. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 0, ' ' */
  2715. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 1, \n */
  2716. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 2, !*-/:=?[]~ */
  2717. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 3, '"' */
  2718. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 4, $ */
  2719. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 5, "'" */
  2720. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 6, ( */
  2721. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 7, ) */
  2722. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 8, \ */
  2723. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 9, ` */
  2724. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 10, } */
  2725. #if !USE_SIT_FUNCTION
  2726. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 11, PEOF */
  2727. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 12, 0-9A-Za-z */
  2728. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 13, CTLESC ... */
  2729. #endif
  2730. #undef SIT_ITEM
  2731. };
  2732. /* Constants below must match table above */
  2733. enum {
  2734. CSPCL_CWORD_CWORD_CWORD , /* 0 */
  2735. CNL_CNL_CNL_CNL , /* 1 */
  2736. CWORD_CCTL_CCTL_CWORD , /* 2 */
  2737. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 3 */
  2738. CVAR_CVAR_CWORD_CVAR , /* 4 */
  2739. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 5 */
  2740. CSPCL_CWORD_CWORD_CLP , /* 6 */
  2741. CSPCL_CWORD_CWORD_CRP , /* 7 */
  2742. CBACK_CBACK_CCTL_CBACK , /* 8 */
  2743. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 9 */
  2744. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 10 */
  2745. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 11 */
  2746. CWORD_CWORD_CWORD_CWORD , /* 12 */
  2747. CCTL_CCTL_CCTL_CCTL , /* 13 */
  2748. };
  2749. /* c in SIT(c, syntax) must be an *unsigned char* or PEOF,
  2750. * caller must ensure proper cast on it if c is *char_ptr!
  2751. */
  2752. #if USE_SIT_FUNCTION
  2753. static int
  2754. SIT(int c, int syntax)
  2755. {
  2756. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2757. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2758. /*
  2759. * This causes '/' to be prepended with CTLESC in dquoted string,
  2760. * making "./file"* treated incorrectly because we feed
  2761. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2762. * The "homegrown" glob implementation is okay with that,
  2763. * but glibc one isn't. With '/' always treated as CWORD,
  2764. * both work fine.
  2765. */
  2766. static const uint8_t syntax_index_table[] ALIGN1 = {
  2767. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2768. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2769. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2770. 10, 2 /* "}~" */
  2771. };
  2772. const char *s;
  2773. int indx;
  2774. if (c == PEOF)
  2775. return CENDFILE;
  2776. /* Cast is purely for paranoia here,
  2777. * just in case someone passed signed char to us */
  2778. if ((unsigned char)c >= CTL_FIRST
  2779. && (unsigned char)c <= CTL_LAST
  2780. ) {
  2781. return CCTL;
  2782. }
  2783. s = strchrnul(spec_symbls, c);
  2784. if (*s == '\0')
  2785. return CWORD;
  2786. indx = syntax_index_table[s - spec_symbls];
  2787. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2788. }
  2789. #else /* !USE_SIT_FUNCTION */
  2790. static const uint8_t syntax_index_table[] ALIGN1 = {
  2791. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2792. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2802. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2803. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2825. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2826. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2827. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2829. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2831. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2832. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2833. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2834. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2835. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2838. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2839. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2840. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2852. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2853. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2854. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2855. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2856. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2857. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2885. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2886. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2887. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2890. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2918. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2919. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2920. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2923. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2924. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2925. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2926. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2927. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2928. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2929. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2930. #if BASH_PROCESS_SUBST
  2931. /* 137 CTLTOPROC */ CCTL_CCTL_CCTL_CCTL,
  2932. /* 138 CTLFROMPROC */ CCTL_CCTL_CCTL_CCTL,
  2933. #else
  2934. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2936. #endif
  2937. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3029. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3030. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3031. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3032. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3033. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3034. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3035. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3036. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3037. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3038. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3039. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3040. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3041. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3042. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3043. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3044. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3045. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3046. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3047. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3048. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3049. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3050. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3051. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3052. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3053. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3054. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3055. };
  3056. #if 1
  3057. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3058. #else /* debug version, caught one signed char bug */
  3059. # define SIT(c, syntax) \
  3060. ({ \
  3061. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3062. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3063. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3064. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3065. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3066. })
  3067. #endif
  3068. #endif /* !USE_SIT_FUNCTION */
  3069. /* ============ Alias handling */
  3070. #if ENABLE_ASH_ALIAS
  3071. #define ALIASINUSE 1
  3072. #define ALIASDEAD 2
  3073. struct alias {
  3074. struct alias *next;
  3075. char *name;
  3076. char *val;
  3077. int flag;
  3078. };
  3079. static struct alias **atab; // [ATABSIZE];
  3080. #define INIT_G_alias() do { \
  3081. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3082. } while (0)
  3083. static struct alias **
  3084. __lookupalias(const char *name)
  3085. {
  3086. unsigned int hashval;
  3087. struct alias **app;
  3088. const char *p;
  3089. unsigned int ch;
  3090. p = name;
  3091. ch = (unsigned char)*p;
  3092. hashval = ch << 4;
  3093. while (ch) {
  3094. hashval += ch;
  3095. ch = (unsigned char)*++p;
  3096. }
  3097. app = &atab[hashval % ATABSIZE];
  3098. for (; *app; app = &(*app)->next) {
  3099. if (strcmp(name, (*app)->name) == 0) {
  3100. break;
  3101. }
  3102. }
  3103. return app;
  3104. }
  3105. static struct alias *
  3106. lookupalias(const char *name, int check)
  3107. {
  3108. struct alias *ap = *__lookupalias(name);
  3109. if (check && ap && (ap->flag & ALIASINUSE))
  3110. return NULL;
  3111. return ap;
  3112. }
  3113. static struct alias *
  3114. freealias(struct alias *ap)
  3115. {
  3116. struct alias *next;
  3117. if (ap->flag & ALIASINUSE) {
  3118. ap->flag |= ALIASDEAD;
  3119. return ap;
  3120. }
  3121. next = ap->next;
  3122. free(ap->name);
  3123. free(ap->val);
  3124. free(ap);
  3125. return next;
  3126. }
  3127. static void
  3128. setalias(const char *name, const char *val)
  3129. {
  3130. struct alias *ap, **app;
  3131. app = __lookupalias(name);
  3132. ap = *app;
  3133. INT_OFF;
  3134. if (ap) {
  3135. if (!(ap->flag & ALIASINUSE)) {
  3136. free(ap->val);
  3137. }
  3138. ap->val = ckstrdup(val);
  3139. ap->flag &= ~ALIASDEAD;
  3140. } else {
  3141. /* not found */
  3142. ap = ckzalloc(sizeof(struct alias));
  3143. ap->name = ckstrdup(name);
  3144. ap->val = ckstrdup(val);
  3145. /*ap->flag = 0; - ckzalloc did it */
  3146. /*ap->next = NULL;*/
  3147. *app = ap;
  3148. }
  3149. INT_ON;
  3150. }
  3151. static int
  3152. unalias(const char *name)
  3153. {
  3154. struct alias **app;
  3155. app = __lookupalias(name);
  3156. if (*app) {
  3157. INT_OFF;
  3158. *app = freealias(*app);
  3159. INT_ON;
  3160. return 0;
  3161. }
  3162. return 1;
  3163. }
  3164. static void
  3165. rmaliases(void)
  3166. {
  3167. struct alias *ap, **app;
  3168. int i;
  3169. INT_OFF;
  3170. for (i = 0; i < ATABSIZE; i++) {
  3171. app = &atab[i];
  3172. for (ap = *app; ap; ap = *app) {
  3173. *app = freealias(*app);
  3174. if (ap == *app) {
  3175. app = &ap->next;
  3176. }
  3177. }
  3178. }
  3179. INT_ON;
  3180. }
  3181. static void
  3182. printalias(const struct alias *ap)
  3183. {
  3184. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3185. }
  3186. /*
  3187. * TODO - sort output
  3188. */
  3189. static int FAST_FUNC
  3190. aliascmd(int argc UNUSED_PARAM, char **argv)
  3191. {
  3192. char *n, *v;
  3193. int ret = 0;
  3194. struct alias *ap;
  3195. if (!argv[1]) {
  3196. int i;
  3197. for (i = 0; i < ATABSIZE; i++) {
  3198. for (ap = atab[i]; ap; ap = ap->next) {
  3199. printalias(ap);
  3200. }
  3201. }
  3202. return 0;
  3203. }
  3204. while ((n = *++argv) != NULL) {
  3205. v = strchr(n+1, '=');
  3206. if (v == NULL) { /* n+1: funny ksh stuff */
  3207. ap = *__lookupalias(n);
  3208. if (ap == NULL) {
  3209. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3210. ret = 1;
  3211. } else
  3212. printalias(ap);
  3213. } else {
  3214. *v++ = '\0';
  3215. setalias(n, v);
  3216. }
  3217. }
  3218. return ret;
  3219. }
  3220. static int FAST_FUNC
  3221. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3222. {
  3223. int i;
  3224. while (nextopt("a") != '\0') {
  3225. rmaliases();
  3226. return 0;
  3227. }
  3228. for (i = 0; *argptr; argptr++) {
  3229. if (unalias(*argptr)) {
  3230. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3231. i = 1;
  3232. }
  3233. }
  3234. return i;
  3235. }
  3236. #endif /* ASH_ALIAS */
  3237. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3238. #define FORK_FG 0
  3239. #define FORK_BG 1
  3240. #define FORK_NOJOB 2
  3241. /* mode flags for showjob(s) */
  3242. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3243. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3244. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3245. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3246. /*
  3247. * A job structure contains information about a job. A job is either a
  3248. * single process or a set of processes contained in a pipeline. In the
  3249. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3250. * array of pids.
  3251. */
  3252. struct procstat {
  3253. pid_t ps_pid; /* process id */
  3254. int ps_status; /* last process status from wait() */
  3255. char *ps_cmd; /* text of command being run */
  3256. };
  3257. struct job {
  3258. struct procstat ps0; /* status of process */
  3259. struct procstat *ps; /* status of processes when more than one */
  3260. #if JOBS
  3261. int stopstatus; /* status of a stopped job */
  3262. #endif
  3263. unsigned nprocs; /* number of processes */
  3264. #define JOBRUNNING 0 /* at least one proc running */
  3265. #define JOBSTOPPED 1 /* all procs are stopped */
  3266. #define JOBDONE 2 /* all procs are completed */
  3267. unsigned
  3268. state: 8,
  3269. #if JOBS
  3270. sigint: 1, /* job was killed by SIGINT */
  3271. jobctl: 1, /* job running under job control */
  3272. #endif
  3273. waited: 1, /* true if this entry has been waited for */
  3274. used: 1, /* true if this entry is in used */
  3275. changed: 1; /* true if status has changed */
  3276. struct job *prev_job; /* previous job */
  3277. };
  3278. static struct job *makejob(/*union node *,*/ int);
  3279. static int forkshell(struct job *, union node *, int);
  3280. static int waitforjob(struct job *);
  3281. #if !JOBS
  3282. enum { doing_jobctl = 0 };
  3283. #define setjobctl(on) do {} while (0)
  3284. #else
  3285. static smallint doing_jobctl; //references:8
  3286. static void setjobctl(int);
  3287. #endif
  3288. /*
  3289. * Ignore a signal.
  3290. */
  3291. static void
  3292. ignoresig(int signo)
  3293. {
  3294. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3295. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3296. /* No, need to do it */
  3297. signal(signo, SIG_IGN);
  3298. }
  3299. sigmode[signo - 1] = S_HARD_IGN;
  3300. }
  3301. /*
  3302. * Only one usage site - in setsignal()
  3303. */
  3304. static void
  3305. signal_handler(int signo)
  3306. {
  3307. if (signo == SIGCHLD) {
  3308. got_sigchld = 1;
  3309. if (!trap[SIGCHLD])
  3310. return;
  3311. }
  3312. #if ENABLE_FEATURE_EDITING
  3313. bb_got_signal = signo; /* for read_line_input: "we got a signal" */
  3314. #endif
  3315. gotsig[signo - 1] = 1;
  3316. pending_sig = signo;
  3317. if (signo == SIGINT && !trap[SIGINT]) {
  3318. if (!suppress_int) {
  3319. pending_sig = 0;
  3320. raise_interrupt(); /* does not return */
  3321. }
  3322. pending_int = 1;
  3323. }
  3324. }
  3325. /*
  3326. * Set the signal handler for the specified signal. The routine figures
  3327. * out what it should be set to.
  3328. */
  3329. static void
  3330. setsignal(int signo)
  3331. {
  3332. char *t;
  3333. char cur_act, new_act;
  3334. struct sigaction act;
  3335. t = trap[signo];
  3336. new_act = S_DFL;
  3337. if (t != NULL) { /* trap for this sig is set */
  3338. new_act = S_CATCH;
  3339. if (t[0] == '\0') /* trap is "": ignore this sig */
  3340. new_act = S_IGN;
  3341. }
  3342. if (rootshell && new_act == S_DFL) {
  3343. switch (signo) {
  3344. case SIGINT:
  3345. if (iflag || minusc || sflag == 0)
  3346. new_act = S_CATCH;
  3347. break;
  3348. case SIGQUIT:
  3349. #if DEBUG
  3350. if (debug)
  3351. break;
  3352. #endif
  3353. /* man bash:
  3354. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3355. * commands run by bash have signal handlers
  3356. * set to the values inherited by the shell
  3357. * from its parent". */
  3358. new_act = S_IGN;
  3359. break;
  3360. case SIGTERM:
  3361. if (iflag)
  3362. new_act = S_IGN;
  3363. break;
  3364. #if JOBS
  3365. case SIGTSTP:
  3366. case SIGTTOU:
  3367. if (mflag)
  3368. new_act = S_IGN;
  3369. break;
  3370. #endif
  3371. }
  3372. }
  3373. /* if !rootshell, we reset SIGQUIT to DFL,
  3374. * whereas we have to restore it to what shell got on entry.
  3375. * This is handled by the fact that if signal was IGNored on entry,
  3376. * then cur_act is S_HARD_IGN and we never change its sigaction
  3377. * (see code below).
  3378. */
  3379. if (signo == SIGCHLD)
  3380. new_act = S_CATCH;
  3381. t = &sigmode[signo - 1];
  3382. cur_act = *t;
  3383. if (cur_act == 0) {
  3384. /* current setting is not yet known */
  3385. if (sigaction(signo, NULL, &act)) {
  3386. /* pretend it worked; maybe we should give a warning,
  3387. * but other shells don't. We don't alter sigmode,
  3388. * so we retry every time.
  3389. * btw, in Linux it never fails. --vda */
  3390. return;
  3391. }
  3392. if (act.sa_handler == SIG_IGN) {
  3393. cur_act = S_HARD_IGN;
  3394. if (mflag
  3395. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3396. ) {
  3397. cur_act = S_IGN; /* don't hard ignore these */
  3398. }
  3399. }
  3400. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3401. /* installing SIG_DFL over SIG_DFL is a no-op */
  3402. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3403. *t = S_DFL;
  3404. return;
  3405. }
  3406. }
  3407. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3408. return;
  3409. *t = new_act;
  3410. act.sa_handler = SIG_DFL;
  3411. switch (new_act) {
  3412. case S_CATCH:
  3413. act.sa_handler = signal_handler;
  3414. break;
  3415. case S_IGN:
  3416. act.sa_handler = SIG_IGN;
  3417. break;
  3418. }
  3419. /* flags and mask matter only if !DFL and !IGN, but we do it
  3420. * for all cases for more deterministic behavior:
  3421. */
  3422. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3423. sigfillset(&act.sa_mask);
  3424. sigaction_set(signo, &act);
  3425. }
  3426. /* mode flags for set_curjob */
  3427. #define CUR_DELETE 2
  3428. #define CUR_RUNNING 1
  3429. #define CUR_STOPPED 0
  3430. #if JOBS
  3431. /* pgrp of shell on invocation */
  3432. static int initialpgrp; //references:2
  3433. static int ttyfd = -1; //5
  3434. #endif
  3435. /* array of jobs */
  3436. static struct job *jobtab; //5
  3437. /* size of array */
  3438. static unsigned njobs; //4
  3439. /* current job */
  3440. static struct job *curjob; //lots
  3441. #if 0
  3442. /* Bash has a feature: it restores termios after a successful wait for
  3443. * a foreground job which had at least one stopped or sigkilled member.
  3444. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3445. * properly restoring tty state. Should we do this too?
  3446. * A reproducer: ^Z an interactive python:
  3447. *
  3448. * # python
  3449. * Python 2.7.12 (...)
  3450. * >>> ^Z
  3451. * { python leaves tty in -icanon -echo state. We do survive that... }
  3452. * [1]+ Stopped python
  3453. * { ...however, next program (python #2) does not survive it well: }
  3454. * # python
  3455. * Python 2.7.12 (...)
  3456. * >>> Traceback (most recent call last):
  3457. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3458. * File "<stdin>", line 1, in <module>
  3459. * NameError: name 'qwerty' is not defined
  3460. *
  3461. * The implementation below is modeled on bash code and seems to work.
  3462. * However, I'm not sure we should do this. For one: what if I'd fg
  3463. * the stopped python instead? It'll be confused by "restored" tty state.
  3464. */
  3465. static struct termios shell_tty_info;
  3466. static void
  3467. get_tty_state(void)
  3468. {
  3469. if (rootshell && ttyfd >= 0)
  3470. tcgetattr(ttyfd, &shell_tty_info);
  3471. }
  3472. static void
  3473. set_tty_state(void)
  3474. {
  3475. /* if (rootshell) - caller ensures this */
  3476. if (ttyfd >= 0)
  3477. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3478. }
  3479. static int
  3480. job_signal_status(struct job *jp)
  3481. {
  3482. int status;
  3483. unsigned i;
  3484. struct procstat *ps = jp->ps;
  3485. for (i = 0; i < jp->nprocs; i++) {
  3486. status = ps[i].ps_status;
  3487. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3488. return status;
  3489. }
  3490. return 0;
  3491. }
  3492. static void
  3493. restore_tty_if_stopped_or_signaled(struct job *jp)
  3494. {
  3495. //TODO: check what happens if we come from waitforjob() in expbackq()
  3496. if (rootshell) {
  3497. int s = job_signal_status(jp);
  3498. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3499. set_tty_state();
  3500. }
  3501. }
  3502. #else
  3503. # define get_tty_state() ((void)0)
  3504. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3505. #endif
  3506. static void
  3507. set_curjob(struct job *jp, unsigned mode)
  3508. {
  3509. struct job *jp1;
  3510. struct job **jpp, **curp;
  3511. /* first remove from list */
  3512. jpp = curp = &curjob;
  3513. while (1) {
  3514. jp1 = *jpp;
  3515. if (jp1 == jp)
  3516. break;
  3517. jpp = &jp1->prev_job;
  3518. }
  3519. *jpp = jp1->prev_job;
  3520. /* Then re-insert in correct position */
  3521. jpp = curp;
  3522. switch (mode) {
  3523. default:
  3524. #if DEBUG
  3525. abort();
  3526. #endif
  3527. case CUR_DELETE:
  3528. /* job being deleted */
  3529. break;
  3530. case CUR_RUNNING:
  3531. /* newly created job or backgrounded job,
  3532. * put after all stopped jobs.
  3533. */
  3534. while (1) {
  3535. jp1 = *jpp;
  3536. #if JOBS
  3537. if (!jp1 || jp1->state != JOBSTOPPED)
  3538. #endif
  3539. break;
  3540. jpp = &jp1->prev_job;
  3541. }
  3542. /* FALLTHROUGH */
  3543. #if JOBS
  3544. case CUR_STOPPED:
  3545. #endif
  3546. /* newly stopped job - becomes curjob */
  3547. jp->prev_job = *jpp;
  3548. *jpp = jp;
  3549. break;
  3550. }
  3551. }
  3552. #if JOBS || DEBUG
  3553. static int
  3554. jobno(const struct job *jp)
  3555. {
  3556. return jp - jobtab + 1;
  3557. }
  3558. #endif
  3559. /*
  3560. * Convert a job name to a job structure.
  3561. */
  3562. #if !JOBS
  3563. #define getjob(name, getctl) getjob(name)
  3564. #endif
  3565. static struct job *
  3566. getjob(const char *name, int getctl)
  3567. {
  3568. struct job *jp;
  3569. struct job *found;
  3570. const char *err_msg = "%s: no such job";
  3571. unsigned num;
  3572. int c;
  3573. const char *p;
  3574. jp = curjob;
  3575. p = name;
  3576. if (!p)
  3577. goto currentjob;
  3578. if (*p != '%')
  3579. goto err;
  3580. c = *++p;
  3581. if (!c)
  3582. goto currentjob;
  3583. if (!p[1]) {
  3584. if (c == '+' || c == '%') {
  3585. currentjob:
  3586. err_msg = "No current job";
  3587. goto check;
  3588. }
  3589. if (c == '-') {
  3590. if (jp)
  3591. jp = jp->prev_job;
  3592. err_msg = "No previous job";
  3593. check:
  3594. if (!jp)
  3595. goto err;
  3596. goto gotit;
  3597. }
  3598. }
  3599. if (is_number(p)) {
  3600. num = atoi(p);
  3601. if (num > 0 && num <= njobs) {
  3602. jp = jobtab + num - 1;
  3603. if (jp->used)
  3604. goto gotit;
  3605. goto err;
  3606. }
  3607. }
  3608. found = NULL;
  3609. while (jp) {
  3610. if (*p == '?'
  3611. ? strstr(jp->ps[0].ps_cmd, p + 1)
  3612. : prefix(jp->ps[0].ps_cmd, p)
  3613. ) {
  3614. if (found)
  3615. goto err;
  3616. found = jp;
  3617. err_msg = "%s: ambiguous";
  3618. }
  3619. jp = jp->prev_job;
  3620. }
  3621. if (!found)
  3622. goto err;
  3623. jp = found;
  3624. gotit:
  3625. #if JOBS
  3626. err_msg = "job %s not created under job control";
  3627. if (getctl && jp->jobctl == 0)
  3628. goto err;
  3629. #endif
  3630. return jp;
  3631. err:
  3632. ash_msg_and_raise_error(err_msg, name);
  3633. }
  3634. /*
  3635. * Mark a job structure as unused.
  3636. */
  3637. static void
  3638. freejob(struct job *jp)
  3639. {
  3640. struct procstat *ps;
  3641. int i;
  3642. INT_OFF;
  3643. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3644. if (ps->ps_cmd != nullstr)
  3645. free(ps->ps_cmd);
  3646. }
  3647. if (jp->ps != &jp->ps0)
  3648. free(jp->ps);
  3649. jp->used = 0;
  3650. set_curjob(jp, CUR_DELETE);
  3651. INT_ON;
  3652. }
  3653. #if JOBS
  3654. static void
  3655. xtcsetpgrp(int fd, pid_t pgrp)
  3656. {
  3657. if (tcsetpgrp(fd, pgrp))
  3658. ash_msg_and_raise_perror("can't set tty process group");
  3659. }
  3660. /*
  3661. * Turn job control on and off.
  3662. *
  3663. * Note: This code assumes that the third arg to ioctl is a character
  3664. * pointer, which is true on Berkeley systems but not System V. Since
  3665. * System V doesn't have job control yet, this isn't a problem now.
  3666. *
  3667. * Called with interrupts off.
  3668. */
  3669. static void
  3670. setjobctl(int on)
  3671. {
  3672. int fd;
  3673. int pgrp;
  3674. if (on == doing_jobctl || rootshell == 0)
  3675. return;
  3676. if (on) {
  3677. int ofd;
  3678. ofd = fd = open(_PATH_TTY, O_RDWR);
  3679. if (fd < 0) {
  3680. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3681. * That sometimes helps to acquire controlling tty.
  3682. * Obviously, a workaround for bugs when someone
  3683. * failed to provide a controlling tty to bash! :) */
  3684. fd = 2;
  3685. while (!isatty(fd))
  3686. if (--fd < 0)
  3687. goto out;
  3688. }
  3689. /* fd is a tty at this point */
  3690. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3691. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3692. close(ofd);
  3693. if (fd < 0)
  3694. goto out; /* F_DUPFD failed */
  3695. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3696. close_on_exec_on(fd);
  3697. while (1) { /* while we are in the background */
  3698. pgrp = tcgetpgrp(fd);
  3699. if (pgrp < 0) {
  3700. out:
  3701. ash_msg("can't access tty; job control turned off");
  3702. mflag = on = 0;
  3703. goto close;
  3704. }
  3705. if (pgrp == getpgrp())
  3706. break;
  3707. killpg(0, SIGTTIN);
  3708. }
  3709. initialpgrp = pgrp;
  3710. setsignal(SIGTSTP);
  3711. setsignal(SIGTTOU);
  3712. setsignal(SIGTTIN);
  3713. pgrp = rootpid;
  3714. setpgid(0, pgrp);
  3715. xtcsetpgrp(fd, pgrp);
  3716. } else {
  3717. /* turning job control off */
  3718. fd = ttyfd;
  3719. pgrp = initialpgrp;
  3720. /* was xtcsetpgrp, but this can make exiting ash
  3721. * loop forever if pty is already deleted */
  3722. tcsetpgrp(fd, pgrp);
  3723. setpgid(0, pgrp);
  3724. setsignal(SIGTSTP);
  3725. setsignal(SIGTTOU);
  3726. setsignal(SIGTTIN);
  3727. close:
  3728. if (fd >= 0)
  3729. close(fd);
  3730. fd = -1;
  3731. }
  3732. ttyfd = fd;
  3733. doing_jobctl = on;
  3734. }
  3735. static int FAST_FUNC
  3736. killcmd(int argc, char **argv)
  3737. {
  3738. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3739. int i = 1;
  3740. do {
  3741. if (argv[i][0] == '%') {
  3742. /*
  3743. * "kill %N" - job kill
  3744. * Converting to pgrp / pid kill
  3745. */
  3746. struct job *jp;
  3747. char *dst;
  3748. int j, n;
  3749. jp = getjob(argv[i], 0);
  3750. /*
  3751. * In jobs started under job control, we signal
  3752. * entire process group by kill -PGRP_ID.
  3753. * This happens, f.e., in interactive shell.
  3754. *
  3755. * Otherwise, we signal each child via
  3756. * kill PID1 PID2 PID3.
  3757. * Testcases:
  3758. * sh -c 'sleep 1|sleep 1 & kill %1'
  3759. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3760. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3761. */
  3762. n = jp->nprocs; /* can't be 0 (I hope) */
  3763. if (jp->jobctl)
  3764. n = 1;
  3765. dst = alloca(n * sizeof(int)*4);
  3766. argv[i] = dst;
  3767. for (j = 0; j < n; j++) {
  3768. struct procstat *ps = &jp->ps[j];
  3769. /* Skip non-running and not-stopped members
  3770. * (i.e. dead members) of the job
  3771. */
  3772. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3773. continue;
  3774. /*
  3775. * kill_main has matching code to expect
  3776. * leading space. Needed to not confuse
  3777. * negative pids with "kill -SIGNAL_NO" syntax
  3778. */
  3779. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3780. }
  3781. *dst = '\0';
  3782. }
  3783. } while (argv[++i]);
  3784. }
  3785. return kill_main(argc, argv);
  3786. }
  3787. static void
  3788. showpipe(struct job *jp /*, FILE *out*/)
  3789. {
  3790. struct procstat *ps;
  3791. struct procstat *psend;
  3792. psend = jp->ps + jp->nprocs;
  3793. for (ps = jp->ps + 1; ps < psend; ps++)
  3794. printf(" | %s", ps->ps_cmd);
  3795. newline_and_flush(stdout);
  3796. flush_stdout_stderr();
  3797. }
  3798. static int
  3799. restartjob(struct job *jp, int mode)
  3800. {
  3801. struct procstat *ps;
  3802. int i;
  3803. int status;
  3804. pid_t pgid;
  3805. INT_OFF;
  3806. if (jp->state == JOBDONE)
  3807. goto out;
  3808. jp->state = JOBRUNNING;
  3809. pgid = jp->ps[0].ps_pid;
  3810. if (mode == FORK_FG) {
  3811. get_tty_state();
  3812. xtcsetpgrp(ttyfd, pgid);
  3813. }
  3814. killpg(pgid, SIGCONT);
  3815. ps = jp->ps;
  3816. i = jp->nprocs;
  3817. do {
  3818. if (WIFSTOPPED(ps->ps_status)) {
  3819. ps->ps_status = -1;
  3820. }
  3821. ps++;
  3822. } while (--i);
  3823. out:
  3824. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3825. INT_ON;
  3826. return status;
  3827. }
  3828. static int FAST_FUNC
  3829. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3830. {
  3831. struct job *jp;
  3832. int mode;
  3833. int retval;
  3834. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3835. nextopt(nullstr);
  3836. argv = argptr;
  3837. do {
  3838. jp = getjob(*argv, 1);
  3839. if (mode == FORK_BG) {
  3840. set_curjob(jp, CUR_RUNNING);
  3841. printf("[%d] ", jobno(jp));
  3842. }
  3843. out1str(jp->ps[0].ps_cmd);
  3844. showpipe(jp /*, stdout*/);
  3845. retval = restartjob(jp, mode);
  3846. } while (*argv && *++argv);
  3847. return retval;
  3848. }
  3849. #endif
  3850. static int
  3851. sprint_status48(char *os, int status, int sigonly)
  3852. {
  3853. char *s = os;
  3854. int st;
  3855. if (!WIFEXITED(status)) {
  3856. #if JOBS
  3857. if (WIFSTOPPED(status))
  3858. st = WSTOPSIG(status);
  3859. else
  3860. #endif
  3861. st = WTERMSIG(status);
  3862. if (sigonly) {
  3863. if (st == SIGINT || st == SIGPIPE)
  3864. goto out;
  3865. #if JOBS
  3866. if (WIFSTOPPED(status))
  3867. goto out;
  3868. #endif
  3869. }
  3870. st &= 0x7f;
  3871. s = stpncpy(s, strsignal(st), 32);
  3872. if (WCOREDUMP(status)) {
  3873. s = stpcpy(s, " (core dumped)");
  3874. }
  3875. } else if (!sigonly) {
  3876. st = WEXITSTATUS(status);
  3877. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3878. }
  3879. out:
  3880. return s - os;
  3881. }
  3882. #define DOWAIT_NONBLOCK 0
  3883. #define DOWAIT_BLOCK 1
  3884. #define DOWAIT_BLOCK_OR_SIG 2
  3885. #if BASH_WAIT_N
  3886. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3887. #endif
  3888. static int
  3889. waitproc(int block, int *status)
  3890. {
  3891. sigset_t oldmask;
  3892. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3893. int err;
  3894. #if JOBS
  3895. if (doing_jobctl)
  3896. flags |= WUNTRACED;
  3897. #endif
  3898. do {
  3899. got_sigchld = 0;
  3900. do
  3901. err = waitpid(-1, status, flags);
  3902. while (err < 0 && errno == EINTR);
  3903. if (err || (err = -!block))
  3904. break;
  3905. sigfillset(&oldmask);
  3906. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3907. while (!got_sigchld && !pending_sig)
  3908. sigsuspend(&oldmask);
  3909. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3910. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3911. //while (!got_sigchld && !pending_sig)
  3912. // pause();
  3913. } while (got_sigchld);
  3914. return err;
  3915. }
  3916. static int
  3917. waitone(int block, struct job *job)
  3918. {
  3919. int pid;
  3920. int status;
  3921. struct job *jp;
  3922. struct job *thisjob = NULL;
  3923. #if BASH_WAIT_N
  3924. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3925. block = (block & ~DOWAIT_JOBSTATUS);
  3926. #endif
  3927. TRACE(("dowait(0x%x) called\n", block));
  3928. /* It's wrong to call waitpid() outside of INT_OFF region:
  3929. * signal can arrive just after syscall return and handler can
  3930. * longjmp away, losing stop/exit notification processing.
  3931. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3932. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3933. *
  3934. * However, for "wait" builtin it is wrong to simply call waitpid()
  3935. * in INT_OFF region: "wait" needs to wait for any running job
  3936. * to change state, but should exit on any trap too.
  3937. * In INT_OFF region, a signal just before syscall entry can set
  3938. * pending_sig variables, but we can't check them, and we would
  3939. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3940. *
  3941. * Because of this, we run inside INT_OFF, but use a special routine
  3942. * which combines waitpid() and sigsuspend().
  3943. * This is the reason why we need to have a handler for SIGCHLD:
  3944. * SIG_DFL handler does not wake sigsuspend().
  3945. */
  3946. INT_OFF;
  3947. pid = waitproc(block, &status);
  3948. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3949. if (pid <= 0)
  3950. goto out;
  3951. for (jp = curjob; jp; jp = jp->prev_job) {
  3952. int jobstate;
  3953. struct procstat *ps;
  3954. struct procstat *psend;
  3955. if (jp->state == JOBDONE)
  3956. continue;
  3957. jobstate = JOBDONE;
  3958. ps = jp->ps;
  3959. psend = ps + jp->nprocs;
  3960. do {
  3961. if (ps->ps_pid == pid) {
  3962. TRACE(("Job %d: changing status of proc %d "
  3963. "from 0x%x to 0x%x\n",
  3964. jobno(jp), pid, ps->ps_status, status));
  3965. ps->ps_status = status;
  3966. thisjob = jp;
  3967. }
  3968. if (ps->ps_status == -1)
  3969. jobstate = JOBRUNNING;
  3970. #if JOBS
  3971. if (jobstate == JOBRUNNING)
  3972. continue;
  3973. if (WIFSTOPPED(ps->ps_status)) {
  3974. jp->stopstatus = ps->ps_status;
  3975. jobstate = JOBSTOPPED;
  3976. }
  3977. #endif
  3978. } while (++ps < psend);
  3979. if (!thisjob)
  3980. continue;
  3981. /* Found the job where one of its processes changed its state.
  3982. * Is there at least one live and running process in this job? */
  3983. if (jobstate != JOBRUNNING) {
  3984. /* No. All live processes in the job are stopped
  3985. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3986. */
  3987. thisjob->changed = 1;
  3988. if (thisjob->state != jobstate) {
  3989. TRACE(("Job %d: changing state from %d to %d\n",
  3990. jobno(thisjob), thisjob->state, jobstate));
  3991. thisjob->state = jobstate;
  3992. #if JOBS
  3993. if (jobstate == JOBSTOPPED)
  3994. set_curjob(thisjob, CUR_STOPPED);
  3995. #endif
  3996. }
  3997. }
  3998. goto out;
  3999. }
  4000. /* The process wasn't found in job list */
  4001. out:
  4002. INT_ON;
  4003. #if BASH_WAIT_N
  4004. if (want_jobexitstatus) {
  4005. pid = -1;
  4006. if (thisjob && thisjob->state == JOBDONE)
  4007. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4008. }
  4009. #endif
  4010. if (thisjob && thisjob == job) {
  4011. char s[48 + 1];
  4012. int len;
  4013. len = sprint_status48(s, status, 1);
  4014. if (len) {
  4015. s[len] = '\n';
  4016. s[len + 1] = '\0';
  4017. out2str(s);
  4018. }
  4019. }
  4020. return pid;
  4021. }
  4022. static int
  4023. dowait(int block, struct job *jp)
  4024. {
  4025. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4026. int rpid;
  4027. int pid;
  4028. if (jp && jp->state != JOBRUNNING)
  4029. block = DOWAIT_NONBLOCK;
  4030. if (block == DOWAIT_NONBLOCK && !gotchld)
  4031. return 1;
  4032. rpid = 1;
  4033. do {
  4034. pid = waitone(block, jp);
  4035. rpid &= !!pid;
  4036. if (!pid || (jp && jp->state != JOBRUNNING))
  4037. block = DOWAIT_NONBLOCK;
  4038. } while (pid >= 0);
  4039. return rpid;
  4040. }
  4041. #if JOBS
  4042. static void
  4043. showjob(struct job *jp, int mode)
  4044. {
  4045. struct procstat *ps;
  4046. struct procstat *psend;
  4047. int col;
  4048. int indent_col;
  4049. char s[16 + 16 + 48];
  4050. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4051. ps = jp->ps;
  4052. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4053. /* just output process (group) id of pipeline */
  4054. fprintf(out, "%d\n", ps->ps_pid);
  4055. return;
  4056. }
  4057. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4058. indent_col = col;
  4059. if (jp == curjob)
  4060. s[col - 3] = '+';
  4061. else if (curjob && jp == curjob->prev_job)
  4062. s[col - 3] = '-';
  4063. if (mode & SHOW_PIDS)
  4064. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4065. psend = ps + jp->nprocs;
  4066. if (jp->state == JOBRUNNING) {
  4067. strcpy(s + col, "Running");
  4068. col += sizeof("Running") - 1;
  4069. } else {
  4070. int status = psend[-1].ps_status;
  4071. if (jp->state == JOBSTOPPED)
  4072. status = jp->stopstatus;
  4073. col += sprint_status48(s + col, status, 0);
  4074. }
  4075. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4076. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4077. * or prints several "PID | <cmdN>" lines,
  4078. * depending on SHOW_PIDS bit.
  4079. * We do not print status of individual processes
  4080. * between PID and <cmdN>. bash does it, but not very well:
  4081. * first line shows overall job status, not process status,
  4082. * making it impossible to know 1st process status.
  4083. */
  4084. goto start;
  4085. do {
  4086. /* for each process */
  4087. s[0] = '\0';
  4088. col = 33;
  4089. if (mode & SHOW_PIDS)
  4090. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4091. start:
  4092. fprintf(out, "%s%*c%s%s",
  4093. s,
  4094. 33 - col >= 0 ? 33 - col : 0, ' ',
  4095. ps == jp->ps ? "" : "| ",
  4096. ps->ps_cmd
  4097. );
  4098. } while (++ps != psend);
  4099. newline_and_flush(out);
  4100. jp->changed = 0;
  4101. if (jp->state == JOBDONE) {
  4102. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4103. freejob(jp);
  4104. }
  4105. }
  4106. /*
  4107. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4108. * statuses have changed since the last call to showjobs.
  4109. */
  4110. static void
  4111. showjobs(int mode)
  4112. {
  4113. struct job *jp;
  4114. TRACE(("showjobs(0x%x) called\n", mode));
  4115. /* Handle all finished jobs */
  4116. dowait(DOWAIT_NONBLOCK, NULL);
  4117. for (jp = curjob; jp; jp = jp->prev_job) {
  4118. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4119. showjob(jp, mode);
  4120. }
  4121. }
  4122. }
  4123. static int FAST_FUNC
  4124. jobscmd(int argc UNUSED_PARAM, char **argv)
  4125. {
  4126. int mode, m;
  4127. mode = 0;
  4128. while ((m = nextopt("lp")) != '\0') {
  4129. if (m == 'l')
  4130. mode |= SHOW_PIDS;
  4131. else
  4132. mode |= SHOW_ONLY_PGID;
  4133. }
  4134. argv = argptr;
  4135. if (*argv) {
  4136. do
  4137. showjob(getjob(*argv, 0), mode);
  4138. while (*++argv);
  4139. } else {
  4140. showjobs(mode);
  4141. }
  4142. return 0;
  4143. }
  4144. #endif /* JOBS */
  4145. /* Called only on finished or stopped jobs (no members are running) */
  4146. static int
  4147. getstatus(struct job *job)
  4148. {
  4149. int status;
  4150. int retval;
  4151. struct procstat *ps;
  4152. /* Fetch last member's status */
  4153. ps = job->ps + job->nprocs - 1;
  4154. status = ps->ps_status;
  4155. if (pipefail) {
  4156. /* "set -o pipefail" mode: use last _nonzero_ status */
  4157. while (status == 0 && --ps >= job->ps)
  4158. status = ps->ps_status;
  4159. }
  4160. retval = WEXITSTATUS(status);
  4161. if (!WIFEXITED(status)) {
  4162. #if JOBS
  4163. retval = WSTOPSIG(status);
  4164. if (!WIFSTOPPED(status))
  4165. #endif
  4166. {
  4167. /* XXX: limits number of signals */
  4168. retval = WTERMSIG(status);
  4169. #if JOBS
  4170. if (retval == SIGINT)
  4171. job->sigint = 1;
  4172. #endif
  4173. }
  4174. retval |= 128;
  4175. }
  4176. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4177. jobno(job), job->nprocs, status, retval));
  4178. return retval;
  4179. }
  4180. static int FAST_FUNC
  4181. waitcmd(int argc UNUSED_PARAM, char **argv)
  4182. {
  4183. struct job *job;
  4184. int retval;
  4185. struct job *jp;
  4186. #if BASH_WAIT_N
  4187. int status;
  4188. char one = nextopt("n");
  4189. #else
  4190. nextopt(nullstr);
  4191. #endif
  4192. retval = 0;
  4193. argv = argptr;
  4194. if (!argv[0]) {
  4195. /* wait for all jobs / one job if -n */
  4196. for (;;) {
  4197. jp = curjob;
  4198. #if BASH_WAIT_N
  4199. if (one && !jp)
  4200. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4201. retval = 127;
  4202. #endif
  4203. while (1) {
  4204. if (!jp) /* no running procs */
  4205. goto ret;
  4206. if (jp->state == JOBRUNNING)
  4207. break;
  4208. jp->waited = 1;
  4209. jp = jp->prev_job;
  4210. }
  4211. /* man bash:
  4212. * "When bash is waiting for an asynchronous command via
  4213. * the wait builtin, the reception of a signal for which a trap
  4214. * has been set will cause the wait builtin to return immediately
  4215. * with an exit status greater than 128, immediately after which
  4216. * the trap is executed."
  4217. */
  4218. #if BASH_WAIT_N
  4219. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4220. #else
  4221. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4222. #endif
  4223. /* if child sends us a signal *and immediately exits*,
  4224. * dowait() returns pid > 0. Check this case,
  4225. * not "if (dowait() < 0)"!
  4226. */
  4227. if (pending_sig)
  4228. goto sigout;
  4229. #if BASH_WAIT_N
  4230. if (one) {
  4231. /* wait -n waits for one _job_, not one _process_.
  4232. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4233. * should wait for 2 seconds. Not 1 or 3.
  4234. */
  4235. if (status != -1 && !WIFSTOPPED(status)) {
  4236. retval = WEXITSTATUS(status);
  4237. if (WIFSIGNALED(status))
  4238. retval = 128 | WTERMSIG(status);
  4239. goto ret;
  4240. }
  4241. }
  4242. #endif
  4243. }
  4244. }
  4245. retval = 127;
  4246. do {
  4247. if (**argv != '%') {
  4248. pid_t pid = number(*argv);
  4249. job = curjob;
  4250. while (1) {
  4251. if (!job)
  4252. goto repeat;
  4253. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4254. break;
  4255. job = job->prev_job;
  4256. }
  4257. } else {
  4258. job = getjob(*argv, 0);
  4259. }
  4260. /* loop until process terminated or stopped */
  4261. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4262. if (pending_sig)
  4263. goto sigout;
  4264. job->waited = 1;
  4265. retval = getstatus(job);
  4266. repeat: ;
  4267. } while (*++argv);
  4268. ret:
  4269. return retval;
  4270. sigout:
  4271. retval = 128 | pending_sig;
  4272. return retval;
  4273. }
  4274. static struct job *
  4275. growjobtab(void)
  4276. {
  4277. size_t len;
  4278. ptrdiff_t offset;
  4279. struct job *jp, *jq;
  4280. len = njobs * sizeof(*jp);
  4281. jq = jobtab;
  4282. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4283. offset = (char *)jp - (char *)jq;
  4284. if (offset) {
  4285. /* Relocate pointers */
  4286. size_t l = len;
  4287. jq = (struct job *)((char *)jq + l);
  4288. while (l) {
  4289. l -= sizeof(*jp);
  4290. jq--;
  4291. #define joff(p) ((struct job *)((char *)(p) + l))
  4292. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4293. if (joff(jp)->ps == &jq->ps0)
  4294. jmove(joff(jp)->ps);
  4295. if (joff(jp)->prev_job)
  4296. jmove(joff(jp)->prev_job);
  4297. }
  4298. if (curjob)
  4299. jmove(curjob);
  4300. #undef joff
  4301. #undef jmove
  4302. }
  4303. njobs += 4;
  4304. jobtab = jp;
  4305. jp = (struct job *)((char *)jp + len);
  4306. jq = jp + 3;
  4307. do {
  4308. jq->used = 0;
  4309. } while (--jq >= jp);
  4310. return jp;
  4311. }
  4312. /*
  4313. * Return a new job structure.
  4314. * Called with interrupts off.
  4315. */
  4316. static struct job *
  4317. makejob(/*union node *node,*/ int nprocs)
  4318. {
  4319. int i;
  4320. struct job *jp;
  4321. for (i = njobs, jp = jobtab; ; jp++) {
  4322. if (--i < 0) {
  4323. jp = growjobtab();
  4324. break;
  4325. }
  4326. if (jp->used == 0)
  4327. break;
  4328. if (jp->state != JOBDONE || !jp->waited)
  4329. continue;
  4330. #if JOBS
  4331. if (doing_jobctl)
  4332. continue;
  4333. #endif
  4334. freejob(jp);
  4335. break;
  4336. }
  4337. memset(jp, 0, sizeof(*jp));
  4338. #if JOBS
  4339. /* jp->jobctl is a bitfield.
  4340. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4341. if (doing_jobctl)
  4342. jp->jobctl = 1;
  4343. #endif
  4344. jp->prev_job = curjob;
  4345. curjob = jp;
  4346. jp->used = 1;
  4347. jp->ps = &jp->ps0;
  4348. if (nprocs > 1) {
  4349. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4350. }
  4351. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4352. jobno(jp)));
  4353. return jp;
  4354. }
  4355. #if JOBS
  4356. /*
  4357. * Return a string identifying a command (to be printed by the
  4358. * jobs command).
  4359. */
  4360. static char *cmdnextc;
  4361. static void
  4362. cmdputs(const char *s)
  4363. {
  4364. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4365. "", "}", "-", "+", "?", "=",
  4366. "%", "%%", "#", "##"
  4367. IF_BASH_SUBSTR(, ":")
  4368. IF_BASH_PATTERN_SUBST(, "/", "//")
  4369. };
  4370. const char *p, *str;
  4371. char cc[2];
  4372. char *nextc;
  4373. unsigned char c;
  4374. unsigned char subtype = 0;
  4375. int quoted = 0;
  4376. cc[1] = '\0';
  4377. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4378. p = s;
  4379. while ((c = *p++) != '\0') {
  4380. str = NULL;
  4381. switch (c) {
  4382. case CTLESC:
  4383. c = *p++;
  4384. break;
  4385. case CTLVAR:
  4386. subtype = *p++;
  4387. if ((subtype & VSTYPE) == VSLENGTH)
  4388. str = "${#";
  4389. else
  4390. str = "${";
  4391. goto dostr;
  4392. case CTLENDVAR:
  4393. str = "\"}";
  4394. str += !(quoted & 1);
  4395. quoted >>= 1;
  4396. subtype = 0;
  4397. goto dostr;
  4398. #if BASH_PROCESS_SUBST
  4399. case CTLBACKQ:
  4400. c = '$';
  4401. str = "(...)";
  4402. break;
  4403. case CTLTOPROC:
  4404. c = '>';
  4405. str = "(...)";
  4406. break;
  4407. case CTLFROMPROC:
  4408. c = '<';
  4409. str = "(...)";
  4410. break;
  4411. #else
  4412. case CTLBACKQ:
  4413. str = "$(...)";
  4414. goto dostr;
  4415. #endif
  4416. #if ENABLE_FEATURE_SH_MATH
  4417. case CTLARI:
  4418. str = "$((";
  4419. goto dostr;
  4420. case CTLENDARI:
  4421. str = "))";
  4422. goto dostr;
  4423. #endif
  4424. case CTLQUOTEMARK:
  4425. quoted ^= 1;
  4426. c = '"';
  4427. break;
  4428. case '=':
  4429. if (subtype == 0)
  4430. break;
  4431. if ((subtype & VSTYPE) != VSNORMAL)
  4432. quoted <<= 1;
  4433. str = vstype[subtype & VSTYPE];
  4434. if (subtype & VSNUL)
  4435. c = ':';
  4436. else
  4437. goto checkstr;
  4438. break;
  4439. case '\'':
  4440. case '\\':
  4441. case '"':
  4442. case '$':
  4443. /* These can only happen inside quotes */
  4444. cc[0] = c;
  4445. str = cc;
  4446. //FIXME:
  4447. // $ true $$ &
  4448. // $ <cr>
  4449. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4450. c = '\\';
  4451. break;
  4452. default:
  4453. break;
  4454. }
  4455. USTPUTC(c, nextc);
  4456. checkstr:
  4457. if (!str)
  4458. continue;
  4459. dostr:
  4460. while ((c = *str++) != '\0') {
  4461. USTPUTC(c, nextc);
  4462. }
  4463. } /* while *p++ not NUL */
  4464. if (quoted & 1) {
  4465. USTPUTC('"', nextc);
  4466. }
  4467. *nextc = 0;
  4468. cmdnextc = nextc;
  4469. }
  4470. /* cmdtxt() and cmdlist() call each other */
  4471. static void cmdtxt(union node *n);
  4472. static void
  4473. cmdlist(union node *np, int sep)
  4474. {
  4475. for (; np; np = np->narg.next) {
  4476. if (!sep)
  4477. cmdputs(" ");
  4478. cmdtxt(np);
  4479. if (sep && np->narg.next)
  4480. cmdputs(" ");
  4481. }
  4482. }
  4483. static void
  4484. cmdtxt(union node *n)
  4485. {
  4486. union node *np;
  4487. struct nodelist *lp;
  4488. const char *p;
  4489. if (!n)
  4490. return;
  4491. switch (n->type) {
  4492. default:
  4493. #if DEBUG
  4494. abort();
  4495. #endif
  4496. case NPIPE:
  4497. lp = n->npipe.cmdlist;
  4498. for (;;) {
  4499. cmdtxt(lp->n);
  4500. lp = lp->next;
  4501. if (!lp)
  4502. break;
  4503. cmdputs(" | ");
  4504. }
  4505. break;
  4506. case NSEMI:
  4507. p = "; ";
  4508. goto binop;
  4509. case NAND:
  4510. p = " && ";
  4511. goto binop;
  4512. case NOR:
  4513. p = " || ";
  4514. binop:
  4515. cmdtxt(n->nbinary.ch1);
  4516. cmdputs(p);
  4517. n = n->nbinary.ch2;
  4518. goto donode;
  4519. case NREDIR:
  4520. case NBACKGND:
  4521. n = n->nredir.n;
  4522. goto donode;
  4523. case NNOT:
  4524. cmdputs("!");
  4525. n = n->nnot.com;
  4526. donode:
  4527. cmdtxt(n);
  4528. break;
  4529. case NIF:
  4530. cmdputs("if ");
  4531. cmdtxt(n->nif.test);
  4532. cmdputs("; then ");
  4533. if (n->nif.elsepart) {
  4534. cmdtxt(n->nif.ifpart);
  4535. cmdputs("; else ");
  4536. n = n->nif.elsepart;
  4537. } else {
  4538. n = n->nif.ifpart;
  4539. }
  4540. p = "; fi";
  4541. goto dotail;
  4542. case NSUBSHELL:
  4543. cmdputs("(");
  4544. n = n->nredir.n;
  4545. p = ")";
  4546. goto dotail;
  4547. case NWHILE:
  4548. p = "while ";
  4549. goto until;
  4550. case NUNTIL:
  4551. p = "until ";
  4552. until:
  4553. cmdputs(p);
  4554. cmdtxt(n->nbinary.ch1);
  4555. n = n->nbinary.ch2;
  4556. p = "; done";
  4557. dodo:
  4558. cmdputs("; do ");
  4559. dotail:
  4560. cmdtxt(n);
  4561. goto dotail2;
  4562. case NFOR:
  4563. cmdputs("for ");
  4564. cmdputs(n->nfor.var);
  4565. cmdputs(" in ");
  4566. cmdlist(n->nfor.args, 1);
  4567. n = n->nfor.body;
  4568. p = "; done";
  4569. goto dodo;
  4570. case NDEFUN:
  4571. cmdputs(n->ndefun.text);
  4572. p = "() { ... }";
  4573. goto dotail2;
  4574. case NCMD:
  4575. cmdlist(n->ncmd.args, 1);
  4576. cmdlist(n->ncmd.redirect, 0);
  4577. break;
  4578. case NARG:
  4579. p = n->narg.text;
  4580. dotail2:
  4581. cmdputs(p);
  4582. break;
  4583. case NHERE:
  4584. case NXHERE:
  4585. p = "<<...";
  4586. goto dotail2;
  4587. case NCASE:
  4588. cmdputs("case ");
  4589. cmdputs(n->ncase.expr->narg.text);
  4590. cmdputs(" in ");
  4591. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4592. cmdtxt(np->nclist.pattern);
  4593. cmdputs(") ");
  4594. cmdtxt(np->nclist.body);
  4595. cmdputs(";; ");
  4596. }
  4597. p = "esac";
  4598. goto dotail2;
  4599. case NTO:
  4600. p = ">";
  4601. goto redir;
  4602. case NCLOBBER:
  4603. p = ">|";
  4604. goto redir;
  4605. case NAPPEND:
  4606. p = ">>";
  4607. goto redir;
  4608. #if BASH_REDIR_OUTPUT
  4609. case NTO2:
  4610. #endif
  4611. case NTOFD:
  4612. p = ">&";
  4613. goto redir;
  4614. case NFROM:
  4615. p = "<";
  4616. goto redir;
  4617. case NFROMFD:
  4618. p = "<&";
  4619. goto redir;
  4620. case NFROMTO:
  4621. p = "<>";
  4622. redir:
  4623. cmdputs(utoa(n->nfile.fd));
  4624. cmdputs(p);
  4625. if (n->type == NTOFD || n->type == NFROMFD) {
  4626. if (n->ndup.dupfd >= 0)
  4627. cmdputs(utoa(n->ndup.dupfd));
  4628. else
  4629. cmdputs("-");
  4630. break;
  4631. }
  4632. n = n->nfile.fname;
  4633. goto donode;
  4634. }
  4635. }
  4636. static char *
  4637. commandtext(union node *n)
  4638. {
  4639. char *name;
  4640. STARTSTACKSTR(cmdnextc);
  4641. cmdtxt(n);
  4642. name = stackblock();
  4643. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4644. return ckstrdup(name);
  4645. }
  4646. #endif /* JOBS */
  4647. /*
  4648. * Fork off a subshell. If we are doing job control, give the subshell its
  4649. * own process group. Jp is a job structure that the job is to be added to.
  4650. * N is the command that will be evaluated by the child. Both jp and n may
  4651. * be NULL. The mode parameter can be one of the following:
  4652. * FORK_FG - Fork off a foreground process.
  4653. * FORK_BG - Fork off a background process.
  4654. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4655. * process group even if job control is on.
  4656. *
  4657. * When job control is turned off, background processes have their standard
  4658. * input redirected to /dev/null (except for the second and later processes
  4659. * in a pipeline).
  4660. *
  4661. * Called with interrupts off.
  4662. */
  4663. /*
  4664. * Clear traps on a fork.
  4665. */
  4666. static void
  4667. clear_traps(void)
  4668. {
  4669. char **tp;
  4670. INT_OFF;
  4671. for (tp = trap; tp <= &trap[NTRAP_LAST]; tp++) {
  4672. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4673. if (trap_ptr == trap)
  4674. free(*tp);
  4675. /* else: it "belongs" to trap_ptr vector, don't free */
  4676. *tp = NULL;
  4677. if ((tp - trap) != 0 && (tp - trap) < NSIG)
  4678. setsignal(tp - trap);
  4679. }
  4680. }
  4681. may_have_traps = 0;
  4682. INT_ON;
  4683. }
  4684. /* Lives far away from here, needed for forkchild */
  4685. static void closescript(void);
  4686. /* Called after fork(), in child */
  4687. /* jp and n are NULL when called by openhere() for heredoc support */
  4688. static NOINLINE void
  4689. forkchild(struct job *jp, union node *n, int mode)
  4690. {
  4691. int oldlvl;
  4692. TRACE(("Child shell %d\n", getpid()));
  4693. oldlvl = shlvl;
  4694. shlvl++;
  4695. /* man bash: "Non-builtin commands run by bash have signal handlers
  4696. * set to the values inherited by the shell from its parent".
  4697. * Do we do it correctly? */
  4698. closescript();
  4699. if (n && n->type == NCMD /* is it single cmd? */
  4700. /* && n->ncmd.args->type == NARG - always true? */
  4701. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4702. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4703. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4704. ) {
  4705. TRACE(("Trap hack\n"));
  4706. /* Awful hack for `trap` or $(trap).
  4707. *
  4708. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4709. * contains an example where "trap" is executed in a subshell:
  4710. *
  4711. * save_traps=$(trap)
  4712. * ...
  4713. * eval "$save_traps"
  4714. *
  4715. * Standard does not say that "trap" in subshell shall print
  4716. * parent shell's traps. It only says that its output
  4717. * must have suitable form, but then, in the above example
  4718. * (which is not supposed to be normative), it implies that.
  4719. *
  4720. * bash (and probably other shell) does implement it
  4721. * (traps are reset to defaults, but "trap" still shows them),
  4722. * but as a result, "trap" logic is hopelessly messed up:
  4723. *
  4724. * # trap
  4725. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4726. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4727. * # true | trap <--- trap is in subshell - no output (ditto)
  4728. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4729. * trap -- 'echo Ho' SIGWINCH
  4730. * # echo `(trap)` <--- in subshell in subshell - output
  4731. * trap -- 'echo Ho' SIGWINCH
  4732. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4733. * trap -- 'echo Ho' SIGWINCH
  4734. *
  4735. * The rules when to forget and when to not forget traps
  4736. * get really complex and nonsensical.
  4737. *
  4738. * Our solution: ONLY bare $(trap) or `trap` is special.
  4739. */
  4740. /* Save trap handler strings for trap builtin to print */
  4741. trap_ptr = xmemdup(trap, sizeof(trap));
  4742. /* Fall through into clearing traps */
  4743. }
  4744. clear_traps();
  4745. #if JOBS
  4746. /* do job control only in root shell */
  4747. doing_jobctl = 0;
  4748. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4749. pid_t pgrp;
  4750. if (jp->nprocs == 0)
  4751. pgrp = getpid();
  4752. else
  4753. pgrp = jp->ps[0].ps_pid;
  4754. /* this can fail because we are doing it in the parent also */
  4755. setpgid(0, pgrp);
  4756. if (mode == FORK_FG)
  4757. xtcsetpgrp(ttyfd, pgrp);
  4758. setsignal(SIGTSTP);
  4759. setsignal(SIGTTOU);
  4760. } else
  4761. #endif
  4762. if (mode == FORK_BG) {
  4763. /* man bash: "When job control is not in effect,
  4764. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4765. ignoresig(SIGINT);
  4766. ignoresig(SIGQUIT);
  4767. if (jp->nprocs == 0) {
  4768. close(0);
  4769. if (open(bb_dev_null, O_RDONLY) != 0)
  4770. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4771. }
  4772. }
  4773. if (oldlvl == 0) {
  4774. if (iflag) { /* why if iflag only? */
  4775. setsignal(SIGINT);
  4776. setsignal(SIGTERM);
  4777. }
  4778. /* man bash:
  4779. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4780. * commands run by bash have signal handlers
  4781. * set to the values inherited by the shell
  4782. * from its parent".
  4783. * Take care of the second rule: */
  4784. setsignal(SIGQUIT);
  4785. }
  4786. #if JOBS
  4787. if (n && n->type == NCMD
  4788. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4789. ) {
  4790. TRACE(("Job hack\n"));
  4791. /* "jobs": we do not want to clear job list for it,
  4792. * instead we remove only _its_ own_ job from job list
  4793. * (if it has one).
  4794. * This makes "jobs .... | cat" more useful.
  4795. */
  4796. if (jp)
  4797. freejob(curjob);
  4798. return;
  4799. }
  4800. #endif
  4801. for (jp = curjob; jp; jp = jp->prev_job)
  4802. freejob(jp);
  4803. }
  4804. /* Called after fork(), in parent */
  4805. #if !JOBS
  4806. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4807. #endif
  4808. static void
  4809. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4810. {
  4811. TRACE(("In parent shell: child = %d\n", pid));
  4812. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4813. return;
  4814. #if JOBS
  4815. if (mode != FORK_NOJOB && jp->jobctl) {
  4816. int pgrp;
  4817. if (jp->nprocs == 0)
  4818. pgrp = pid;
  4819. else
  4820. pgrp = jp->ps[0].ps_pid;
  4821. /* This can fail because we are doing it in the child also */
  4822. setpgid(pid, pgrp);
  4823. }
  4824. #endif
  4825. if (mode == FORK_BG) {
  4826. backgndpid = pid; /* set $! */
  4827. set_curjob(jp, CUR_RUNNING);
  4828. }
  4829. if (jp) {
  4830. struct procstat *ps = &jp->ps[jp->nprocs++];
  4831. ps->ps_pid = pid;
  4832. ps->ps_status = -1;
  4833. ps->ps_cmd = nullstr;
  4834. #if JOBS
  4835. if (doing_jobctl && n)
  4836. ps->ps_cmd = commandtext(n);
  4837. #endif
  4838. }
  4839. }
  4840. /* jp and n are NULL when called by openhere() for heredoc support */
  4841. static int
  4842. forkshell(struct job *jp, union node *n, int mode)
  4843. {
  4844. int pid;
  4845. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4846. pid = fork();
  4847. if (pid < 0) {
  4848. TRACE(("Fork failed, errno=%d", errno));
  4849. if (jp)
  4850. freejob(jp);
  4851. ash_msg_and_raise_perror("can't fork");
  4852. }
  4853. if (pid == 0) {
  4854. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4855. forkchild(jp, n, mode);
  4856. } else {
  4857. forkparent(jp, n, mode, pid);
  4858. }
  4859. return pid;
  4860. }
  4861. /*
  4862. * Wait for job to finish.
  4863. *
  4864. * Under job control we have the problem that while a child process
  4865. * is running interrupts generated by the user are sent to the child
  4866. * but not to the shell. This means that an infinite loop started by
  4867. * an interactive user may be hard to kill. With job control turned off,
  4868. * an interactive user may place an interactive program inside a loop.
  4869. * If the interactive program catches interrupts, the user doesn't want
  4870. * these interrupts to also abort the loop. The approach we take here
  4871. * is to have the shell ignore interrupt signals while waiting for a
  4872. * foreground process to terminate, and then send itself an interrupt
  4873. * signal if the child process was terminated by an interrupt signal.
  4874. * Unfortunately, some programs want to do a bit of cleanup and then
  4875. * exit on interrupt; unless these processes terminate themselves by
  4876. * sending a signal to themselves (instead of calling exit) they will
  4877. * confuse this approach.
  4878. *
  4879. * Called with interrupts off.
  4880. */
  4881. static int
  4882. waitforjob(struct job *jp)
  4883. {
  4884. int st;
  4885. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4886. /* In non-interactive shells, we _can_ get
  4887. * a keyboard signal here and be EINTRed, but we just loop
  4888. * inside dowait(), waiting for command to complete.
  4889. *
  4890. * man bash:
  4891. * "If bash is waiting for a command to complete and receives
  4892. * a signal for which a trap has been set, the trap
  4893. * will not be executed until the command completes."
  4894. *
  4895. * Reality is that even if trap is not set, bash
  4896. * will not act on the signal until command completes.
  4897. * Try this. sleep5intoff.c:
  4898. * #include <signal.h>
  4899. * #include <unistd.h>
  4900. * int main() {
  4901. * sigset_t set;
  4902. * sigemptyset(&set);
  4903. * sigaddset(&set, SIGINT);
  4904. * sigaddset(&set, SIGQUIT);
  4905. * sigprocmask(SIG_BLOCK, &set, NULL);
  4906. * sleep(5);
  4907. * return 0;
  4908. * }
  4909. * $ bash -c './sleep5intoff; echo hi'
  4910. * ^C^C^C^C <--- pressing ^C once a second
  4911. * $ _
  4912. * $ bash -c './sleep5intoff; echo hi'
  4913. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4914. * $ _
  4915. */
  4916. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4917. if (!jp)
  4918. return exitstatus;
  4919. st = getstatus(jp);
  4920. #if JOBS
  4921. if (jp->jobctl) {
  4922. xtcsetpgrp(ttyfd, rootpid);
  4923. restore_tty_if_stopped_or_signaled(jp);
  4924. /*
  4925. * This is truly gross.
  4926. * If we're doing job control, then we did a TIOCSPGRP which
  4927. * caused us (the shell) to no longer be in the controlling
  4928. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4929. * intuit from the subprocess exit status whether a SIGINT
  4930. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4931. */
  4932. if (jp->sigint) /* TODO: do the same with all signals */
  4933. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4934. }
  4935. if (jp->state == JOBDONE)
  4936. #endif
  4937. freejob(jp);
  4938. return st;
  4939. }
  4940. /*
  4941. * return 1 if there are stopped jobs, otherwise 0
  4942. */
  4943. static int
  4944. stoppedjobs(void)
  4945. {
  4946. struct job *jp;
  4947. int retval;
  4948. retval = 0;
  4949. if (!iflag || job_warning)
  4950. goto out;
  4951. jp = curjob;
  4952. if (jp && jp->state == JOBSTOPPED) {
  4953. out2str("You have stopped jobs.\n");
  4954. job_warning = 2;
  4955. retval++;
  4956. }
  4957. out:
  4958. return retval;
  4959. }
  4960. /*
  4961. * Code for dealing with input/output redirection.
  4962. */
  4963. #undef EMPTY
  4964. #undef CLOSED
  4965. #define EMPTY -2 /* marks an unused slot in redirtab */
  4966. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4967. /*
  4968. * Handle here documents. Normally we fork off a process to write the
  4969. * data to a pipe. If the document is short, we can stuff the data in
  4970. * the pipe without forking.
  4971. */
  4972. /* openhere needs this forward reference */
  4973. static void expandhere(union node *arg);
  4974. static int
  4975. openhere(union node *redir)
  4976. {
  4977. char *p;
  4978. int pip[2];
  4979. size_t len = 0;
  4980. if (pipe(pip) < 0)
  4981. ash_msg_and_raise_perror("can't create pipe");
  4982. p = redir->nhere.doc->narg.text;
  4983. if (redir->type == NXHERE) {
  4984. expandhere(redir->nhere.doc);
  4985. p = stackblock();
  4986. }
  4987. len = strlen(p);
  4988. if (len <= PIPE_BUF) {
  4989. xwrite(pip[1], p, len);
  4990. goto out;
  4991. }
  4992. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4993. /* child */
  4994. close(pip[0]);
  4995. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4996. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4997. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4998. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4999. signal(SIGPIPE, SIG_DFL);
  5000. xwrite(pip[1], p, len);
  5001. _exit_SUCCESS();
  5002. }
  5003. out:
  5004. close(pip[1]);
  5005. return pip[0];
  5006. }
  5007. static int
  5008. openredirect(union node *redir)
  5009. {
  5010. struct stat sb;
  5011. char *fname;
  5012. int f;
  5013. switch (redir->nfile.type) {
  5014. /* Can't happen, our single caller does this itself */
  5015. // case NTOFD:
  5016. // case NFROMFD:
  5017. // return -1;
  5018. case NHERE:
  5019. case NXHERE:
  5020. return openhere(redir);
  5021. }
  5022. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  5023. * allocated space. Do it only when we know it is safe.
  5024. */
  5025. fname = redir->nfile.expfname;
  5026. switch (redir->nfile.type) {
  5027. default:
  5028. #if DEBUG
  5029. abort();
  5030. #endif
  5031. case NFROM:
  5032. f = open(fname, O_RDONLY);
  5033. if (f < 0)
  5034. goto eopen;
  5035. break;
  5036. case NFROMTO:
  5037. f = open(fname, O_RDWR|O_CREAT, 0666);
  5038. if (f < 0)
  5039. goto ecreate;
  5040. break;
  5041. case NTO:
  5042. #if BASH_REDIR_OUTPUT
  5043. case NTO2:
  5044. #endif
  5045. /* Take care of noclobber mode. */
  5046. if (Cflag) {
  5047. if (stat(fname, &sb) < 0) {
  5048. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5049. if (f < 0)
  5050. goto ecreate;
  5051. } else if (!S_ISREG(sb.st_mode)) {
  5052. f = open(fname, O_WRONLY, 0666);
  5053. if (f < 0)
  5054. goto ecreate;
  5055. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5056. close(f);
  5057. errno = EEXIST;
  5058. goto ecreate;
  5059. }
  5060. } else {
  5061. errno = EEXIST;
  5062. goto ecreate;
  5063. }
  5064. break;
  5065. }
  5066. /* FALLTHROUGH */
  5067. case NCLOBBER:
  5068. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5069. if (f < 0)
  5070. goto ecreate;
  5071. break;
  5072. case NAPPEND:
  5073. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5074. if (f < 0)
  5075. goto ecreate;
  5076. break;
  5077. }
  5078. return f;
  5079. ecreate:
  5080. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5081. eopen:
  5082. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5083. }
  5084. /*
  5085. * Copy a file descriptor to be >= 10. Throws exception on error.
  5086. */
  5087. static int
  5088. savefd(int from)
  5089. {
  5090. int newfd;
  5091. int err;
  5092. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5093. err = newfd < 0 ? errno : 0;
  5094. if (err != EBADF) {
  5095. if (err)
  5096. ash_msg_and_raise_perror("%d", from);
  5097. close(from);
  5098. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5099. close_on_exec_on(newfd);
  5100. }
  5101. return newfd;
  5102. }
  5103. static int
  5104. dup2_or_raise(int from, int to)
  5105. {
  5106. int newfd;
  5107. newfd = (from != to) ? dup2(from, to) : to;
  5108. if (newfd < 0) {
  5109. /* Happens when source fd is not open: try "echo >&99" */
  5110. ash_msg_and_raise_perror("%d", from);
  5111. }
  5112. return newfd;
  5113. }
  5114. static int
  5115. dup_CLOEXEC(int fd, int avoid_fd)
  5116. {
  5117. int newfd;
  5118. repeat:
  5119. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5120. if (newfd >= 0) {
  5121. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5122. close_on_exec_on(newfd);
  5123. } else { /* newfd < 0 */
  5124. if (errno == EBUSY)
  5125. goto repeat;
  5126. if (errno == EINTR)
  5127. goto repeat;
  5128. }
  5129. return newfd;
  5130. }
  5131. static int
  5132. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5133. {
  5134. int newfd;
  5135. repeat:
  5136. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5137. if (newfd < 0) {
  5138. if (errno == EBUSY)
  5139. goto repeat;
  5140. if (errno == EINTR)
  5141. goto repeat;
  5142. /* fd was not open? */
  5143. if (errno == EBADF)
  5144. return fd;
  5145. ash_msg_and_raise_perror("%d", newfd);
  5146. }
  5147. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5148. close_on_exec_on(newfd);
  5149. close(fd);
  5150. return newfd;
  5151. }
  5152. /* Struct def and variable are moved down to the first usage site */
  5153. struct squirrel {
  5154. int orig_fd;
  5155. int moved_to;
  5156. };
  5157. struct redirtab {
  5158. struct redirtab *next;
  5159. int pair_count;
  5160. struct squirrel two_fd[];
  5161. };
  5162. #define redirlist (G_var.redirlist)
  5163. static void
  5164. add_squirrel_closed(struct redirtab *sq, int fd)
  5165. {
  5166. int i;
  5167. if (!sq)
  5168. return;
  5169. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5170. /* If we collide with an already moved fd... */
  5171. if (fd == sq->two_fd[i].orig_fd) {
  5172. /* Examples:
  5173. * "echo 3>FILE 3>&- 3>FILE"
  5174. * "echo 3>&- 3>FILE"
  5175. * No need for last redirect to insert
  5176. * another "need to close 3" indicator.
  5177. */
  5178. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5179. return;
  5180. }
  5181. }
  5182. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5183. sq->two_fd[i].orig_fd = fd;
  5184. sq->two_fd[i].moved_to = CLOSED;
  5185. }
  5186. static int
  5187. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5188. {
  5189. int i, new_fd;
  5190. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5191. avoid_fd = 9;
  5192. #if JOBS
  5193. if (fd == ttyfd) {
  5194. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5195. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5196. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5197. return 1; /* "we closed fd" */
  5198. }
  5199. #endif
  5200. /* Are we called from redirect(0)? E.g. redirect
  5201. * in a forked child. No need to save fds,
  5202. * we aren't going to use them anymore, ok to trash.
  5203. */
  5204. if (!sq)
  5205. return 0;
  5206. /* If this one of script's fds? */
  5207. if (fd != 0) {
  5208. struct parsefile *pf = g_parsefile;
  5209. while (pf) {
  5210. /* We skip fd == 0 case because of the following:
  5211. * $ ash # running ash interactively
  5212. * $ . ./script.sh
  5213. * and in script.sh: "exec 9>&0".
  5214. * Even though top-level pf_fd _is_ 0,
  5215. * it's still ok to use it: "read" builtin uses it,
  5216. * why should we cripple "exec" builtin?
  5217. */
  5218. if (fd == pf->pf_fd) {
  5219. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5220. return 1; /* "we closed fd" */
  5221. }
  5222. pf = pf->prev;
  5223. }
  5224. }
  5225. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5226. /* First: do we collide with some already moved fds? */
  5227. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5228. /* If we collide with an already moved fd... */
  5229. if (fd == sq->two_fd[i].moved_to) {
  5230. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5231. sq->two_fd[i].moved_to = new_fd;
  5232. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5233. if (new_fd < 0) /* what? */
  5234. xfunc_die();
  5235. return 0; /* "we did not close fd" */
  5236. }
  5237. if (fd == sq->two_fd[i].orig_fd) {
  5238. /* Example: echo Hello >/dev/null 1>&2 */
  5239. TRACE(("redirect_fd %d: already moved\n", fd));
  5240. return 0; /* "we did not close fd" */
  5241. }
  5242. }
  5243. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5244. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5245. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5246. if (new_fd < 0) {
  5247. if (errno != EBADF)
  5248. xfunc_die();
  5249. /* new_fd = CLOSED; - already is -1 */
  5250. }
  5251. sq->two_fd[i].moved_to = new_fd;
  5252. sq->two_fd[i].orig_fd = fd;
  5253. /* if we move stderr, let "set -x" code know */
  5254. if (fd == preverrout_fd)
  5255. preverrout_fd = new_fd;
  5256. return 0; /* "we did not close fd" */
  5257. }
  5258. static int
  5259. internally_opened_fd(int fd, struct redirtab *sq)
  5260. {
  5261. int i;
  5262. #if JOBS
  5263. if (fd == ttyfd)
  5264. return 1;
  5265. #endif
  5266. /* If this one of script's fds? */
  5267. if (fd != 0) {
  5268. struct parsefile *pf = g_parsefile;
  5269. while (pf) {
  5270. if (fd == pf->pf_fd)
  5271. return 1;
  5272. pf = pf->prev;
  5273. }
  5274. }
  5275. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5276. if (fd == sq->two_fd[i].moved_to)
  5277. return 1;
  5278. }
  5279. return 0;
  5280. }
  5281. /*
  5282. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5283. * old file descriptors are stashed away so that the redirection can be
  5284. * undone by calling popredir.
  5285. */
  5286. /* flags passed to redirect */
  5287. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5288. static void
  5289. redirect(union node *redir, int flags)
  5290. {
  5291. struct redirtab *sv;
  5292. if (!redir)
  5293. return;
  5294. sv = NULL;
  5295. INT_OFF;
  5296. if (flags & REDIR_PUSH)
  5297. sv = redirlist;
  5298. do {
  5299. int fd;
  5300. int newfd;
  5301. int close_fd;
  5302. int closed;
  5303. fd = redir->nfile.fd;
  5304. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5305. //bb_error_msg("doing %d > %d", fd, newfd);
  5306. newfd = redir->ndup.dupfd;
  5307. close_fd = -1;
  5308. } else {
  5309. newfd = openredirect(redir); /* always >= 0 */
  5310. if (fd == newfd) {
  5311. /* open() gave us precisely the fd we wanted.
  5312. * This means that this fd was not busy
  5313. * (not opened to anywhere).
  5314. * Remember to close it on restore:
  5315. */
  5316. add_squirrel_closed(sv, fd);
  5317. continue;
  5318. }
  5319. close_fd = newfd;
  5320. }
  5321. if (fd == newfd)
  5322. continue;
  5323. /* if "N>FILE": move newfd to fd */
  5324. /* if "N>&M": dup newfd to fd */
  5325. /* if "N>&-": close fd (newfd is -1) */
  5326. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5327. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5328. if (newfd == -1) {
  5329. /* "N>&-" means "close me" */
  5330. if (!closed) {
  5331. /* ^^^ optimization: saving may already
  5332. * have closed it. If not... */
  5333. close(fd);
  5334. }
  5335. } else {
  5336. /* if newfd is a script fd or saved fd, simulate EBADF */
  5337. if (internally_opened_fd(newfd, sv)) {
  5338. errno = EBADF;
  5339. ash_msg_and_raise_perror("%d", newfd);
  5340. }
  5341. dup2_or_raise(newfd, fd);
  5342. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5343. close(close_fd);
  5344. #if BASH_REDIR_OUTPUT
  5345. if (redir->nfile.type == NTO2 && fd == 1) {
  5346. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5347. fd = 2;
  5348. newfd = 1;
  5349. close_fd = -1;
  5350. goto redirect_more;
  5351. }
  5352. #endif
  5353. }
  5354. } while ((redir = redir->nfile.next) != NULL);
  5355. INT_ON;
  5356. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5357. #define REDIR_SAVEFD2 0
  5358. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5359. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5360. // not only for calls with flags containing REDIR_SAVEFD2.
  5361. // We do this unconditionally (see save_fd_on_redirect()).
  5362. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5363. // preverrout_fd = copied_fd2;
  5364. }
  5365. static int
  5366. redirectsafe(union node *redir, int flags)
  5367. {
  5368. int err;
  5369. volatile int saveint;
  5370. struct jmploc *volatile savehandler = exception_handler;
  5371. struct jmploc jmploc;
  5372. SAVE_INT(saveint);
  5373. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5374. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5375. if (!err) {
  5376. exception_handler = &jmploc;
  5377. redirect(redir, flags);
  5378. }
  5379. exception_handler = savehandler;
  5380. if (err && exception_type != EXERROR)
  5381. longjmp(exception_handler->loc, 1);
  5382. RESTORE_INT(saveint);
  5383. return err;
  5384. }
  5385. #if BASH_PROCESS_SUBST
  5386. static void
  5387. pushfd(int fd)
  5388. {
  5389. struct redirtab *sv;
  5390. sv = ckzalloc(sizeof(*sv) + sizeof(sv->two_fd[0]));
  5391. sv->pair_count = 1;
  5392. sv->two_fd[0].orig_fd = fd;
  5393. sv->two_fd[0].moved_to = CLOSED;
  5394. sv->next = redirlist;
  5395. redirlist = sv;
  5396. }
  5397. #endif
  5398. static struct redirtab*
  5399. pushredir(union node *redir)
  5400. {
  5401. struct redirtab *sv;
  5402. int i;
  5403. if (!redir)
  5404. return redirlist;
  5405. i = 0;
  5406. do {
  5407. i++;
  5408. #if BASH_REDIR_OUTPUT
  5409. if (redir->nfile.type == NTO2)
  5410. i++;
  5411. #endif
  5412. redir = redir->nfile.next;
  5413. } while (redir);
  5414. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5415. sv->pair_count = i;
  5416. while (--i >= 0)
  5417. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5418. sv->next = redirlist;
  5419. redirlist = sv;
  5420. return sv->next;
  5421. }
  5422. /*
  5423. * Undo the effects of the last redirection.
  5424. */
  5425. static void
  5426. popredir(int drop)
  5427. {
  5428. struct redirtab *rp;
  5429. int i;
  5430. if (redirlist == NULL)
  5431. return;
  5432. INT_OFF;
  5433. rp = redirlist;
  5434. for (i = 0; i < rp->pair_count; i++) {
  5435. int fd = rp->two_fd[i].orig_fd;
  5436. int copy = rp->two_fd[i].moved_to;
  5437. if (copy == CLOSED) {
  5438. if (!drop)
  5439. close(fd);
  5440. continue;
  5441. }
  5442. if (copy != EMPTY) {
  5443. if (!drop) {
  5444. /*close(fd);*/
  5445. dup2_or_raise(copy, fd);
  5446. }
  5447. close(copy);
  5448. }
  5449. }
  5450. redirlist = rp->next;
  5451. free(rp);
  5452. INT_ON;
  5453. }
  5454. static void
  5455. unwindredir(struct redirtab *stop)
  5456. {
  5457. while (redirlist != stop)
  5458. popredir(/*drop:*/ 0);
  5459. }
  5460. /* ============ Routines to expand arguments to commands
  5461. *
  5462. * We have to deal with backquotes, shell variables, and file metacharacters.
  5463. */
  5464. #if ENABLE_FEATURE_SH_MATH
  5465. static arith_t
  5466. ash_arith(const char *s)
  5467. {
  5468. arith_state_t math_state;
  5469. arith_t result;
  5470. math_state.lookupvar = lookupvar;
  5471. math_state.setvar = setvar0;
  5472. //math_state.endofname = endofname;
  5473. INT_OFF;
  5474. result = arith(&math_state, s);
  5475. if (math_state.errmsg)
  5476. ash_msg_and_raise_error(math_state.errmsg);
  5477. INT_ON;
  5478. return result;
  5479. }
  5480. #endif
  5481. #if BASH_SUBSTR
  5482. # if ENABLE_FEATURE_SH_MATH
  5483. static int substr_atoi(const char *s)
  5484. {
  5485. arith_t t = ash_arith(s);
  5486. if (sizeof(t) > sizeof(int)) {
  5487. /* clamp very large or very large negative nums for ${v:N:M}:
  5488. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5489. */
  5490. if (t > INT_MAX)
  5491. t = INT_MAX;
  5492. if (t < INT_MIN)
  5493. t = INT_MIN;
  5494. }
  5495. return t;
  5496. }
  5497. # else
  5498. # define substr_atoi(s) number(s)
  5499. # endif
  5500. #endif
  5501. /*
  5502. * expandarg flags
  5503. */
  5504. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5505. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5506. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5507. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5508. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5509. * POSIX says for this case:
  5510. * Pathname expansion shall not be performed on the word by a
  5511. * non-interactive shell; an interactive shell may perform it, but shall
  5512. * do so only when the expansion would result in one word.
  5513. * Currently, our code complies to the above rule by never globbing
  5514. * redirection filenames.
  5515. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5516. * (this means that on a typical Linux distro, bash almost always
  5517. * performs globbing, and thus diverges from what we do).
  5518. */
  5519. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5520. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5521. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5522. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5523. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5524. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5525. /*
  5526. * rmescape() flags
  5527. */
  5528. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5529. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5530. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5531. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5532. /* Add CTLESC when necessary. */
  5533. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5534. /*
  5535. * Structure specifying which parts of the string should be searched
  5536. * for IFS characters.
  5537. */
  5538. struct ifsregion {
  5539. struct ifsregion *next; /* next region in list */
  5540. int begoff; /* offset of start of region */
  5541. int endoff; /* offset of end of region */
  5542. int nulonly; /* search for nul bytes only */
  5543. };
  5544. struct arglist {
  5545. struct strlist *list;
  5546. struct strlist **lastp;
  5547. };
  5548. /* output of current string */
  5549. static char *expdest;
  5550. /* list of back quote expressions */
  5551. static struct nodelist *argbackq;
  5552. /* first struct in list of ifs regions */
  5553. static struct ifsregion ifsfirst;
  5554. /* last struct in list */
  5555. static struct ifsregion *ifslastp;
  5556. /* holds expanded arg list */
  5557. static struct arglist exparg;
  5558. /*
  5559. * Break the argument string into pieces based upon IFS and add the
  5560. * strings to the argument list. The regions of the string to be
  5561. * searched for IFS characters have been stored by recordregion.
  5562. */
  5563. static void
  5564. ifsbreakup(char *string, struct arglist *arglist)
  5565. {
  5566. struct ifsregion *ifsp;
  5567. struct strlist *sp;
  5568. char *start;
  5569. char *p;
  5570. char *q;
  5571. const char *ifs, *realifs;
  5572. int ifsspc;
  5573. int nulonly;
  5574. start = string;
  5575. if (ifslastp != NULL) {
  5576. ifsspc = 0;
  5577. nulonly = 0;
  5578. realifs = ifsset() ? ifsval() : defifs;
  5579. ifsp = &ifsfirst;
  5580. do {
  5581. int afternul;
  5582. p = string + ifsp->begoff;
  5583. afternul = nulonly;
  5584. nulonly = ifsp->nulonly;
  5585. ifs = nulonly ? nullstr : realifs;
  5586. ifsspc = 0;
  5587. while (p < string + ifsp->endoff) {
  5588. q = p;
  5589. if ((unsigned char)*p == CTLESC)
  5590. p++;
  5591. if (!strchr(ifs, *p)) {
  5592. p++;
  5593. continue;
  5594. }
  5595. if (!(afternul || nulonly))
  5596. ifsspc = (strchr(defifs, *p) != NULL);
  5597. /* Ignore IFS whitespace at start */
  5598. if (q == start && ifsspc) {
  5599. p++;
  5600. start = p;
  5601. continue;
  5602. }
  5603. *q = '\0';
  5604. sp = stzalloc(sizeof(*sp));
  5605. sp->text = start;
  5606. *arglist->lastp = sp;
  5607. arglist->lastp = &sp->next;
  5608. p++;
  5609. if (!nulonly) {
  5610. for (;;) {
  5611. if (p >= string + ifsp->endoff) {
  5612. break;
  5613. }
  5614. q = p;
  5615. if ((unsigned char)*p == CTLESC)
  5616. p++;
  5617. if (strchr(ifs, *p) == NULL) {
  5618. p = q;
  5619. break;
  5620. }
  5621. if (strchr(defifs, *p) == NULL) {
  5622. if (ifsspc) {
  5623. p++;
  5624. ifsspc = 0;
  5625. } else {
  5626. p = q;
  5627. break;
  5628. }
  5629. } else
  5630. p++;
  5631. }
  5632. }
  5633. start = p;
  5634. } /* while */
  5635. ifsp = ifsp->next;
  5636. } while (ifsp != NULL);
  5637. if (nulonly)
  5638. goto add;
  5639. }
  5640. if (!*start)
  5641. return;
  5642. add:
  5643. sp = stzalloc(sizeof(*sp));
  5644. sp->text = start;
  5645. *arglist->lastp = sp;
  5646. arglist->lastp = &sp->next;
  5647. }
  5648. static void
  5649. ifsfree(void)
  5650. {
  5651. struct ifsregion *p = ifsfirst.next;
  5652. if (!p)
  5653. goto out;
  5654. INT_OFF;
  5655. do {
  5656. struct ifsregion *ifsp;
  5657. ifsp = p->next;
  5658. free(p);
  5659. p = ifsp;
  5660. } while (p);
  5661. ifsfirst.next = NULL;
  5662. INT_ON;
  5663. out:
  5664. ifslastp = NULL;
  5665. }
  5666. static size_t
  5667. esclen(const char *start, const char *p)
  5668. {
  5669. size_t esc = 0;
  5670. while (p > start && (unsigned char)*--p == CTLESC) {
  5671. esc++;
  5672. }
  5673. return esc;
  5674. }
  5675. /*
  5676. * Remove any CTLESC characters from a string.
  5677. */
  5678. #if !BASH_PATTERN_SUBST
  5679. #define rmescapes(str, flag, slash_position) \
  5680. rmescapes(str, flag)
  5681. #endif
  5682. static char *
  5683. rmescapes(char *str, int flag, int *slash_position)
  5684. {
  5685. static const char qchars[] ALIGN1 = {
  5686. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5687. char *p, *q, *r;
  5688. unsigned protect_against_glob;
  5689. unsigned globbing;
  5690. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5691. if (!p)
  5692. return str;
  5693. q = p;
  5694. r = str;
  5695. if (flag & RMESCAPE_ALLOC) {
  5696. size_t len = p - str;
  5697. size_t fulllen = len + strlen(p) + 1;
  5698. if (flag & RMESCAPE_GROW) {
  5699. int strloc = str - (char *)stackblock();
  5700. r = makestrspace(fulllen, expdest);
  5701. /* p and str may be invalidated by makestrspace */
  5702. str = (char *)stackblock() + strloc;
  5703. p = str + len;
  5704. } else if (flag & RMESCAPE_HEAP) {
  5705. r = ckmalloc(fulllen);
  5706. } else {
  5707. r = stalloc(fulllen);
  5708. }
  5709. q = r;
  5710. if (len > 0) {
  5711. q = (char *)mempcpy(q, str, len);
  5712. }
  5713. }
  5714. globbing = flag & RMESCAPE_GLOB;
  5715. protect_against_glob = globbing;
  5716. while (*p) {
  5717. if ((unsigned char)*p == CTLQUOTEMARK) {
  5718. // Note: protect_against_glob only affect whether
  5719. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5720. p++;
  5721. protect_against_glob = globbing;
  5722. continue;
  5723. }
  5724. if (*p == '\\') {
  5725. /* naked back slash */
  5726. protect_against_glob = 0;
  5727. goto copy;
  5728. }
  5729. if ((unsigned char)*p == CTLESC) {
  5730. p++;
  5731. #if DEBUG
  5732. if (*p == '\0')
  5733. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5734. #endif
  5735. if (protect_against_glob) {
  5736. /*
  5737. * We used to trust glob() and fnmatch() to eat
  5738. * superfluous escapes (\z where z has no
  5739. * special meaning anyway). But this causes
  5740. * bugs such as string of one greek letter rho
  5741. * (unicode-encoded as two bytes "cf,81")
  5742. * getting encoded as "cf,CTLESC,81"
  5743. * and here, converted to "cf,\,81" -
  5744. * which does not go well with some flavors
  5745. * of fnmatch() in unicode locales
  5746. * (for example, glibc <= 2.22).
  5747. *
  5748. * Lets add "\" only on the chars which need it.
  5749. * Testcases for less obvious chars are shown.
  5750. */
  5751. if (*p == '*'
  5752. || *p == '?'
  5753. || *p == '['
  5754. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5755. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5756. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5757. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5758. /* Some libc support [^negate], that's why "^" also needs love */
  5759. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5760. ) {
  5761. *q++ = '\\';
  5762. }
  5763. }
  5764. }
  5765. #if BASH_PATTERN_SUBST
  5766. else if (slash_position && p == str + *slash_position) {
  5767. /* stop handling globbing */
  5768. globbing = 0;
  5769. *slash_position = q - r;
  5770. slash_position = NULL;
  5771. }
  5772. #endif
  5773. protect_against_glob = globbing;
  5774. copy:
  5775. *q++ = *p++;
  5776. }
  5777. *q = '\0';
  5778. if (flag & RMESCAPE_GROW) {
  5779. expdest = r;
  5780. STADJUST(q - r + 1, expdest);
  5781. }
  5782. return r;
  5783. }
  5784. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5785. /*
  5786. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5787. *
  5788. * Returns an stalloced string.
  5789. */
  5790. static char *
  5791. preglob(const char *pattern, int flag)
  5792. {
  5793. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5794. }
  5795. /*
  5796. * Put a string on the stack.
  5797. */
  5798. static size_t
  5799. memtodest(const char *p, size_t len, int flags)
  5800. {
  5801. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5802. char *q;
  5803. char *s;
  5804. if (!len)
  5805. return 0;
  5806. q = makestrspace(len * 2, expdest);
  5807. s = q;
  5808. do {
  5809. unsigned char c = *p++;
  5810. if (c) {
  5811. if (flags & QUOTES_ESC) {
  5812. int n = SIT(c, syntax);
  5813. if (n == CCTL
  5814. || ((flags & EXP_QUOTED) && n == CBACK)
  5815. ) {
  5816. USTPUTC(CTLESC, q);
  5817. }
  5818. }
  5819. } else if (!(flags & EXP_KEEPNUL))
  5820. continue;
  5821. USTPUTC(c, q);
  5822. } while (--len);
  5823. expdest = q;
  5824. return q - s;
  5825. }
  5826. static size_t
  5827. strtodest(const char *p, int flags)
  5828. {
  5829. size_t len = strlen(p);
  5830. memtodest(p, len, flags);
  5831. return len;
  5832. }
  5833. /*
  5834. * Our own itoa().
  5835. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5836. */
  5837. static int
  5838. cvtnum(arith_t num, int flags)
  5839. {
  5840. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5841. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5842. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5843. char buf[len];
  5844. len = fmtstr(buf, len, ARITH_FMT, num);
  5845. return memtodest(buf, len, flags);
  5846. }
  5847. /*
  5848. * Record the fact that we have to scan this region of the
  5849. * string for IFS characters.
  5850. */
  5851. static void
  5852. recordregion(int start, int end, int nulonly)
  5853. {
  5854. struct ifsregion *ifsp;
  5855. if (ifslastp == NULL) {
  5856. ifsp = &ifsfirst;
  5857. } else {
  5858. INT_OFF;
  5859. ifsp = ckzalloc(sizeof(*ifsp));
  5860. /*ifsp->next = NULL; - ckzalloc did it */
  5861. ifslastp->next = ifsp;
  5862. INT_ON;
  5863. }
  5864. ifslastp = ifsp;
  5865. ifslastp->begoff = start;
  5866. ifslastp->endoff = end;
  5867. ifslastp->nulonly = nulonly;
  5868. }
  5869. static void
  5870. removerecordregions(int endoff)
  5871. {
  5872. if (ifslastp == NULL)
  5873. return;
  5874. if (ifsfirst.endoff > endoff) {
  5875. while (ifsfirst.next) {
  5876. struct ifsregion *ifsp;
  5877. INT_OFF;
  5878. ifsp = ifsfirst.next->next;
  5879. free(ifsfirst.next);
  5880. ifsfirst.next = ifsp;
  5881. INT_ON;
  5882. }
  5883. if (ifsfirst.begoff > endoff) {
  5884. ifslastp = NULL;
  5885. } else {
  5886. ifslastp = &ifsfirst;
  5887. ifsfirst.endoff = endoff;
  5888. }
  5889. return;
  5890. }
  5891. ifslastp = &ifsfirst;
  5892. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5893. ifslastp = ifslastp->next;
  5894. while (ifslastp->next) {
  5895. struct ifsregion *ifsp;
  5896. INT_OFF;
  5897. ifsp = ifslastp->next->next;
  5898. free(ifslastp->next);
  5899. ifslastp->next = ifsp;
  5900. INT_ON;
  5901. }
  5902. if (ifslastp->endoff > endoff)
  5903. ifslastp->endoff = endoff;
  5904. }
  5905. static char *
  5906. exptilde(char *startp, int flag)
  5907. {
  5908. unsigned char c;
  5909. char *name;
  5910. struct passwd *pw;
  5911. const char *home;
  5912. char *p;
  5913. p = startp;
  5914. name = p + 1;
  5915. while ((c = *++p) != '\0') {
  5916. switch (c) {
  5917. case CTLESC:
  5918. return startp;
  5919. case CTLQUOTEMARK:
  5920. return startp;
  5921. case ':':
  5922. if (flag & EXP_VARTILDE)
  5923. goto done;
  5924. break;
  5925. case '/':
  5926. case CTLENDVAR:
  5927. goto done;
  5928. }
  5929. }
  5930. done:
  5931. if (flag & EXP_DISCARD)
  5932. goto out;
  5933. *p = '\0';
  5934. if (*name == '\0') {
  5935. home = lookupvar("HOME");
  5936. } else {
  5937. pw = getpwnam(name);
  5938. home = pw ? pw->pw_dir : NULL;
  5939. }
  5940. *p = c;
  5941. if (!home)
  5942. goto lose;
  5943. strtodest(home, flag | EXP_QUOTED);
  5944. out:
  5945. return p;
  5946. lose:
  5947. return startp;
  5948. }
  5949. /*
  5950. * Execute a command inside back quotes. If it's a builtin command, we
  5951. * want to save its output in a block obtained from malloc. Otherwise
  5952. * we fork off a subprocess and get the output of the command via a pipe.
  5953. * Should be called with interrupts off.
  5954. */
  5955. struct backcmd { /* result of evalbackcmd */
  5956. int fd; /* file descriptor to read from */
  5957. int nleft; /* number of chars in buffer */
  5958. char *buf; /* buffer */
  5959. struct job *jp; /* job structure for command */
  5960. };
  5961. /* These forward decls are needed to use "eval" code for backticks handling: */
  5962. /* flags in argument to evaltree */
  5963. #define EV_EXIT 01 /* exit after evaluating tree */
  5964. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5965. static int evaltree(union node *, int);
  5966. /* An evaltree() which is known to never return.
  5967. * Used to use an alias:
  5968. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5969. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5970. */
  5971. static ALWAYS_INLINE NORETURN void
  5972. evaltreenr(union node *n, int flags)
  5973. {
  5974. evaltree(n, flags);
  5975. bb_unreachable(abort());
  5976. /* NOTREACHED */
  5977. }
  5978. static void FAST_FUNC
  5979. evalbackcmd(union node *n, struct backcmd *result
  5980. IF_BASH_PROCESS_SUBST(, int ctl))
  5981. {
  5982. int pip[2];
  5983. struct job *jp;
  5984. #if BASH_PROCESS_SUBST
  5985. /* determine end of pipe used by parent (ip) and child (ic) */
  5986. const int ip = (ctl == CTLTOPROC);
  5987. const int ic = !(ctl == CTLTOPROC);
  5988. #else
  5989. const int ctl = CTLBACKQ;
  5990. const int ip = 0;
  5991. const int ic = 1;
  5992. #endif
  5993. result->fd = -1;
  5994. result->buf = NULL;
  5995. result->nleft = 0;
  5996. result->jp = NULL;
  5997. if (n == NULL) {
  5998. goto out;
  5999. }
  6000. if (pipe(pip) < 0)
  6001. ash_msg_and_raise_perror("can't create pipe");
  6002. /* process substitution uses NULL job, like openhere() */
  6003. jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
  6004. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  6005. /* child */
  6006. FORCE_INT_ON;
  6007. close(pip[ip]);
  6008. /* ic is index of child end of pipe *and* fd to connect it to */
  6009. if (pip[ic] != ic) {
  6010. /*close(ic);*/
  6011. dup2_or_raise(pip[ic], ic);
  6012. close(pip[ic]);
  6013. }
  6014. /* TODO: eflag clearing makes the following not abort:
  6015. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  6016. * which is what bash does (unless it is in POSIX mode).
  6017. * dash deleted "eflag = 0" line in the commit
  6018. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  6019. * [EVAL] Don't clear eflag in evalbackcmd
  6020. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  6021. */
  6022. eflag = 0;
  6023. ifsfree();
  6024. evaltreenr(n, EV_EXIT);
  6025. /* NOTREACHED */
  6026. }
  6027. /* parent */
  6028. #if BASH_PROCESS_SUBST
  6029. if (ctl != CTLBACKQ) {
  6030. int fd = fcntl(pip[ip], F_DUPFD, 64);
  6031. if (fd > 0) {
  6032. close(pip[ip]);
  6033. pip[ip] = fd;
  6034. }
  6035. pushfd(pip[ip]);
  6036. }
  6037. #endif
  6038. close(pip[ic]);
  6039. result->fd = pip[ip];
  6040. result->jp = jp;
  6041. out:
  6042. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  6043. result->fd, result->buf, result->nleft, result->jp));
  6044. }
  6045. /*
  6046. * Expand stuff in backwards quotes.
  6047. */
  6048. static void
  6049. expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
  6050. {
  6051. #if !BASH_PROCESS_SUBST
  6052. const int ctl = CTLBACKQ;
  6053. #endif
  6054. struct backcmd in;
  6055. int i;
  6056. char buf[128];
  6057. char *p;
  6058. char *dest;
  6059. int startloc;
  6060. struct stackmark smark;
  6061. if (flag & EXP_DISCARD)
  6062. goto out;
  6063. INT_OFF;
  6064. startloc = expdest - (char *)stackblock();
  6065. pushstackmark(&smark, startloc);
  6066. evalbackcmd(cmd, &in IF_BASH_PROCESS_SUBST(, ctl));
  6067. popstackmark(&smark);
  6068. if (ctl != CTLBACKQ) {
  6069. sprintf(buf, DEV_FD_PREFIX"%d", in.fd);
  6070. strtodest(buf, BASESYNTAX);
  6071. goto done;
  6072. }
  6073. p = in.buf;
  6074. i = in.nleft;
  6075. if (i == 0)
  6076. goto read;
  6077. for (;;) {
  6078. memtodest(p, i, flag);
  6079. read:
  6080. if (in.fd < 0)
  6081. break;
  6082. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6083. TRACE(("expbackq: read returns %d\n", i));
  6084. if (i <= 0)
  6085. break;
  6086. p = buf;
  6087. }
  6088. free(in.buf);
  6089. if (in.fd >= 0) {
  6090. close(in.fd);
  6091. back_exitstatus = waitforjob(in.jp);
  6092. }
  6093. done:
  6094. INT_ON;
  6095. /* Eat all trailing newlines */
  6096. dest = expdest;
  6097. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6098. STUNPUTC(dest);
  6099. expdest = dest;
  6100. if (!(flag & EXP_QUOTED))
  6101. recordregion(startloc, dest - (char *)stackblock(), 0);
  6102. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6103. (int)((dest - (char *)stackblock()) - startloc),
  6104. (int)((dest - (char *)stackblock()) - startloc),
  6105. stackblock() + startloc));
  6106. out:
  6107. argbackq = argbackq->next;
  6108. }
  6109. /* expari needs it */
  6110. static char *argstr(char *p, int flag);
  6111. #if ENABLE_FEATURE_SH_MATH
  6112. /*
  6113. * Expand arithmetic expression. Backup to start of expression,
  6114. * evaluate, place result in (backed up) result, adjust string position.
  6115. */
  6116. static char *
  6117. expari(char *start, int flag)
  6118. {
  6119. struct stackmark sm;
  6120. int begoff;
  6121. int endoff;
  6122. int len;
  6123. arith_t result;
  6124. char *p;
  6125. p = stackblock();
  6126. begoff = expdest - p;
  6127. p = argstr(start, flag & EXP_DISCARD);
  6128. if (flag & EXP_DISCARD)
  6129. goto out;
  6130. start = stackblock();
  6131. endoff = expdest - start;
  6132. start += begoff;
  6133. STADJUST(start - expdest, expdest);
  6134. removerecordregions(begoff);
  6135. if (flag & QUOTES_ESC)
  6136. rmescapes(start, 0, NULL);
  6137. pushstackmark(&sm, endoff);
  6138. result = ash_arith(start);
  6139. popstackmark(&sm);
  6140. len = cvtnum(result, flag);
  6141. if (!(flag & EXP_QUOTED))
  6142. recordregion(begoff, begoff + len, 0);
  6143. out:
  6144. return p;
  6145. }
  6146. #endif
  6147. /* argstr needs it */
  6148. static char *evalvar(char *p, int flags);
  6149. /*
  6150. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6151. * characters to allow for further processing. Otherwise treat
  6152. * $@ like $* since no splitting will be performed.
  6153. */
  6154. static char *
  6155. argstr(char *p, int flag)
  6156. {
  6157. static const char spclchars[] ALIGN1 = {
  6158. '=',
  6159. ':',
  6160. CTLQUOTEMARK,
  6161. CTLENDVAR,
  6162. CTLESC,
  6163. CTLVAR,
  6164. CTLBACKQ,
  6165. #if BASH_PROCESS_SUBST
  6166. CTLTOPROC,
  6167. CTLFROMPROC,
  6168. #endif
  6169. #if ENABLE_FEATURE_SH_MATH
  6170. CTLARI,
  6171. CTLENDARI,
  6172. #endif
  6173. '\0'
  6174. };
  6175. const char *reject = spclchars;
  6176. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6177. int inquotes;
  6178. size_t length;
  6179. int startloc;
  6180. reject += !!(flag & EXP_VARTILDE2);
  6181. reject += flag & EXP_VARTILDE ? 0 : 2;
  6182. inquotes = 0;
  6183. length = 0;
  6184. if (flag & EXP_TILDE) {
  6185. flag &= ~EXP_TILDE;
  6186. tilde:
  6187. if (*p == '~')
  6188. p = exptilde(p, flag);
  6189. }
  6190. start:
  6191. startloc = expdest - (char *)stackblock();
  6192. for (;;) {
  6193. int end;
  6194. unsigned char c;
  6195. length += strcspn(p + length, reject);
  6196. end = 0;
  6197. c = p[length];
  6198. if (!(c & 0x80)
  6199. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6200. || c == CTLENDVAR
  6201. ) {
  6202. /*
  6203. * c == '=' || c == ':' || c == '\0' ||
  6204. * c == CTLENDARI || c == CTLENDVAR
  6205. */
  6206. length++;
  6207. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6208. end = !!((c - 1) & 0x80);
  6209. }
  6210. if (length > 0 && !(flag & EXP_DISCARD)) {
  6211. int newloc;
  6212. char *q;
  6213. q = stnputs(p, length, expdest);
  6214. q[-1] &= end - 1;
  6215. expdest = q - (flag & EXP_WORD ? end : 0);
  6216. newloc = q - (char *)stackblock() - end;
  6217. if (breakall && !inquotes && newloc > startloc) {
  6218. recordregion(startloc, newloc, 0);
  6219. }
  6220. startloc = newloc;
  6221. }
  6222. p += length + 1;
  6223. length = 0;
  6224. if (end)
  6225. break;
  6226. switch (c) {
  6227. case '=':
  6228. flag |= EXP_VARTILDE2;
  6229. reject++;
  6230. /* fall through */
  6231. case ':':
  6232. /*
  6233. * sort of a hack - expand tildes in variable
  6234. * assignments (after the first '=' and after ':'s).
  6235. */
  6236. if (*--p == '~') {
  6237. goto tilde;
  6238. }
  6239. continue;
  6240. case CTLQUOTEMARK:
  6241. /* "$@" syntax adherence hack */
  6242. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6243. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6244. goto start;
  6245. }
  6246. inquotes ^= EXP_QUOTED;
  6247. addquote:
  6248. if (flag & QUOTES_ESC) {
  6249. p--;
  6250. length++;
  6251. startloc++;
  6252. }
  6253. break;
  6254. case CTLESC:
  6255. startloc++;
  6256. length++;
  6257. goto addquote;
  6258. case CTLVAR:
  6259. TRACE(("argstr: evalvar('%s')\n", p));
  6260. p = evalvar(p, flag | inquotes);
  6261. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6262. goto start;
  6263. #if BASH_PROCESS_SUBST
  6264. case CTLTOPROC:
  6265. case CTLFROMPROC:
  6266. #endif
  6267. case CTLBACKQ:
  6268. expbackq(argbackq->n, flag | inquotes IF_BASH_PROCESS_SUBST(, c));
  6269. goto start;
  6270. #if ENABLE_FEATURE_SH_MATH
  6271. case CTLARI:
  6272. p = expari(p, flag | inquotes);
  6273. goto start;
  6274. #endif
  6275. }
  6276. }
  6277. return p - 1;
  6278. }
  6279. static char *
  6280. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6281. char *pattern, int quotes, int zero)
  6282. {
  6283. char *loc, *loc2;
  6284. char c;
  6285. loc = startp;
  6286. loc2 = rmesc;
  6287. do {
  6288. int match;
  6289. const char *s = loc2;
  6290. c = *loc2;
  6291. if (zero) {
  6292. *loc2 = '\0';
  6293. s = rmesc;
  6294. }
  6295. match = pmatch(pattern, s);
  6296. *loc2 = c;
  6297. if (match)
  6298. return loc;
  6299. if (quotes && (unsigned char)*loc == CTLESC)
  6300. loc++;
  6301. loc++;
  6302. loc2++;
  6303. } while (c);
  6304. return NULL;
  6305. }
  6306. static char *
  6307. scanright(char *startp, char *rmesc, char *rmescend,
  6308. char *pattern, int quotes, int match_at_start)
  6309. {
  6310. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6311. int try2optimize = match_at_start;
  6312. #endif
  6313. int esc = 0;
  6314. char *loc;
  6315. char *loc2;
  6316. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6317. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6318. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6319. * Logic:
  6320. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6321. * and on each iteration they go back two/one char until they reach the beginning.
  6322. * We try to match "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6323. * If one of these matches, return pointer past last matched char in startp.
  6324. */
  6325. /* TODO: document in what other circumstances we are called. */
  6326. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6327. int match;
  6328. char c = *loc2;
  6329. const char *s = loc2;
  6330. if (match_at_start) {
  6331. *loc2 = '\0';
  6332. s = rmesc;
  6333. }
  6334. match = pmatch(pattern, s);
  6335. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6336. *loc2 = c;
  6337. if (match)
  6338. return loc;
  6339. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6340. if (try2optimize) {
  6341. /* Maybe we can optimize this:
  6342. * if pattern ends with unescaped *, we can avoid checking
  6343. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6344. * it won't match truncated "raw_value_of_" strings too.
  6345. */
  6346. unsigned plen = strlen(pattern);
  6347. /* Does it end with "*"? */
  6348. if (plen != 0 && pattern[--plen] == '*') {
  6349. /* "xxxx*" is not escaped */
  6350. /* "xxx\*" is escaped */
  6351. /* "xx\\*" is not escaped */
  6352. /* "x\\\*" is escaped */
  6353. int slashes = 0;
  6354. while (plen != 0 && pattern[--plen] == '\\')
  6355. slashes++;
  6356. if (!(slashes & 1))
  6357. break; /* ends with unescaped "*" */
  6358. }
  6359. try2optimize = 0;
  6360. }
  6361. #endif
  6362. loc--;
  6363. if (quotes) {
  6364. if (--esc < 0) {
  6365. esc = esclen(startp, loc);
  6366. }
  6367. if (esc % 2) {
  6368. esc--;
  6369. loc--;
  6370. }
  6371. }
  6372. }
  6373. return NULL;
  6374. }
  6375. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6376. static void
  6377. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6378. {
  6379. const char *msg;
  6380. const char *tail;
  6381. tail = nullstr;
  6382. msg = "parameter not set";
  6383. if (umsg) {
  6384. if ((unsigned char)*end == CTLENDVAR) {
  6385. if (varflags & VSNUL)
  6386. tail = " or null";
  6387. } else {
  6388. msg = umsg;
  6389. }
  6390. }
  6391. ifsfree();
  6392. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6393. }
  6394. static char *
  6395. subevalvar(char *start, char *str, int strloc,
  6396. int startloc, int varflags, int flag)
  6397. {
  6398. int subtype = varflags & VSTYPE;
  6399. int quotes = flag & QUOTES_ESC;
  6400. char *startp;
  6401. char *loc;
  6402. char *rmesc, *rmescend;
  6403. long amount;
  6404. int resetloc;
  6405. int argstr_flags;
  6406. IF_BASH_PATTERN_SUBST(int workloc;)
  6407. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6408. IF_BASH_PATTERN_SUBST(char *repl;)
  6409. int zero;
  6410. char *(*scan)(char*, char*, char*, char*, int, int);
  6411. char *p;
  6412. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6413. // start, str, strloc, startloc, varflags, quotes);
  6414. #if BASH_PATTERN_SUBST
  6415. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6416. * argstr() call expands possible variable references in pattern:
  6417. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6418. */
  6419. repl = NULL;
  6420. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6421. /* Find '/' and replace with NUL */
  6422. repl = start;
  6423. /* The pattern can't be empty.
  6424. * IOW: if the first char after "${v//" is a slash,
  6425. * it does not terminate the pattern - it's the first char of the pattern:
  6426. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6427. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6428. */
  6429. if (*repl == '/')
  6430. repl++;
  6431. for (;;) {
  6432. if (*repl == '\0') {
  6433. repl = NULL;
  6434. break;
  6435. }
  6436. /* Skip over quoted 'str'. Example: ${var/'/'} - second / is not a separator */
  6437. if ((unsigned char)*repl == CTLQUOTEMARK) {
  6438. while ((unsigned char)*++repl != CTLQUOTEMARK)
  6439. continue;
  6440. }
  6441. if (*repl == '/') {
  6442. *repl = '\0';
  6443. break;
  6444. }
  6445. if ((unsigned char)*repl == CTLENDVAR) { /* ${v/pattern} (no trailing /, no repl) */
  6446. repl = NULL;
  6447. break;
  6448. }
  6449. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6450. if ((unsigned char)*repl == CTLESC && repl[1])
  6451. repl++;
  6452. repl++;
  6453. }
  6454. }
  6455. #endif
  6456. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6457. if (!str
  6458. #if BASH_SUBSTR
  6459. && subtype != VSSUBSTR
  6460. #endif
  6461. ) {
  6462. /* EXP_CASE keeps CTLESC's */
  6463. argstr_flags |= EXP_CASE;
  6464. }
  6465. p = argstr(start, argstr_flags);
  6466. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6467. #if BASH_PATTERN_SUBST
  6468. slash_pos = -1;
  6469. if (repl) {
  6470. slash_pos = expdest - ((char *)stackblock() + strloc);
  6471. if (!(flag & EXP_DISCARD))
  6472. STPUTC('/', expdest);
  6473. //bb_error_msg("repl+1:'%s'", repl + 1);
  6474. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6475. *repl = '/';
  6476. }
  6477. #endif
  6478. if (flag & EXP_DISCARD)
  6479. return p;
  6480. startp = (char *)stackblock() + startloc;
  6481. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6482. switch (subtype) {
  6483. case VSASSIGN:
  6484. setvar0(str, startp);
  6485. loc = startp;
  6486. goto out;
  6487. case VSQUESTION:
  6488. varunset(start, str, startp, varflags);
  6489. /* NOTREACHED */
  6490. #if BASH_SUBSTR
  6491. case VSSUBSTR: {
  6492. int pos, len, orig_len;
  6493. char *colon;
  6494. char *vstr;
  6495. loc = vstr = stackblock() + strloc;
  6496. /* Read POS in ${var:POS:LEN} */
  6497. colon = strchr(loc, ':');
  6498. if (colon) *colon = '\0';
  6499. pos = substr_atoi(loc);
  6500. if (colon) *colon = ':';
  6501. /* Read LEN in ${var:POS:LEN} */
  6502. len = vstr - startp - 1;
  6503. /* *loc != '\0', guaranteed by parser */
  6504. if (quotes) {
  6505. char *ptr;
  6506. /* Adjust the length by the number of escapes */
  6507. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6508. if ((unsigned char)*ptr == CTLESC) {
  6509. len--;
  6510. ptr++;
  6511. }
  6512. }
  6513. }
  6514. orig_len = len;
  6515. if (*loc++ == ':') {
  6516. /* ${var::LEN} */
  6517. len = substr_atoi(loc);
  6518. } else {
  6519. /* Skip POS in ${var:POS:LEN} */
  6520. len = orig_len;
  6521. while (*loc && *loc != ':')
  6522. loc++;
  6523. if (*loc++ == ':')
  6524. len = substr_atoi(loc);
  6525. }
  6526. if (pos < 0) {
  6527. /* ${VAR:$((-n)):l} starts n chars from the end */
  6528. pos = orig_len + pos;
  6529. }
  6530. if ((unsigned)pos >= orig_len) {
  6531. /* apart from obvious ${VAR:999999:l},
  6532. * covers ${VAR:$((-9999999)):l} - result is ""
  6533. * (bash compat)
  6534. */
  6535. pos = 0;
  6536. len = 0;
  6537. }
  6538. if (len < 0) {
  6539. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6540. len = (orig_len - pos) + len;
  6541. }
  6542. if ((unsigned)len > (orig_len - pos))
  6543. len = orig_len - pos;
  6544. if (!quotes) {
  6545. /* want: loc = mempcpy(startp, startp + pos, len)
  6546. * but it does not allow overlapping arguments */
  6547. loc = startp;
  6548. while (--len >= 0) {
  6549. *loc = loc[pos];
  6550. loc++;
  6551. }
  6552. } else {
  6553. for (vstr = startp; pos != 0; pos--) {
  6554. if ((unsigned char)*vstr == CTLESC)
  6555. vstr++;
  6556. vstr++;
  6557. }
  6558. for (loc = startp; len != 0; len--) {
  6559. if ((unsigned char)*vstr == CTLESC)
  6560. *loc++ = *vstr++;
  6561. *loc++ = *vstr++;
  6562. }
  6563. }
  6564. *loc = '\0';
  6565. goto out;
  6566. }
  6567. #endif /* BASH_SUBSTR */
  6568. }
  6569. resetloc = expdest - (char *)stackblock();
  6570. #if BASH_PATTERN_SUBST
  6571. repl = NULL;
  6572. /* We'll comeback here if we grow the stack while handling
  6573. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6574. * stack will need rebasing, and we'll need to remove our work
  6575. * areas each time
  6576. */
  6577. restart:
  6578. #endif
  6579. amount = expdest - ((char *)stackblock() + resetloc);
  6580. STADJUST(-amount, expdest);
  6581. startp = (char *)stackblock() + startloc;
  6582. rmesc = startp;
  6583. rmescend = (char *)stackblock() + strloc;
  6584. //bb_error_msg("str7:'%s'", rmescend);
  6585. if (quotes) {
  6586. //TODO: how to handle slash_pos here if string changes (shortens?)
  6587. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6588. if (rmesc != startp) {
  6589. rmescend = expdest;
  6590. startp = (char *)stackblock() + startloc;
  6591. }
  6592. }
  6593. rmescend--;
  6594. str = (char *)stackblock() + strloc;
  6595. /*
  6596. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6597. * The result is a_\_z_c (not a\_\_z_c)!
  6598. *
  6599. * The search pattern and replace string treat backslashes differently!
  6600. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6601. * and string. It's only used on the first call.
  6602. */
  6603. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6604. rmescapes(str, RMESCAPE_GLOB,
  6605. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6606. );
  6607. #if BASH_PATTERN_SUBST
  6608. workloc = expdest - (char *)stackblock();
  6609. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6610. size_t no_meta_len, first_escaped;
  6611. int len;
  6612. char *idx, *end;
  6613. if (!repl) {
  6614. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6615. repl = nullstr;
  6616. if (slash_pos >= 0) {
  6617. repl = str + slash_pos;
  6618. *repl++ = '\0';
  6619. }
  6620. }
  6621. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6622. /* If there's no pattern to match, return the expansion unmolested */
  6623. if (str[0] == '\0')
  6624. goto out1;
  6625. first_escaped = (str[0] == '\\' && str[1]);
  6626. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6627. * as literal too (as it is semi-common, and easy to accomodate
  6628. * by just using str + 1).
  6629. */
  6630. no_meta_len = strpbrk(str + first_escaped * 2, "*?[\\") ? 0 : strlen(str);
  6631. len = 0;
  6632. idx = startp;
  6633. end = str - 1;
  6634. while (idx <= end) {
  6635. try_to_match:
  6636. if (no_meta_len == 0) {
  6637. /* pattern has meta chars, have to glob */
  6638. loc = scanright(idx, rmesc, rmescend, str, quotes, /*match_at_start:*/ 1);
  6639. } else {
  6640. /* Testcase for very slow replace (performs about 22k replaces):
  6641. * x=::::::::::::::::::::::
  6642. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6643. * echo "${x//:/|}"
  6644. * To test "first_escaped" logic, replace : with *.
  6645. */
  6646. if (strncmp(rmesc, str + first_escaped, no_meta_len - first_escaped) != 0)
  6647. goto no_match;
  6648. loc = idx;
  6649. if (!quotes) {
  6650. loc += no_meta_len - first_escaped;
  6651. } else {
  6652. size_t n = no_meta_len - first_escaped;
  6653. do {
  6654. if ((unsigned char)*loc == CTLESC)
  6655. loc++;
  6656. loc++;
  6657. } while (--n != 0);
  6658. }
  6659. }
  6660. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6661. if (!loc) {
  6662. char *restart_detect;
  6663. no_match:
  6664. /* No match, advance */
  6665. restart_detect = stackblock();
  6666. skip_matching:
  6667. if (idx >= end)
  6668. break;
  6669. STPUTC(*idx, expdest);
  6670. if (stackblock() != restart_detect)
  6671. goto restart;
  6672. if (quotes && (unsigned char)*idx == CTLESC) {
  6673. idx++;
  6674. len++;
  6675. STPUTC(*idx, expdest);
  6676. if (stackblock() != restart_detect)
  6677. goto restart;
  6678. }
  6679. idx++;
  6680. len++;
  6681. rmesc++;
  6682. /* continue; - prone to quadratic behavior, smarter code: */
  6683. if (str[0] == '*') {
  6684. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6685. * it would never match "ong_string" etc, no point in trying.
  6686. */
  6687. goto skip_matching;
  6688. }
  6689. goto try_to_match;
  6690. }
  6691. if (subtype == VSREPLACEALL) {
  6692. while (idx < loc) {
  6693. if (quotes && (unsigned char)*idx == CTLESC)
  6694. idx++;
  6695. idx++;
  6696. rmesc++;
  6697. }
  6698. } else {
  6699. idx = loc;
  6700. }
  6701. /* The STPUTC invocations above may resize and move the
  6702. * stack via realloc(3). Since repl is a pointer into the
  6703. * stack, we need to reconstruct it relative to stackblock().
  6704. */
  6705. if (slash_pos >= 0)
  6706. repl = (char *)stackblock() + strloc + slash_pos + 1;
  6707. //bb_error_msg("repl:'%s'", repl);
  6708. for (loc = (char*)repl; *loc; loc++) {
  6709. char *restart_detect = stackblock();
  6710. if (quotes && *loc == '\\') {
  6711. STPUTC(CTLESC, expdest);
  6712. if (stackblock() != restart_detect)
  6713. goto restart;
  6714. len++;
  6715. }
  6716. STPUTC(*loc, expdest);
  6717. if (stackblock() != restart_detect)
  6718. goto restart;
  6719. len++;
  6720. }
  6721. if (subtype == VSREPLACE) {
  6722. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6723. while (*idx) {
  6724. char *restart_detect = stackblock();
  6725. STPUTC(*idx, expdest);
  6726. if (stackblock() != restart_detect)
  6727. goto restart;
  6728. len++;
  6729. idx++;
  6730. }
  6731. break;
  6732. }
  6733. }
  6734. /* We've put the replaced text into a buffer at workloc, now
  6735. * move it to the right place and adjust the stack.
  6736. */
  6737. STPUTC('\0', expdest);
  6738. startp = (char *)stackblock() + startloc;
  6739. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6740. //bb_error_msg("startp:'%s'", startp);
  6741. loc = startp + len;
  6742. goto out;
  6743. }
  6744. #endif /* BASH_PATTERN_SUBST */
  6745. subtype -= VSTRIMRIGHT;
  6746. #if DEBUG
  6747. if (subtype < 0 || subtype > 7)
  6748. abort();
  6749. #endif
  6750. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6751. zero = subtype >> 1;
  6752. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6753. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6754. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6755. if (loc) {
  6756. if (zero) {
  6757. memmove(startp, loc, str - loc);
  6758. loc = startp + (str - loc) - 1;
  6759. }
  6760. *loc = '\0';
  6761. } else
  6762. loc = str - 1;
  6763. out:
  6764. amount = loc - expdest;
  6765. STADJUST(amount, expdest);
  6766. #if BASH_PATTERN_SUBST
  6767. out1:
  6768. #endif
  6769. /* Remove any recorded regions beyond start of variable */
  6770. removerecordregions(startloc);
  6771. return p;
  6772. }
  6773. /*
  6774. * Add the value of a specialized variable to the stack string.
  6775. * name parameter (examples):
  6776. * ash -c 'echo $1' name:'1='
  6777. * ash -c 'echo $qwe' name:'qwe='
  6778. * ash -c 'echo $$' name:'$='
  6779. * ash -c 'echo ${$}' name:'$='
  6780. * ash -c 'echo ${$##q}' name:'$=q'
  6781. * ash -c 'echo ${#$}' name:'$='
  6782. * note: examples with bad shell syntax:
  6783. * ash -c 'echo ${#$1}' name:'$=1'
  6784. * ash -c 'echo ${#1#}' name:'1=#'
  6785. */
  6786. static NOINLINE ssize_t
  6787. varvalue(char *name, int varflags, int flags, int quoted)
  6788. {
  6789. const char *p;
  6790. int num;
  6791. int i;
  6792. ssize_t len = 0;
  6793. int sep;
  6794. int subtype = varflags & VSTYPE;
  6795. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6796. if (!subtype) {
  6797. if (discard)
  6798. return -1;
  6799. ifsfree();
  6800. raise_error_syntax("bad substitution");
  6801. }
  6802. flags |= EXP_KEEPNUL;
  6803. flags &= discard ? ~QUOTES_ESC : ~0;
  6804. sep = (flags & EXP_FULL) << CHAR_BIT;
  6805. switch (*name) {
  6806. case '$':
  6807. num = rootpid;
  6808. goto numvar;
  6809. case '?':
  6810. num = exitstatus;
  6811. goto numvar;
  6812. case '#':
  6813. num = shellparam.nparam;
  6814. goto numvar;
  6815. case '!':
  6816. num = backgndpid;
  6817. if (num == 0)
  6818. return -1;
  6819. numvar:
  6820. len = cvtnum(num, flags);
  6821. goto check_1char_name;
  6822. case '-':
  6823. expdest = makestrspace(NOPTS, expdest);
  6824. for (i = NOPTS - 1; i >= 0; i--) {
  6825. if (optlist[i] && optletters(i)) {
  6826. USTPUTC(optletters(i), expdest);
  6827. len++;
  6828. }
  6829. }
  6830. check_1char_name:
  6831. #if 0
  6832. /* handles cases similar to ${#$1} */
  6833. if (name[2] != '\0')
  6834. raise_error_syntax("bad substitution");
  6835. #endif
  6836. break;
  6837. case '@':
  6838. if (quoted && sep)
  6839. goto param;
  6840. /* fall through */
  6841. case '*': {
  6842. char **ap;
  6843. char sepc;
  6844. char c;
  6845. /* We will set c to 0 or ~0 depending on whether
  6846. * we're doing field splitting. We won't do field
  6847. * splitting if either we're quoted or sep is zero.
  6848. *
  6849. * Instead of testing (quoted || !sep) the following
  6850. * trick optimises away any branches by using the
  6851. * fact that EXP_QUOTED (which is the only bit that
  6852. * can be set in quoted) is the same as EXP_FULL <<
  6853. * CHAR_BIT (which is the only bit that can be set
  6854. * in sep).
  6855. */
  6856. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6857. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6858. #endif
  6859. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6860. sep &= ~quoted;
  6861. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6862. param:
  6863. sepc = sep;
  6864. ap = shellparam.p;
  6865. if (!ap)
  6866. return -1;
  6867. while ((p = *ap++) != NULL) {
  6868. len += strtodest(p, flags);
  6869. if (*ap && sep) {
  6870. len++;
  6871. memtodest(&sepc, 1, flags);
  6872. }
  6873. }
  6874. break;
  6875. } /* case '*' */
  6876. case '0':
  6877. case '1':
  6878. case '2':
  6879. case '3':
  6880. case '4':
  6881. case '5':
  6882. case '6':
  6883. case '7':
  6884. case '8':
  6885. case '9':
  6886. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6887. if (num < 0 || num > shellparam.nparam)
  6888. return -1;
  6889. p = num ? shellparam.p[num - 1] : arg0;
  6890. goto value;
  6891. default:
  6892. /* NB: name has form "VAR=..." */
  6893. p = lookupvar(name);
  6894. value:
  6895. if (!p)
  6896. return -1;
  6897. len = strtodest(p, flags);
  6898. #if ENABLE_UNICODE_SUPPORT
  6899. if (subtype == VSLENGTH && len > 0) {
  6900. reinit_unicode_for_ash();
  6901. if (unicode_status == UNICODE_ON) {
  6902. STADJUST(-len, expdest);
  6903. discard = 0;
  6904. len = unicode_strlen(p);
  6905. }
  6906. }
  6907. #endif
  6908. break;
  6909. }
  6910. if (discard)
  6911. STADJUST(-len, expdest);
  6912. return len;
  6913. }
  6914. /*
  6915. * Expand a variable, and return a pointer to the next character in the
  6916. * input string.
  6917. */
  6918. static char *
  6919. evalvar(char *p, int flag)
  6920. {
  6921. char varflags;
  6922. char subtype;
  6923. char *var;
  6924. int patloc;
  6925. int startloc;
  6926. ssize_t varlen;
  6927. int discard;
  6928. int quoted;
  6929. varflags = (unsigned char) *p++;
  6930. subtype = varflags & VSTYPE;
  6931. quoted = flag & EXP_QUOTED;
  6932. var = p;
  6933. startloc = expdest - (char *)stackblock();
  6934. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6935. again:
  6936. varlen = varvalue(var, varflags, flag, quoted);
  6937. if (varflags & VSNUL)
  6938. varlen--;
  6939. discard = varlen < 0 ? EXP_DISCARD : 0;
  6940. switch (subtype) {
  6941. case VSPLUS:
  6942. discard ^= EXP_DISCARD;
  6943. /* fall through */
  6944. case 0:
  6945. case VSMINUS:
  6946. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6947. goto record;
  6948. case VSASSIGN:
  6949. case VSQUESTION:
  6950. p = subevalvar(p, var, 0, startloc, varflags,
  6951. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6952. if ((flag | ~discard) & EXP_DISCARD)
  6953. goto record;
  6954. varflags &= ~VSNUL;
  6955. subtype = VSNORMAL;
  6956. goto again;
  6957. }
  6958. if ((discard & ~flag) && uflag)
  6959. varunset(p, var, 0, 0);
  6960. if (subtype == VSLENGTH) {
  6961. p++;
  6962. if (flag & EXP_DISCARD)
  6963. return p;
  6964. cvtnum(varlen > 0 ? varlen : 0, flag);
  6965. goto really_record;
  6966. }
  6967. if (subtype == VSNORMAL)
  6968. goto record;
  6969. #if DEBUG
  6970. switch (subtype) {
  6971. case VSTRIMLEFT:
  6972. case VSTRIMLEFTMAX:
  6973. case VSTRIMRIGHT:
  6974. case VSTRIMRIGHTMAX:
  6975. #if BASH_SUBSTR
  6976. case VSSUBSTR:
  6977. #endif
  6978. #if BASH_PATTERN_SUBST
  6979. case VSREPLACE:
  6980. case VSREPLACEALL:
  6981. #endif
  6982. break;
  6983. default:
  6984. abort();
  6985. }
  6986. #endif
  6987. flag |= discard;
  6988. if (!(flag & EXP_DISCARD)) {
  6989. /*
  6990. * Terminate the string and start recording the pattern
  6991. * right after it
  6992. */
  6993. STPUTC('\0', expdest);
  6994. }
  6995. patloc = expdest - (char *)stackblock();
  6996. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6997. record:
  6998. if ((flag | discard) & EXP_DISCARD)
  6999. return p;
  7000. really_record:
  7001. if (quoted) {
  7002. quoted = *var == '@' && shellparam.nparam;
  7003. if (!quoted)
  7004. return p;
  7005. }
  7006. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  7007. return p;
  7008. }
  7009. /*
  7010. * Add a file name to the list.
  7011. */
  7012. static void
  7013. addfname(const char *name)
  7014. {
  7015. struct strlist *sp;
  7016. sp = stzalloc(sizeof(*sp));
  7017. sp->text = sstrdup(name);
  7018. *exparg.lastp = sp;
  7019. exparg.lastp = &sp->next;
  7020. }
  7021. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  7022. static int
  7023. hasmeta(const char *p)
  7024. {
  7025. static const char chars[] ALIGN1 = {
  7026. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  7027. };
  7028. for (;;) {
  7029. p = strpbrk(p, chars);
  7030. if (!p)
  7031. break;
  7032. switch ((unsigned char)*p) {
  7033. case CTLQUOTEMARK:
  7034. for (;;) {
  7035. p++;
  7036. if ((unsigned char)*p == CTLQUOTEMARK)
  7037. break;
  7038. if ((unsigned char)*p == CTLESC)
  7039. p++;
  7040. if (*p == '\0') /* huh? */
  7041. return 0;
  7042. }
  7043. break;
  7044. case '\\':
  7045. case CTLESC:
  7046. p++;
  7047. if (*p == '\0')
  7048. return 0;
  7049. break;
  7050. case '[':
  7051. if (!strchr(p + 1, ']')) {
  7052. /* It's not a properly closed [] pattern,
  7053. * but other metas may follow. Continue checking.
  7054. * my[file* _is_ globbed by bash
  7055. * and matches filenames like "my[file1".
  7056. */
  7057. break;
  7058. }
  7059. /* fallthrough */
  7060. default:
  7061. /* case '*': */
  7062. /* case '?': */
  7063. return 1;
  7064. }
  7065. p++;
  7066. }
  7067. return 0;
  7068. }
  7069. /* If we want to use glob() from libc... */
  7070. #if !ENABLE_ASH_INTERNAL_GLOB
  7071. /* Add the result of glob() to the list */
  7072. static void
  7073. addglob(const glob_t *pglob)
  7074. {
  7075. char **p = pglob->gl_pathv;
  7076. do {
  7077. addfname(*p);
  7078. } while (*++p);
  7079. }
  7080. static void
  7081. expandmeta(struct strlist *str /*, int flag*/)
  7082. {
  7083. /* TODO - EXP_REDIR */
  7084. while (str) {
  7085. char *p;
  7086. glob_t pglob;
  7087. int i;
  7088. if (fflag)
  7089. goto nometa;
  7090. if (!hasmeta(str->text))
  7091. goto nometa;
  7092. INT_OFF;
  7093. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7094. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  7095. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  7096. //
  7097. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  7098. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  7099. // Which means you need to unescape the string, right? Not so fast:
  7100. // if there _is_ a file named "file\?" (with backslash), it is returned
  7101. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  7102. // You DON'T KNOW by looking at the result whether you need to unescape it.
  7103. //
  7104. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  7105. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  7106. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  7107. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  7108. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  7109. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  7110. i = glob(p, 0, NULL, &pglob);
  7111. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  7112. if (p != str->text)
  7113. free(p);
  7114. switch (i) {
  7115. case 0:
  7116. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  7117. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  7118. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  7119. goto nometa2;
  7120. #endif
  7121. addglob(&pglob);
  7122. globfree(&pglob);
  7123. INT_ON;
  7124. break;
  7125. case GLOB_NOMATCH:
  7126. //nometa2:
  7127. globfree(&pglob);
  7128. INT_ON;
  7129. nometa:
  7130. *exparg.lastp = str;
  7131. rmescapes(str->text, 0, NULL);
  7132. exparg.lastp = &str->next;
  7133. break;
  7134. default: /* GLOB_NOSPACE */
  7135. globfree(&pglob);
  7136. INT_ON;
  7137. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7138. }
  7139. str = str->next;
  7140. }
  7141. }
  7142. #else
  7143. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7144. /*
  7145. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7146. */
  7147. typedef struct exp_t {
  7148. char *dir;
  7149. unsigned dir_max;
  7150. } exp_t;
  7151. static void
  7152. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7153. {
  7154. #define expdir exp->dir
  7155. #define expdir_max exp->dir_max
  7156. char *enddir = expdir + expdir_len;
  7157. char *p;
  7158. const char *cp;
  7159. char *start;
  7160. char *endname;
  7161. int metaflag;
  7162. struct stat statb;
  7163. DIR *dirp;
  7164. struct dirent *dp;
  7165. int atend;
  7166. int matchdot;
  7167. int esc;
  7168. metaflag = 0;
  7169. start = name;
  7170. for (p = name; esc = 0, *p; p += esc + 1) {
  7171. if (*p == '*' || *p == '?')
  7172. metaflag = 1;
  7173. else if (*p == '[') {
  7174. char *q = p + 1;
  7175. if (*q == '!')
  7176. q++;
  7177. for (;;) {
  7178. if (*q == '\\')
  7179. q++;
  7180. if (*q == '/' || *q == '\0')
  7181. break;
  7182. if (*++q == ']') {
  7183. metaflag = 1;
  7184. break;
  7185. }
  7186. }
  7187. } else {
  7188. if (*p == '\\' && p[1])
  7189. esc++;
  7190. if (p[esc] == '/') {
  7191. if (metaflag)
  7192. break;
  7193. start = p + esc + 1;
  7194. }
  7195. }
  7196. }
  7197. if (metaflag == 0) { /* we've reached the end of the file name */
  7198. if (!expdir_len)
  7199. return;
  7200. p = name;
  7201. do {
  7202. if (*p == '\\' && p[1])
  7203. p++;
  7204. *enddir++ = *p;
  7205. } while (*p++);
  7206. if (lstat(expdir, &statb) == 0)
  7207. addfname(expdir);
  7208. return;
  7209. }
  7210. endname = p;
  7211. if (name < start) {
  7212. p = name;
  7213. do {
  7214. if (*p == '\\' && p[1])
  7215. p++;
  7216. *enddir++ = *p++;
  7217. } while (p < start);
  7218. }
  7219. *enddir = '\0';
  7220. cp = expdir;
  7221. expdir_len = enddir - cp;
  7222. if (!expdir_len)
  7223. cp = ".";
  7224. dirp = opendir(cp);
  7225. if (dirp == NULL)
  7226. return;
  7227. if (*endname == 0) {
  7228. atend = 1;
  7229. } else {
  7230. atend = 0;
  7231. *endname = '\0';
  7232. endname += esc + 1;
  7233. }
  7234. name_len -= endname - name;
  7235. matchdot = 0;
  7236. p = start;
  7237. if (*p == '\\')
  7238. p++;
  7239. if (*p == '.')
  7240. matchdot++;
  7241. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7242. if (dp->d_name[0] == '.' && !matchdot)
  7243. continue;
  7244. if (pmatch(start, dp->d_name)) {
  7245. if (atend) {
  7246. strcpy(enddir, dp->d_name);
  7247. addfname(expdir);
  7248. } else {
  7249. unsigned offset;
  7250. unsigned len;
  7251. p = stpcpy(enddir, dp->d_name);
  7252. *p = '/';
  7253. offset = p - expdir + 1;
  7254. len = offset + name_len + NAME_MAX;
  7255. if (len > expdir_max) {
  7256. len += PATH_MAX;
  7257. expdir = ckrealloc(expdir, len);
  7258. expdir_max = len;
  7259. }
  7260. expmeta(exp, endname, name_len, offset);
  7261. enddir = expdir + expdir_len;
  7262. }
  7263. }
  7264. }
  7265. closedir(dirp);
  7266. if (!atend)
  7267. endname[-esc - 1] = esc ? '\\' : '/';
  7268. #undef expdir
  7269. #undef expdir_max
  7270. }
  7271. static struct strlist *
  7272. msort(struct strlist *list, int len)
  7273. {
  7274. struct strlist *p, *q = NULL;
  7275. struct strlist **lpp;
  7276. int half;
  7277. int n;
  7278. if (len <= 1)
  7279. return list;
  7280. half = len >> 1;
  7281. p = list;
  7282. for (n = half; --n >= 0;) {
  7283. q = p;
  7284. p = p->next;
  7285. }
  7286. q->next = NULL; /* terminate first half of list */
  7287. q = msort(list, half); /* sort first half of list */
  7288. p = msort(p, len - half); /* sort second half */
  7289. lpp = &list;
  7290. for (;;) {
  7291. #if ENABLE_LOCALE_SUPPORT
  7292. if (strcoll(p->text, q->text) < 0)
  7293. #else
  7294. if (strcmp(p->text, q->text) < 0)
  7295. #endif
  7296. {
  7297. *lpp = p;
  7298. lpp = &p->next;
  7299. p = *lpp;
  7300. if (p == NULL) {
  7301. *lpp = q;
  7302. break;
  7303. }
  7304. } else {
  7305. *lpp = q;
  7306. lpp = &q->next;
  7307. q = *lpp;
  7308. if (q == NULL) {
  7309. *lpp = p;
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return list;
  7315. }
  7316. /*
  7317. * Sort the results of file name expansion. It calculates the number of
  7318. * strings to sort and then calls msort (short for merge sort) to do the
  7319. * work.
  7320. */
  7321. static struct strlist *
  7322. expsort(struct strlist *str)
  7323. {
  7324. int len;
  7325. struct strlist *sp;
  7326. len = 0;
  7327. for (sp = str; sp; sp = sp->next)
  7328. len++;
  7329. return msort(str, len);
  7330. }
  7331. static void
  7332. expandmeta(struct strlist *str /*, int flag*/)
  7333. {
  7334. /* TODO - EXP_REDIR */
  7335. while (str) {
  7336. exp_t exp;
  7337. struct strlist **savelastp;
  7338. struct strlist *sp;
  7339. char *p;
  7340. unsigned len;
  7341. if (fflag)
  7342. goto nometa;
  7343. if (!hasmeta(str->text))
  7344. goto nometa;
  7345. savelastp = exparg.lastp;
  7346. INT_OFF;
  7347. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7348. len = strlen(p);
  7349. exp.dir_max = len + PATH_MAX;
  7350. exp.dir = ckmalloc(exp.dir_max);
  7351. expmeta(&exp, p, len, 0);
  7352. free(exp.dir);
  7353. if (p != str->text)
  7354. free(p);
  7355. INT_ON;
  7356. if (exparg.lastp == savelastp) {
  7357. /*
  7358. * no matches
  7359. */
  7360. nometa:
  7361. *exparg.lastp = str;
  7362. rmescapes(str->text, 0, NULL);
  7363. exparg.lastp = &str->next;
  7364. } else {
  7365. *exparg.lastp = NULL;
  7366. *savelastp = sp = expsort(*savelastp);
  7367. while (sp->next != NULL)
  7368. sp = sp->next;
  7369. exparg.lastp = &sp->next;
  7370. }
  7371. str = str->next;
  7372. }
  7373. }
  7374. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7375. /*
  7376. * Perform variable substitution and command substitution on an argument,
  7377. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7378. * perform splitting and file name expansion. When arglist is NULL, perform
  7379. * here document expansion.
  7380. */
  7381. static void
  7382. expandarg(union node *arg, struct arglist *arglist, int flag)
  7383. {
  7384. struct strlist *sp;
  7385. char *p;
  7386. argbackq = arg->narg.backquote;
  7387. STARTSTACKSTR(expdest);
  7388. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7389. argstr(arg->narg.text, flag);
  7390. if (arglist == NULL) {
  7391. /* here document expanded */
  7392. goto out;
  7393. }
  7394. p = grabstackstr(expdest);
  7395. TRACE(("expandarg: p:'%s'\n", p));
  7396. exparg.lastp = &exparg.list;
  7397. /*
  7398. * TODO - EXP_REDIR
  7399. */
  7400. if (flag & EXP_FULL) {
  7401. ifsbreakup(p, &exparg);
  7402. *exparg.lastp = NULL;
  7403. exparg.lastp = &exparg.list;
  7404. expandmeta(exparg.list /*, flag*/);
  7405. } else {
  7406. sp = stzalloc(sizeof(*sp));
  7407. sp->text = p;
  7408. *exparg.lastp = sp;
  7409. exparg.lastp = &sp->next;
  7410. }
  7411. *exparg.lastp = NULL;
  7412. if (exparg.list) {
  7413. *arglist->lastp = exparg.list;
  7414. arglist->lastp = exparg.lastp;
  7415. }
  7416. out:
  7417. ifsfree();
  7418. }
  7419. /*
  7420. * Expand shell variables and backquotes inside a here document.
  7421. */
  7422. static void
  7423. expandhere(union node *arg)
  7424. {
  7425. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7426. }
  7427. /*
  7428. * Returns true if the pattern matches the string.
  7429. */
  7430. static int
  7431. patmatch(char *pattern, const char *string)
  7432. {
  7433. char *p = preglob(pattern, 0);
  7434. int r = pmatch(p, string);
  7435. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7436. return r;
  7437. }
  7438. /*
  7439. * See if a pattern matches in a case statement.
  7440. */
  7441. static int
  7442. casematch(union node *pattern, char *val)
  7443. {
  7444. struct stackmark smark;
  7445. int result;
  7446. setstackmark(&smark);
  7447. argbackq = pattern->narg.backquote;
  7448. STARTSTACKSTR(expdest);
  7449. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7450. ifsfree();
  7451. result = patmatch(stackblock(), val);
  7452. popstackmark(&smark);
  7453. return result;
  7454. }
  7455. /* ============ find_command */
  7456. struct builtincmd {
  7457. const char *name;
  7458. int (*builtin)(int, char **) FAST_FUNC;
  7459. /* unsigned flags; */
  7460. };
  7461. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7462. /* "regular" builtins always take precedence over commands,
  7463. * regardless of PATH=....%builtin... position */
  7464. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7465. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7466. struct cmdentry {
  7467. smallint cmdtype; /* CMDxxx */
  7468. union param {
  7469. int index;
  7470. /* index >= 0 for commands without path (slashes) */
  7471. /* (TODO: what exactly does the value mean? PATH position?) */
  7472. /* index == -1 for commands with slashes */
  7473. /* index == (-2 - applet_no) for NOFORK applets */
  7474. const struct builtincmd *cmd;
  7475. struct funcnode *func;
  7476. } u;
  7477. };
  7478. /* values of cmdtype */
  7479. #define CMDUNKNOWN -1 /* no entry in table for command */
  7480. #define CMDNORMAL 0 /* command is an executable program */
  7481. #define CMDFUNCTION 1 /* command is a shell function */
  7482. #define CMDBUILTIN 2 /* command is a shell builtin */
  7483. /* action to find_command() */
  7484. #define DO_ERR 0x01 /* prints errors */
  7485. #define DO_ABS 0x02 /* checks absolute paths */
  7486. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7487. #define DO_ALTPATH 0x08 /* using alternate path */
  7488. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7489. static void find_command(char *, struct cmdentry *, int, const char *);
  7490. /* ============ Hashing commands */
  7491. /*
  7492. * When commands are first encountered, they are entered in a hash table.
  7493. * This ensures that a full path search will not have to be done for them
  7494. * on each invocation.
  7495. *
  7496. * We should investigate converting to a linear search, even though that
  7497. * would make the command name "hash" a misnomer.
  7498. */
  7499. struct tblentry {
  7500. struct tblentry *next; /* next entry in hash chain */
  7501. union param param; /* definition of builtin function */
  7502. smallint cmdtype; /* CMDxxx */
  7503. char rehash; /* if set, cd done since entry created */
  7504. char cmdname[1]; /* name of command */
  7505. };
  7506. static struct tblentry **cmdtable;
  7507. #define INIT_G_cmdtable() do { \
  7508. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7509. } while (0)
  7510. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7511. static void
  7512. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7513. {
  7514. #if ENABLE_FEATURE_SH_STANDALONE
  7515. if (applet_no >= 0) {
  7516. if (APPLET_IS_NOEXEC(applet_no)) {
  7517. clearenv();
  7518. while (*envp)
  7519. putenv(*envp++);
  7520. popredir(/*drop:*/ 1);
  7521. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7522. }
  7523. /* re-exec ourselves with the new arguments */
  7524. execve(bb_busybox_exec_path, argv, envp);
  7525. /* If they called chroot or otherwise made the binary no longer
  7526. * executable, fall through */
  7527. }
  7528. #endif
  7529. repeat:
  7530. #ifdef SYSV
  7531. do {
  7532. execve(cmd, argv, envp);
  7533. } while (errno == EINTR);
  7534. #else
  7535. execve(cmd, argv, envp);
  7536. #endif
  7537. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7538. /* Run "cmd" as a shell script:
  7539. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7540. * "If the execve() function fails with ENOEXEC, the shell
  7541. * shall execute a command equivalent to having a shell invoked
  7542. * with the command name as its first operand,
  7543. * with any remaining arguments passed to the new shell"
  7544. *
  7545. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7546. * just call ourselves.
  7547. *
  7548. * Note that bash reads ~80 chars of the file, and if it sees
  7549. * a zero byte before it sees newline, it doesn't try to
  7550. * interpret it, but fails with "cannot execute binary file"
  7551. * message and exit code 126. For one, this prevents attempts
  7552. * to interpret foreign ELF binaries as shell scripts.
  7553. */
  7554. argv[0] = (char*) cmd;
  7555. cmd = bb_busybox_exec_path;
  7556. /* NB: this is only possible because all callers of shellexec()
  7557. * ensure that the argv[-1] slot exists!
  7558. */
  7559. argv--;
  7560. argv[0] = (char*) "ash";
  7561. goto repeat;
  7562. }
  7563. }
  7564. /*
  7565. * Exec a program. Never returns. If you change this routine, you may
  7566. * have to change the find_command routine as well.
  7567. * argv[-1] must exist and be writable! See tryexec() for why.
  7568. */
  7569. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7570. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7571. {
  7572. char *cmdname;
  7573. int e;
  7574. char **envp;
  7575. int exerrno;
  7576. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7577. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7578. if (strchr(prog, '/') != NULL
  7579. #if ENABLE_FEATURE_SH_STANDALONE
  7580. || (applet_no = find_applet_by_name(prog)) >= 0
  7581. #endif
  7582. ) {
  7583. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7584. if (applet_no >= 0) {
  7585. /* We tried execing ourself, but it didn't work.
  7586. * Maybe /proc/self/exe doesn't exist?
  7587. * Try $PATH search.
  7588. */
  7589. goto try_PATH;
  7590. }
  7591. e = errno;
  7592. } else {
  7593. try_PATH:
  7594. e = ENOENT;
  7595. while (padvance(&path, argv[0]) >= 0) {
  7596. cmdname = stackblock();
  7597. if (--idx < 0 && pathopt == NULL) {
  7598. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7599. if (errno != ENOENT && errno != ENOTDIR)
  7600. e = errno;
  7601. }
  7602. }
  7603. }
  7604. /* Map to POSIX errors */
  7605. switch (e) {
  7606. default:
  7607. exerrno = 126;
  7608. break;
  7609. case ELOOP:
  7610. case ENAMETOOLONG:
  7611. case ENOENT:
  7612. case ENOTDIR:
  7613. exerrno = 127;
  7614. break;
  7615. }
  7616. exitstatus = exerrno;
  7617. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7618. prog, e, suppress_int));
  7619. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7620. /* NOTREACHED */
  7621. }
  7622. static void
  7623. printentry(struct tblentry *cmdp)
  7624. {
  7625. int idx;
  7626. const char *path;
  7627. char *name;
  7628. idx = cmdp->param.index;
  7629. path = pathval();
  7630. do {
  7631. padvance(&path, cmdp->cmdname);
  7632. } while (--idx >= 0);
  7633. name = stackblock();
  7634. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7635. }
  7636. /*
  7637. * Clear out command entries.
  7638. */
  7639. static void
  7640. clearcmdentry(void)
  7641. {
  7642. struct tblentry **tblp;
  7643. struct tblentry **pp;
  7644. struct tblentry *cmdp;
  7645. INT_OFF;
  7646. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7647. pp = tblp;
  7648. while ((cmdp = *pp) != NULL) {
  7649. if (cmdp->cmdtype == CMDNORMAL
  7650. || (cmdp->cmdtype == CMDBUILTIN
  7651. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7652. && builtinloc > 0
  7653. )
  7654. ) {
  7655. *pp = cmdp->next;
  7656. free(cmdp);
  7657. } else {
  7658. pp = &cmdp->next;
  7659. }
  7660. }
  7661. }
  7662. INT_ON;
  7663. }
  7664. /*
  7665. * Locate a command in the command hash table. If "add" is nonzero,
  7666. * add the command to the table if it is not already present. The
  7667. * variable "lastcmdentry" is set to point to the address of the link
  7668. * pointing to the entry, so that delete_cmd_entry can delete the
  7669. * entry.
  7670. *
  7671. * Interrupts must be off if called with add != 0.
  7672. */
  7673. static struct tblentry **lastcmdentry;
  7674. static struct tblentry *
  7675. cmdlookup(const char *name, int add)
  7676. {
  7677. unsigned int hashval;
  7678. const char *p;
  7679. struct tblentry *cmdp;
  7680. struct tblentry **pp;
  7681. p = name;
  7682. hashval = (unsigned char)*p << 4;
  7683. while (*p)
  7684. hashval += (unsigned char)*p++;
  7685. hashval &= 0x7FFF;
  7686. pp = &cmdtable[hashval % CMDTABLESIZE];
  7687. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7688. if (strcmp(cmdp->cmdname, name) == 0)
  7689. break;
  7690. pp = &cmdp->next;
  7691. }
  7692. if (add && cmdp == NULL) {
  7693. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7694. + strlen(name)
  7695. /* + 1 - already done because
  7696. * tblentry::cmdname is char[1] */);
  7697. /*cmdp->next = NULL; - ckzalloc did it */
  7698. cmdp->cmdtype = CMDUNKNOWN;
  7699. strcpy(cmdp->cmdname, name);
  7700. }
  7701. lastcmdentry = pp;
  7702. return cmdp;
  7703. }
  7704. /*
  7705. * Delete the command entry returned on the last lookup.
  7706. */
  7707. static void
  7708. delete_cmd_entry(void)
  7709. {
  7710. struct tblentry *cmdp;
  7711. INT_OFF;
  7712. cmdp = *lastcmdentry;
  7713. *lastcmdentry = cmdp->next;
  7714. if (cmdp->cmdtype == CMDFUNCTION)
  7715. freefunc(cmdp->param.func);
  7716. free(cmdp);
  7717. INT_ON;
  7718. }
  7719. /*
  7720. * Add a new command entry, replacing any existing command entry for
  7721. * the same name - except special builtins.
  7722. */
  7723. static void
  7724. addcmdentry(char *name, struct cmdentry *entry)
  7725. {
  7726. struct tblentry *cmdp;
  7727. cmdp = cmdlookup(name, 1);
  7728. if (cmdp->cmdtype == CMDFUNCTION) {
  7729. freefunc(cmdp->param.func);
  7730. }
  7731. cmdp->cmdtype = entry->cmdtype;
  7732. cmdp->param = entry->u;
  7733. cmdp->rehash = 0;
  7734. }
  7735. static int FAST_FUNC
  7736. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7737. {
  7738. struct tblentry **pp;
  7739. struct tblentry *cmdp;
  7740. int c;
  7741. struct cmdentry entry;
  7742. char *name;
  7743. if (nextopt("r") != '\0') {
  7744. clearcmdentry();
  7745. return 0;
  7746. }
  7747. if (*argptr == NULL) {
  7748. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7749. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7750. if (cmdp->cmdtype == CMDNORMAL)
  7751. printentry(cmdp);
  7752. }
  7753. }
  7754. return 0;
  7755. }
  7756. c = 0;
  7757. while ((name = *argptr) != NULL) {
  7758. cmdp = cmdlookup(name, 0);
  7759. if (cmdp != NULL
  7760. && (cmdp->cmdtype == CMDNORMAL
  7761. || (cmdp->cmdtype == CMDBUILTIN
  7762. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7763. && builtinloc > 0
  7764. )
  7765. )
  7766. ) {
  7767. delete_cmd_entry();
  7768. }
  7769. find_command(name, &entry, DO_ERR, pathval());
  7770. if (entry.cmdtype == CMDUNKNOWN)
  7771. c = 1;
  7772. argptr++;
  7773. }
  7774. return c;
  7775. }
  7776. /*
  7777. * Called when a cd is done. Marks all commands so the next time they
  7778. * are executed they will be rehashed.
  7779. */
  7780. static void
  7781. hashcd(void)
  7782. {
  7783. struct tblentry **pp;
  7784. struct tblentry *cmdp;
  7785. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7786. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7787. if (cmdp->cmdtype == CMDNORMAL
  7788. || (cmdp->cmdtype == CMDBUILTIN
  7789. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7790. && builtinloc > 0)
  7791. ) {
  7792. cmdp->rehash = 1;
  7793. }
  7794. }
  7795. }
  7796. }
  7797. /*
  7798. * Fix command hash table when PATH changed.
  7799. * Called before PATH is changed. The argument is the new value of PATH;
  7800. * pathval() still returns the old value at this point.
  7801. * Called with interrupts off.
  7802. */
  7803. static void FAST_FUNC
  7804. changepath(const char *newval)
  7805. {
  7806. const char *new;
  7807. int idx;
  7808. int bltin;
  7809. new = newval;
  7810. idx = 0;
  7811. bltin = -1;
  7812. for (;;) {
  7813. if (*new == '%' && prefix(new + 1, "builtin")) {
  7814. bltin = idx;
  7815. break;
  7816. }
  7817. new = strchr(new, ':');
  7818. if (!new)
  7819. break;
  7820. idx++;
  7821. new++;
  7822. }
  7823. builtinloc = bltin;
  7824. clearcmdentry();
  7825. }
  7826. enum {
  7827. TEOF,
  7828. TNL,
  7829. TREDIR,
  7830. TWORD,
  7831. TSEMI,
  7832. TBACKGND,
  7833. TAND,
  7834. TOR,
  7835. TPIPE,
  7836. TLP,
  7837. TRP,
  7838. TENDCASE,
  7839. TENDBQUOTE,
  7840. TNOT,
  7841. TCASE,
  7842. TDO,
  7843. TDONE,
  7844. TELIF,
  7845. TELSE,
  7846. TESAC,
  7847. TFI,
  7848. TFOR,
  7849. #if BASH_FUNCTION
  7850. TFUNCTION,
  7851. #endif
  7852. TIF,
  7853. TIN,
  7854. TTHEN,
  7855. TUNTIL,
  7856. TWHILE,
  7857. TBEGIN,
  7858. TEND
  7859. };
  7860. typedef smallint token_id_t;
  7861. /* Nth bit indicates if token marks the end of a list */
  7862. enum {
  7863. tokendlist = 0
  7864. /* 0 */ | (1u << TEOF)
  7865. /* 1 */ | (0u << TNL)
  7866. /* 2 */ | (0u << TREDIR)
  7867. /* 3 */ | (0u << TWORD)
  7868. /* 4 */ | (0u << TSEMI)
  7869. /* 5 */ | (0u << TBACKGND)
  7870. /* 6 */ | (0u << TAND)
  7871. /* 7 */ | (0u << TOR)
  7872. /* 8 */ | (0u << TPIPE)
  7873. /* 9 */ | (0u << TLP)
  7874. /* 10 */ | (1u << TRP)
  7875. /* 11 */ | (1u << TENDCASE)
  7876. /* 12 */ | (1u << TENDBQUOTE)
  7877. /* 13 */ | (0u << TNOT)
  7878. /* 14 */ | (0u << TCASE)
  7879. /* 15 */ | (1u << TDO)
  7880. /* 16 */ | (1u << TDONE)
  7881. /* 17 */ | (1u << TELIF)
  7882. /* 18 */ | (1u << TELSE)
  7883. /* 19 */ | (1u << TESAC)
  7884. /* 20 */ | (1u << TFI)
  7885. /* 21 */ | (0u << TFOR)
  7886. #if BASH_FUNCTION
  7887. /* 22 */ | (0u << TFUNCTION)
  7888. #endif
  7889. /* 23 */ | (0u << TIF)
  7890. /* 24 */ | (0u << TIN)
  7891. /* 25 */ | (1u << TTHEN)
  7892. /* 26 */ | (0u << TUNTIL)
  7893. /* 27 */ | (0u << TWHILE)
  7894. /* 28 */ | (0u << TBEGIN)
  7895. /* 29 */ | (1u << TEND)
  7896. , /* thus far 29 bits used */
  7897. };
  7898. static const char *const tokname_array[] ALIGN_PTR = {
  7899. "end of file",
  7900. "newline",
  7901. "redirection",
  7902. "word",
  7903. ";",
  7904. "&",
  7905. "&&",
  7906. "||",
  7907. "|",
  7908. "(",
  7909. ")",
  7910. ";;",
  7911. "`",
  7912. #define KWDOFFSET 13
  7913. /* the following are keywords */
  7914. "!",
  7915. "case",
  7916. "do",
  7917. "done",
  7918. "elif",
  7919. "else",
  7920. "esac",
  7921. "fi",
  7922. "for",
  7923. #if BASH_FUNCTION
  7924. "function",
  7925. #endif
  7926. "if",
  7927. "in",
  7928. "then",
  7929. "until",
  7930. "while",
  7931. "{",
  7932. "}",
  7933. };
  7934. /* Wrapper around strcmp for qsort/bsearch/... */
  7935. static int
  7936. pstrcmp(const void *a, const void *b)
  7937. {
  7938. return strcmp((char*)a, *(char**)b);
  7939. }
  7940. static const char *const *
  7941. findkwd(const char *s)
  7942. {
  7943. return bsearch(s, tokname_array + KWDOFFSET,
  7944. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7945. sizeof(tokname_array[0]), pstrcmp);
  7946. }
  7947. /*
  7948. * Locate and print what a word is...
  7949. */
  7950. static int
  7951. describe_command(char *command, const char *path, int describe_command_verbose)
  7952. {
  7953. struct cmdentry entry;
  7954. #if ENABLE_ASH_ALIAS
  7955. const struct alias *ap;
  7956. #endif
  7957. if (describe_command_verbose) {
  7958. out1str(command);
  7959. }
  7960. /* First look at the keywords */
  7961. if (findkwd(command)) {
  7962. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7963. goto out;
  7964. }
  7965. #if ENABLE_ASH_ALIAS
  7966. /* Then look at the aliases */
  7967. ap = lookupalias(command, 0);
  7968. if (ap != NULL) {
  7969. if (!describe_command_verbose) {
  7970. out1str("alias ");
  7971. printalias(ap);
  7972. return 0;
  7973. }
  7974. out1fmt(" is an alias for %s", ap->val);
  7975. goto out;
  7976. }
  7977. #endif
  7978. /* Brute force */
  7979. path = path ? path : pathval();
  7980. find_command(command, &entry, DO_ABS, path);
  7981. switch (entry.cmdtype) {
  7982. case CMDNORMAL: {
  7983. int j = entry.u.index;
  7984. char *p;
  7985. if (j < 0) {
  7986. p = command;
  7987. } else {
  7988. do {
  7989. padvance(&path, command);
  7990. } while (--j >= 0);
  7991. p = stackblock();
  7992. }
  7993. if (describe_command_verbose) {
  7994. out1fmt(" is %s", p);
  7995. } else {
  7996. out1str(p);
  7997. }
  7998. break;
  7999. }
  8000. case CMDFUNCTION:
  8001. if (describe_command_verbose) {
  8002. /*out1str(" is a shell function");*/
  8003. out1str(" is a function"); /* bash says this */
  8004. } else {
  8005. out1str(command);
  8006. }
  8007. break;
  8008. case CMDBUILTIN:
  8009. if (describe_command_verbose) {
  8010. out1fmt(" is a %sshell builtin",
  8011. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  8012. "special " : nullstr
  8013. );
  8014. } else {
  8015. out1str(command);
  8016. }
  8017. break;
  8018. default:
  8019. if (describe_command_verbose) {
  8020. out1str(": not found\n");
  8021. }
  8022. return 127;
  8023. }
  8024. out:
  8025. out1str("\n");
  8026. return 0;
  8027. }
  8028. static int FAST_FUNC
  8029. typecmd(int argc UNUSED_PARAM, char **argv)
  8030. {
  8031. int i = 1;
  8032. int err = 0;
  8033. int verbose = 1;
  8034. /* type -p ... ? (we don't bother checking for 'p') */
  8035. if (argv[1] && argv[1][0] == '-') {
  8036. i++;
  8037. verbose = 0;
  8038. }
  8039. while (argv[i]) {
  8040. err |= describe_command(argv[i++], NULL, verbose);
  8041. }
  8042. return err;
  8043. }
  8044. static struct strlist *
  8045. fill_arglist(struct arglist *arglist, union node **argpp)
  8046. {
  8047. struct strlist **lastp = arglist->lastp;
  8048. union node *argp;
  8049. while ((argp = *argpp) != NULL) {
  8050. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  8051. *argpp = argp->narg.next;
  8052. if (*lastp)
  8053. break;
  8054. }
  8055. return *lastp;
  8056. }
  8057. #if ENABLE_ASH_CMDCMD
  8058. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  8059. static int
  8060. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  8061. {
  8062. struct strlist *sp = arglist->list;
  8063. char *cp, c;
  8064. for (;;) {
  8065. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  8066. if (!sp)
  8067. return 0;
  8068. cp = sp->text;
  8069. if (*cp++ != '-')
  8070. break;
  8071. c = *cp++;
  8072. if (!c)
  8073. break;
  8074. if (c == '-' && !*cp) {
  8075. if (!sp->next && !fill_arglist(arglist, argpp))
  8076. return 0;
  8077. sp = sp->next;
  8078. break;
  8079. }
  8080. do {
  8081. switch (c) {
  8082. case 'p':
  8083. *path = bb_default_path;
  8084. break;
  8085. default:
  8086. /* run 'typecmd' for other options */
  8087. return 0;
  8088. }
  8089. c = *cp++;
  8090. } while (c);
  8091. }
  8092. arglist->list = sp;
  8093. return DO_NOFUNC;
  8094. }
  8095. static int FAST_FUNC
  8096. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8097. {
  8098. char *cmd;
  8099. int c;
  8100. enum {
  8101. VERIFY_BRIEF = 1,
  8102. VERIFY_VERBOSE = 2,
  8103. } verify = 0;
  8104. const char *path = NULL;
  8105. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  8106. * never reaches this function.
  8107. */
  8108. while ((c = nextopt("pvV")) != '\0')
  8109. if (c == 'V')
  8110. verify |= VERIFY_VERBOSE;
  8111. else if (c == 'v')
  8112. /*verify |= VERIFY_BRIEF*/;
  8113. #if DEBUG
  8114. else if (c != 'p')
  8115. abort();
  8116. #endif
  8117. else
  8118. path = bb_default_path;
  8119. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  8120. cmd = *argptr;
  8121. if (/*verify && */ cmd)
  8122. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  8123. return 0;
  8124. }
  8125. #endif
  8126. /*static int funcblocksize; // size of structures in function */
  8127. /*static int funcstringsize; // size of strings in node */
  8128. static void *funcblock; /* block to allocate function from */
  8129. static char *funcstring_end; /* end of block to allocate strings from */
  8130. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  8131. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  8132. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  8133. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  8134. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  8135. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  8136. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8137. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8138. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8139. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  8140. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8141. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8142. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8143. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8144. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8145. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8146. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8147. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8148. #if BASH_REDIR_OUTPUT
  8149. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8150. #endif
  8151. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8152. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8153. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8154. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8155. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8156. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8157. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8158. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8159. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8160. };
  8161. static int calcsize(int funcblocksize, union node *n);
  8162. static int
  8163. sizenodelist(int funcblocksize, struct nodelist *lp)
  8164. {
  8165. while (lp) {
  8166. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8167. funcblocksize = calcsize(funcblocksize, lp->n);
  8168. lp = lp->next;
  8169. }
  8170. return funcblocksize;
  8171. }
  8172. static int
  8173. calcsize(int funcblocksize, union node *n)
  8174. {
  8175. if (n == NULL)
  8176. return funcblocksize;
  8177. funcblocksize += nodesize[n->type];
  8178. switch (n->type) {
  8179. case NCMD:
  8180. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8181. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8182. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8183. break;
  8184. case NPIPE:
  8185. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8186. break;
  8187. case NREDIR:
  8188. case NBACKGND:
  8189. case NSUBSHELL:
  8190. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8191. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8192. break;
  8193. case NAND:
  8194. case NOR:
  8195. case NSEMI:
  8196. case NWHILE:
  8197. case NUNTIL:
  8198. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8199. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8200. break;
  8201. case NIF:
  8202. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8203. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8204. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8205. break;
  8206. case NFOR:
  8207. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8208. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8209. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8210. break;
  8211. case NCASE:
  8212. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8213. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8214. break;
  8215. case NCLIST:
  8216. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8217. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8218. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8219. break;
  8220. case NDEFUN:
  8221. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8222. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8223. break;
  8224. case NARG:
  8225. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8226. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8227. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8228. break;
  8229. case NTO:
  8230. #if BASH_REDIR_OUTPUT
  8231. case NTO2:
  8232. #endif
  8233. case NCLOBBER:
  8234. case NFROM:
  8235. case NFROMTO:
  8236. case NAPPEND:
  8237. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8238. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8239. break;
  8240. case NTOFD:
  8241. case NFROMFD:
  8242. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8243. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8244. break;
  8245. case NHERE:
  8246. case NXHERE:
  8247. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8248. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8249. break;
  8250. case NNOT:
  8251. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8252. break;
  8253. };
  8254. return funcblocksize;
  8255. }
  8256. static char *
  8257. nodeckstrdup(char *s)
  8258. {
  8259. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8260. return strcpy(funcstring_end, s);
  8261. }
  8262. static union node *copynode(union node *);
  8263. static struct nodelist *
  8264. copynodelist(struct nodelist *lp)
  8265. {
  8266. struct nodelist *start;
  8267. struct nodelist **lpp;
  8268. lpp = &start;
  8269. while (lp) {
  8270. *lpp = funcblock;
  8271. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8272. (*lpp)->n = copynode(lp->n);
  8273. lp = lp->next;
  8274. lpp = &(*lpp)->next;
  8275. }
  8276. *lpp = NULL;
  8277. return start;
  8278. }
  8279. static union node *
  8280. copynode(union node *n)
  8281. {
  8282. union node *new;
  8283. if (n == NULL)
  8284. return NULL;
  8285. new = funcblock;
  8286. funcblock = (char *) funcblock + nodesize[n->type];
  8287. switch (n->type) {
  8288. case NCMD:
  8289. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8290. new->ncmd.args = copynode(n->ncmd.args);
  8291. new->ncmd.assign = copynode(n->ncmd.assign);
  8292. new->ncmd.linno = n->ncmd.linno;
  8293. break;
  8294. case NPIPE:
  8295. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8296. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8297. break;
  8298. case NREDIR:
  8299. case NBACKGND:
  8300. case NSUBSHELL:
  8301. new->nredir.redirect = copynode(n->nredir.redirect);
  8302. new->nredir.n = copynode(n->nredir.n);
  8303. new->nredir.linno = n->nredir.linno;
  8304. break;
  8305. case NAND:
  8306. case NOR:
  8307. case NSEMI:
  8308. case NWHILE:
  8309. case NUNTIL:
  8310. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8311. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8312. break;
  8313. case NIF:
  8314. new->nif.elsepart = copynode(n->nif.elsepart);
  8315. new->nif.ifpart = copynode(n->nif.ifpart);
  8316. new->nif.test = copynode(n->nif.test);
  8317. break;
  8318. case NFOR:
  8319. new->nfor.var = nodeckstrdup(n->nfor.var);
  8320. new->nfor.body = copynode(n->nfor.body);
  8321. new->nfor.args = copynode(n->nfor.args);
  8322. new->nfor.linno = n->nfor.linno;
  8323. break;
  8324. case NCASE:
  8325. new->ncase.cases = copynode(n->ncase.cases);
  8326. new->ncase.expr = copynode(n->ncase.expr);
  8327. new->ncase.linno = n->ncase.linno;
  8328. break;
  8329. case NCLIST:
  8330. new->nclist.body = copynode(n->nclist.body);
  8331. new->nclist.pattern = copynode(n->nclist.pattern);
  8332. new->nclist.next = copynode(n->nclist.next);
  8333. break;
  8334. case NDEFUN:
  8335. new->ndefun.body = copynode(n->ndefun.body);
  8336. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8337. new->ndefun.linno = n->ndefun.linno;
  8338. break;
  8339. case NARG:
  8340. new->narg.backquote = copynodelist(n->narg.backquote);
  8341. new->narg.text = nodeckstrdup(n->narg.text);
  8342. new->narg.next = copynode(n->narg.next);
  8343. break;
  8344. case NTO:
  8345. #if BASH_REDIR_OUTPUT
  8346. case NTO2:
  8347. #endif
  8348. case NCLOBBER:
  8349. case NFROM:
  8350. case NFROMTO:
  8351. case NAPPEND:
  8352. new->nfile.fname = copynode(n->nfile.fname);
  8353. new->nfile.fd = n->nfile.fd;
  8354. new->nfile.next = copynode(n->nfile.next);
  8355. break;
  8356. case NTOFD:
  8357. case NFROMFD:
  8358. new->ndup.vname = copynode(n->ndup.vname);
  8359. new->ndup.dupfd = n->ndup.dupfd;
  8360. new->ndup.fd = n->ndup.fd;
  8361. new->ndup.next = copynode(n->ndup.next);
  8362. break;
  8363. case NHERE:
  8364. case NXHERE:
  8365. new->nhere.doc = copynode(n->nhere.doc);
  8366. new->nhere.fd = n->nhere.fd;
  8367. new->nhere.next = copynode(n->nhere.next);
  8368. break;
  8369. case NNOT:
  8370. new->nnot.com = copynode(n->nnot.com);
  8371. break;
  8372. };
  8373. new->type = n->type;
  8374. return new;
  8375. }
  8376. /*
  8377. * Make a copy of a parse tree.
  8378. */
  8379. static struct funcnode *
  8380. copyfunc(union node *n)
  8381. {
  8382. struct funcnode *f;
  8383. size_t blocksize;
  8384. /*funcstringsize = 0;*/
  8385. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8386. f = ckzalloc(blocksize /* + funcstringsize */);
  8387. funcblock = (char *) f + offsetof(struct funcnode, n);
  8388. funcstring_end = (char *) f + blocksize;
  8389. copynode(n);
  8390. /* f->count = 0; - ckzalloc did it */
  8391. return f;
  8392. }
  8393. /*
  8394. * Define a shell function.
  8395. */
  8396. static void
  8397. defun(union node *func)
  8398. {
  8399. struct cmdentry entry;
  8400. INT_OFF;
  8401. entry.cmdtype = CMDFUNCTION;
  8402. entry.u.func = copyfunc(func);
  8403. addcmdentry(func->ndefun.text, &entry);
  8404. INT_ON;
  8405. }
  8406. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8407. #define SKIPBREAK (1 << 0)
  8408. #define SKIPCONT (1 << 1)
  8409. #define SKIPFUNC (1 << 2)
  8410. #define SKIPFUNCDEF (1 << 3)
  8411. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8412. static int skipcount; /* number of levels to skip */
  8413. static int loopnest; /* current loop nesting level */
  8414. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8415. /* Forward decl way out to parsing code - dotrap needs it */
  8416. static int evalstring(char *s, int flags);
  8417. /* Called to execute a trap.
  8418. * Single callsite - at the end of evaltree().
  8419. * If we return non-zero, evaltree raises EXEXIT exception.
  8420. *
  8421. * Perhaps we should avoid entering new trap handlers
  8422. * while we are executing a trap handler. [is it a TODO?]
  8423. */
  8424. static void
  8425. dotrap(void)
  8426. {
  8427. uint8_t *g;
  8428. int sig;
  8429. int status, last_status;
  8430. if (!pending_sig)
  8431. return;
  8432. status = savestatus;
  8433. last_status = status;
  8434. if (status < 0) {
  8435. status = exitstatus;
  8436. savestatus = status;
  8437. }
  8438. pending_sig = 0;
  8439. barrier();
  8440. TRACE(("dotrap entered\n"));
  8441. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8442. char *p;
  8443. if (!*g)
  8444. continue;
  8445. if (evalskip) {
  8446. pending_sig = sig;
  8447. break;
  8448. }
  8449. p = trap[sig];
  8450. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8451. * don't upset it by resetting gotsig[SIGINT-1] */
  8452. if (sig == SIGINT && !p)
  8453. continue;
  8454. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8455. *g = 0;
  8456. if (!p)
  8457. continue;
  8458. trap_depth++;
  8459. evalstring(p, 0);
  8460. trap_depth--;
  8461. if (evalskip != SKIPFUNC)
  8462. exitstatus = status;
  8463. }
  8464. savestatus = last_status;
  8465. TRACE(("dotrap returns\n"));
  8466. }
  8467. /* forward declarations - evaluation is fairly recursive business... */
  8468. static int evalloop(union node *, int);
  8469. static int evalfor(union node *, int);
  8470. static int evalcase(union node *, int);
  8471. static int evalsubshell(union node *, int);
  8472. static void expredir(union node *);
  8473. static int evalpipe(union node *, int);
  8474. static int evalcommand(union node *, int);
  8475. static int evalbltin(const struct builtincmd *, int, char **, int);
  8476. static void prehash(union node *);
  8477. /*
  8478. * Evaluate a parse tree. The value is left in the global variable
  8479. * exitstatus.
  8480. */
  8481. static int
  8482. evaltree(union node *n, int flags)
  8483. {
  8484. int checkexit = 0;
  8485. int (*evalfn)(union node *, int);
  8486. struct stackmark smark;
  8487. int status = 0;
  8488. setstackmark(&smark);
  8489. if (nflag)
  8490. goto out;
  8491. if (n == NULL) {
  8492. TRACE(("evaltree(NULL) called\n"));
  8493. goto out;
  8494. }
  8495. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8496. dotrap();
  8497. switch (n->type) {
  8498. default:
  8499. #if DEBUG
  8500. out1fmt("Node type = %d\n", n->type);
  8501. fflush_all();
  8502. break;
  8503. #endif
  8504. case NNOT:
  8505. status = !evaltree(n->nnot.com, EV_TESTED);
  8506. goto setstatus;
  8507. case NREDIR:
  8508. errlinno = lineno = n->nredir.linno;
  8509. expredir(n->nredir.redirect);
  8510. pushredir(n->nredir.redirect);
  8511. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8512. if (!status) {
  8513. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8514. }
  8515. if (n->nredir.redirect)
  8516. popredir(/*drop:*/ 0);
  8517. goto setstatus;
  8518. case NCMD:
  8519. evalfn = evalcommand;
  8520. checkexit:
  8521. checkexit = ~flags & EV_TESTED;
  8522. goto calleval;
  8523. case NFOR:
  8524. evalfn = evalfor;
  8525. goto calleval;
  8526. case NWHILE:
  8527. case NUNTIL:
  8528. evalfn = evalloop;
  8529. goto calleval;
  8530. case NSUBSHELL:
  8531. case NBACKGND:
  8532. evalfn = evalsubshell;
  8533. goto checkexit;
  8534. case NPIPE:
  8535. evalfn = evalpipe;
  8536. goto checkexit;
  8537. case NCASE:
  8538. evalfn = evalcase;
  8539. goto calleval;
  8540. case NAND:
  8541. case NOR:
  8542. case NSEMI: {
  8543. #if NAND + 1 != NOR
  8544. #error NAND + 1 != NOR
  8545. #endif
  8546. #if NOR + 1 != NSEMI
  8547. #error NOR + 1 != NSEMI
  8548. #endif
  8549. unsigned is_or = n->type - NAND;
  8550. status = evaltree(
  8551. n->nbinary.ch1,
  8552. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8553. );
  8554. if ((!status) == is_or || evalskip)
  8555. break;
  8556. n = n->nbinary.ch2;
  8557. evaln:
  8558. evalfn = evaltree;
  8559. calleval:
  8560. status = evalfn(n, flags);
  8561. goto setstatus;
  8562. }
  8563. case NIF:
  8564. status = evaltree(n->nif.test, EV_TESTED);
  8565. if (evalskip)
  8566. break;
  8567. if (!status) {
  8568. n = n->nif.ifpart;
  8569. goto evaln;
  8570. } else if (n->nif.elsepart) {
  8571. n = n->nif.elsepart;
  8572. goto evaln;
  8573. }
  8574. status = 0;
  8575. goto setstatus;
  8576. case NDEFUN:
  8577. defun(n);
  8578. /* Not necessary. To test it:
  8579. * "false; f() { qwerty; }; echo $?" should print 0.
  8580. */
  8581. /* status = 0; */
  8582. setstatus:
  8583. exitstatus = status;
  8584. break;
  8585. }
  8586. out:
  8587. /* Order of checks below is important:
  8588. * signal handlers trigger before exit caused by "set -e".
  8589. */
  8590. dotrap();
  8591. if (checkexit && status) {
  8592. if (trap[NTRAP_ERR] && !in_trap_ERR) {
  8593. int err;
  8594. struct jmploc *volatile savehandler = exception_handler;
  8595. struct jmploc jmploc;
  8596. in_trap_ERR = 1;
  8597. trap_depth++;
  8598. err = setjmp(jmploc.loc);
  8599. if (!err) {
  8600. exception_handler = &jmploc;
  8601. savestatus = exitstatus;
  8602. evalstring(trap[NTRAP_ERR], 0);
  8603. }
  8604. trap_depth--;
  8605. in_trap_ERR = 0;
  8606. exception_handler = savehandler;
  8607. if (err && exception_type != EXERROR)
  8608. longjmp(exception_handler->loc, 1);
  8609. exitstatus = savestatus;
  8610. }
  8611. if (eflag)
  8612. goto exexit;
  8613. }
  8614. if (flags & EV_EXIT) {
  8615. exexit:
  8616. raise_exception(EXEND); /* does not return */
  8617. }
  8618. popstackmark(&smark);
  8619. TRACE(("leaving evaltree (no interrupts)\n"));
  8620. return exitstatus;
  8621. }
  8622. static int
  8623. skiploop(void)
  8624. {
  8625. int skip = evalskip;
  8626. switch (skip) {
  8627. case 0:
  8628. break;
  8629. case SKIPBREAK:
  8630. case SKIPCONT:
  8631. if (--skipcount <= 0) {
  8632. evalskip = 0;
  8633. break;
  8634. }
  8635. skip = SKIPBREAK;
  8636. break;
  8637. }
  8638. return skip;
  8639. }
  8640. static int
  8641. evalloop(union node *n, int flags)
  8642. {
  8643. int skip;
  8644. int status;
  8645. loopnest++;
  8646. status = 0;
  8647. flags &= EV_TESTED;
  8648. do {
  8649. int i;
  8650. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8651. skip = skiploop();
  8652. if (skip == SKIPFUNC)
  8653. status = i;
  8654. if (skip)
  8655. continue;
  8656. if (n->type != NWHILE)
  8657. i = !i;
  8658. if (i != 0)
  8659. break;
  8660. status = evaltree(n->nbinary.ch2, flags);
  8661. skip = skiploop();
  8662. } while (!(skip & ~SKIPCONT));
  8663. loopnest--;
  8664. return status;
  8665. }
  8666. static int
  8667. evalfor(union node *n, int flags)
  8668. {
  8669. struct arglist arglist;
  8670. union node *argp;
  8671. struct strlist *sp;
  8672. int status = 0;
  8673. errlinno = lineno = n->ncase.linno;
  8674. arglist.list = NULL;
  8675. arglist.lastp = &arglist.list;
  8676. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8677. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8678. }
  8679. *arglist.lastp = NULL;
  8680. loopnest++;
  8681. flags &= EV_TESTED;
  8682. for (sp = arglist.list; sp; sp = sp->next) {
  8683. setvar0(n->nfor.var, sp->text);
  8684. status = evaltree(n->nfor.body, flags);
  8685. if (skiploop() & ~SKIPCONT)
  8686. break;
  8687. }
  8688. loopnest--;
  8689. return status;
  8690. }
  8691. static int
  8692. evalcase(union node *n, int flags)
  8693. {
  8694. union node *cp;
  8695. union node *patp;
  8696. struct arglist arglist;
  8697. int status = 0;
  8698. errlinno = lineno = n->ncase.linno;
  8699. arglist.list = NULL;
  8700. arglist.lastp = &arglist.list;
  8701. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8702. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8703. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8704. if (casematch(patp, arglist.list->text)) {
  8705. /* Ensure body is non-empty as otherwise
  8706. * EV_EXIT may prevent us from setting the
  8707. * exit status.
  8708. */
  8709. if (evalskip == 0 && cp->nclist.body) {
  8710. status = evaltree(cp->nclist.body, flags);
  8711. }
  8712. goto out;
  8713. }
  8714. }
  8715. }
  8716. out:
  8717. return status;
  8718. }
  8719. /*
  8720. * Kick off a subshell to evaluate a tree.
  8721. */
  8722. static int
  8723. evalsubshell(union node *n, int flags)
  8724. {
  8725. struct job *jp;
  8726. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8727. int status;
  8728. errlinno = lineno = n->nredir.linno;
  8729. expredir(n->nredir.redirect);
  8730. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8731. goto nofork;
  8732. INT_OFF;
  8733. if (backgnd == FORK_FG)
  8734. get_tty_state();
  8735. jp = makejob(/*n,*/ 1);
  8736. if (forkshell(jp, n, backgnd) == 0) {
  8737. /* child */
  8738. INT_ON;
  8739. flags |= EV_EXIT;
  8740. if (backgnd)
  8741. flags &= ~EV_TESTED;
  8742. nofork:
  8743. redirect(n->nredir.redirect, 0);
  8744. evaltreenr(n->nredir.n, flags);
  8745. /* never returns */
  8746. }
  8747. /* parent */
  8748. status = 0;
  8749. if (backgnd == FORK_FG)
  8750. status = waitforjob(jp);
  8751. INT_ON;
  8752. return status;
  8753. }
  8754. /*
  8755. * Compute the names of the files in a redirection list.
  8756. */
  8757. static void fixredir(union node *, const char *, int);
  8758. static void
  8759. expredir(union node *n)
  8760. {
  8761. union node *redir;
  8762. for (redir = n; redir; redir = redir->nfile.next) {
  8763. struct arglist fn;
  8764. fn.list = NULL;
  8765. fn.lastp = &fn.list;
  8766. switch (redir->type) {
  8767. case NFROMTO:
  8768. case NFROM:
  8769. case NTO:
  8770. #if BASH_REDIR_OUTPUT
  8771. case NTO2:
  8772. #endif
  8773. case NCLOBBER:
  8774. case NAPPEND:
  8775. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8776. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8777. #if BASH_REDIR_OUTPUT
  8778. store_expfname:
  8779. #endif
  8780. #if 0
  8781. // By the design of stack allocator, the loop of this kind:
  8782. // while true; do while true; do break; done </dev/null; done
  8783. // will look like a memory leak: ash plans to free expfname's
  8784. // of "/dev/null" as soon as it finishes running the loop
  8785. // (in this case, never).
  8786. // This "fix" is wrong:
  8787. if (redir->nfile.expfname)
  8788. stunalloc(redir->nfile.expfname);
  8789. // It results in corrupted state of stacked allocations.
  8790. #endif
  8791. redir->nfile.expfname = fn.list->text;
  8792. break;
  8793. case NFROMFD:
  8794. case NTOFD: /* >& */
  8795. if (redir->ndup.vname) {
  8796. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8797. if (fn.list == NULL)
  8798. ash_msg_and_raise_error("redir error");
  8799. #if BASH_REDIR_OUTPUT
  8800. if (!isdigit_str9(fn.list->text)) {
  8801. /* >&file, not >&fd */
  8802. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8803. ash_msg_and_raise_error("redir error");
  8804. redir->type = NTO2;
  8805. goto store_expfname;
  8806. }
  8807. #endif
  8808. fixredir(redir, fn.list->text, 1);
  8809. }
  8810. break;
  8811. }
  8812. }
  8813. }
  8814. /*
  8815. * Evaluate a pipeline. All the processes in the pipeline are children
  8816. * of the process creating the pipeline. (This differs from some versions
  8817. * of the shell, which make the last process in a pipeline the parent
  8818. * of all the rest.)
  8819. */
  8820. static int
  8821. evalpipe(union node *n, int flags)
  8822. {
  8823. struct job *jp;
  8824. struct nodelist *lp;
  8825. int pipelen;
  8826. int prevfd;
  8827. int pip[2];
  8828. int status = 0;
  8829. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8830. pipelen = 0;
  8831. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8832. pipelen++;
  8833. flags |= EV_EXIT;
  8834. INT_OFF;
  8835. if (n->npipe.pipe_backgnd == 0)
  8836. get_tty_state();
  8837. jp = makejob(/*n,*/ pipelen);
  8838. prevfd = -1;
  8839. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8840. prehash(lp->n);
  8841. pip[1] = -1;
  8842. if (lp->next) {
  8843. if (pipe(pip) < 0) {
  8844. close(prevfd);
  8845. ash_msg_and_raise_perror("can't create pipe");
  8846. }
  8847. }
  8848. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8849. /* child */
  8850. INT_ON;
  8851. if (pip[1] >= 0) {
  8852. close(pip[0]);
  8853. }
  8854. if (prevfd > 0) {
  8855. dup2(prevfd, 0);
  8856. close(prevfd);
  8857. }
  8858. if (pip[1] > 1) {
  8859. dup2(pip[1], 1);
  8860. close(pip[1]);
  8861. }
  8862. evaltreenr(lp->n, flags);
  8863. /* never returns */
  8864. }
  8865. /* parent */
  8866. if (prevfd >= 0)
  8867. close(prevfd);
  8868. prevfd = pip[0];
  8869. /* Don't want to trigger debugging */
  8870. if (pip[1] != -1)
  8871. close(pip[1]);
  8872. }
  8873. if (n->npipe.pipe_backgnd == 0) {
  8874. status = waitforjob(jp);
  8875. TRACE(("evalpipe: job done exit status %d\n", status));
  8876. }
  8877. INT_ON;
  8878. return status;
  8879. }
  8880. /* setinteractive needs this forward reference */
  8881. #if ENABLE_FEATURE_TAB_COMPLETION
  8882. static const char *ash_command_name(int i) FAST_FUNC;
  8883. #endif
  8884. /*
  8885. * Controls whether the shell is interactive or not.
  8886. */
  8887. static void
  8888. setinteractive(int on)
  8889. {
  8890. static smallint is_interactive;
  8891. if (++on == is_interactive)
  8892. return;
  8893. is_interactive = on;
  8894. setsignal(SIGINT);
  8895. setsignal(SIGQUIT);
  8896. setsignal(SIGTERM);
  8897. if (is_interactive > 1) {
  8898. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8899. /* Looks like they want an interactive shell */
  8900. static smallint did_banner;
  8901. if (!did_banner) {
  8902. /* note: ash and hush share this string */
  8903. out1fmt("\n\n%s %s\n"
  8904. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8905. "\n",
  8906. bb_banner,
  8907. "built-in shell (ash)"
  8908. );
  8909. did_banner = 1;
  8910. }
  8911. #endif
  8912. #if ENABLE_FEATURE_EDITING
  8913. if (!line_input_state) {
  8914. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8915. # if ENABLE_FEATURE_TAB_COMPLETION
  8916. line_input_state->get_exe_name = ash_command_name;
  8917. # endif
  8918. # if EDITING_HAS_sh_get_var
  8919. line_input_state->sh_get_var = lookupvar;
  8920. # endif
  8921. }
  8922. #endif
  8923. }
  8924. }
  8925. static void
  8926. optschanged(void)
  8927. {
  8928. #if DEBUG
  8929. opentrace();
  8930. #endif
  8931. setinteractive(iflag);
  8932. setjobctl(mflag);
  8933. #if ENABLE_FEATURE_EDITING_VI
  8934. if (line_input_state) {
  8935. if (viflag)
  8936. line_input_state->flags |= VI_MODE;
  8937. else
  8938. line_input_state->flags &= ~VI_MODE;
  8939. }
  8940. #else
  8941. viflag = 0; /* forcibly keep the option off */
  8942. #endif
  8943. }
  8944. struct localvar_list {
  8945. struct localvar_list *next;
  8946. struct localvar *lv;
  8947. };
  8948. static struct localvar_list *localvar_stack;
  8949. /*
  8950. * Called after a function returns.
  8951. * Interrupts must be off.
  8952. */
  8953. static void
  8954. poplocalvars(int keep)
  8955. {
  8956. struct localvar_list *ll;
  8957. struct localvar *lvp, *next;
  8958. struct var *vp;
  8959. INT_OFF;
  8960. ll = localvar_stack;
  8961. localvar_stack = ll->next;
  8962. next = ll->lv;
  8963. free(ll);
  8964. while ((lvp = next) != NULL) {
  8965. next = lvp->next;
  8966. vp = lvp->vp;
  8967. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8968. if (keep) {
  8969. int bits = VSTRFIXED;
  8970. if (lvp->flags != VUNSET) {
  8971. if (vp->var_text == lvp->text)
  8972. bits |= VTEXTFIXED;
  8973. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8974. free((char*)lvp->text);
  8975. }
  8976. vp->flags &= ~bits;
  8977. vp->flags |= (lvp->flags & bits);
  8978. if ((vp->flags &
  8979. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8980. unsetvar(vp->var_text);
  8981. } else if (vp == NULL) { /* $- saved */
  8982. memcpy(optlist, lvp->text, sizeof(optlist));
  8983. free((char*)lvp->text);
  8984. optschanged();
  8985. } else if (lvp->flags == VUNSET) {
  8986. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8987. unsetvar(vp->var_text);
  8988. } else {
  8989. if (vp->var_func)
  8990. vp->var_func(var_end(lvp->text));
  8991. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8992. free((char*)vp->var_text);
  8993. vp->flags = lvp->flags;
  8994. vp->var_text = lvp->text;
  8995. }
  8996. free(lvp);
  8997. }
  8998. INT_ON;
  8999. }
  9000. /*
  9001. * Create a new localvar environment.
  9002. */
  9003. static struct localvar_list *
  9004. pushlocalvars(int push)
  9005. {
  9006. struct localvar_list *ll;
  9007. struct localvar_list *top;
  9008. top = localvar_stack;
  9009. if (!push)
  9010. goto out;
  9011. INT_OFF;
  9012. ll = ckzalloc(sizeof(*ll));
  9013. /*ll->lv = NULL; - zalloc did it */
  9014. ll->next = top;
  9015. localvar_stack = ll;
  9016. INT_ON;
  9017. out:
  9018. return top;
  9019. }
  9020. static void
  9021. unwindlocalvars(struct localvar_list *stop)
  9022. {
  9023. while (localvar_stack != stop)
  9024. poplocalvars(0);
  9025. }
  9026. static int
  9027. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  9028. {
  9029. volatile struct shparam saveparam;
  9030. struct jmploc *volatile savehandler;
  9031. struct jmploc jmploc;
  9032. int e;
  9033. int savelineno;
  9034. int savefuncline;
  9035. char *savefuncname;
  9036. char *savetrap = NULL;
  9037. if (!Eflag) {
  9038. savetrap = trap[NTRAP_ERR];
  9039. trap[NTRAP_ERR] = NULL;
  9040. }
  9041. savelineno = lineno;
  9042. saveparam = shellparam;
  9043. savefuncline = funcline;
  9044. savefuncname = funcname;
  9045. savehandler = exception_handler;
  9046. e = setjmp(jmploc.loc);
  9047. if (e) {
  9048. goto funcdone;
  9049. }
  9050. INT_OFF;
  9051. exception_handler = &jmploc;
  9052. shellparam.malloced = 0;
  9053. func->count++;
  9054. funcname = func->n.ndefun.text;
  9055. funcline = func->n.ndefun.linno;
  9056. INT_ON;
  9057. shellparam.nparam = argc - 1;
  9058. shellparam.p = argv + 1;
  9059. #if ENABLE_ASH_GETOPTS
  9060. shellparam.optind = 1;
  9061. shellparam.optoff = -1;
  9062. #endif
  9063. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  9064. funcdone:
  9065. INT_OFF;
  9066. funcname = savefuncname;
  9067. if (savetrap) {
  9068. if (!trap[NTRAP_ERR])
  9069. trap[NTRAP_ERR] = savetrap;
  9070. else
  9071. free(savetrap);
  9072. }
  9073. funcline = savefuncline;
  9074. lineno = savelineno;
  9075. freefunc(func);
  9076. freeparam(&shellparam);
  9077. shellparam = saveparam;
  9078. exception_handler = savehandler;
  9079. INT_ON;
  9080. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  9081. return e;
  9082. }
  9083. /*
  9084. * Make a variable a local variable. When a variable is made local, it's
  9085. * value and flags are saved in a localvar structure. The saved values
  9086. * will be restored when the shell function returns. We handle the name
  9087. * "-" as a special case: it makes changes to "set +-options" local
  9088. * (options will be restored on return from the function).
  9089. */
  9090. static void
  9091. mklocal(char *name, int flags)
  9092. {
  9093. struct localvar *lvp;
  9094. struct var **vpp;
  9095. struct var *vp;
  9096. char *eq = strchr(name, '=');
  9097. INT_OFF;
  9098. /* Cater for duplicate "local". Examples:
  9099. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  9100. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  9101. */
  9102. lvp = localvar_stack->lv;
  9103. while (lvp) {
  9104. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  9105. if (eq)
  9106. setvareq(name, 0);
  9107. /* else:
  9108. * it's a duplicate "local VAR" declaration, do nothing
  9109. */
  9110. goto ret;
  9111. }
  9112. lvp = lvp->next;
  9113. }
  9114. lvp = ckzalloc(sizeof(*lvp));
  9115. if (LONE_DASH(name)) {
  9116. char *p;
  9117. p = ckmalloc(sizeof(optlist));
  9118. lvp->text = memcpy(p, optlist, sizeof(optlist));
  9119. vp = NULL;
  9120. } else {
  9121. vpp = hashvar(name);
  9122. vp = *findvar(vpp, name);
  9123. if (vp == NULL) {
  9124. /* variable did not exist yet */
  9125. if (eq)
  9126. vp = setvareq(name, VSTRFIXED | flags);
  9127. else
  9128. vp = setvar(name, NULL, VSTRFIXED | flags);
  9129. lvp->flags = VUNSET;
  9130. } else {
  9131. lvp->text = vp->var_text;
  9132. lvp->flags = vp->flags;
  9133. /* make sure neither "struct var" nor string gets freed
  9134. * during (un)setting:
  9135. */
  9136. vp->flags |= VSTRFIXED|VTEXTFIXED;
  9137. if (eq)
  9138. setvareq(name, flags);
  9139. else
  9140. /* "local VAR" unsets VAR: */
  9141. unsetvar(name);
  9142. }
  9143. }
  9144. lvp->vp = vp;
  9145. lvp->next = localvar_stack->lv;
  9146. localvar_stack->lv = lvp;
  9147. ret:
  9148. INT_ON;
  9149. }
  9150. /*
  9151. * The "local" command.
  9152. */
  9153. static int FAST_FUNC
  9154. localcmd(int argc UNUSED_PARAM, char **argv)
  9155. {
  9156. char *name;
  9157. if (!localvar_stack)
  9158. ash_msg_and_raise_error("not in a function");
  9159. argv = argptr;
  9160. while ((name = *argv++) != NULL) {
  9161. mklocal(name, 0);
  9162. }
  9163. return 0;
  9164. }
  9165. static int FAST_FUNC
  9166. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9167. {
  9168. return 1;
  9169. }
  9170. static int FAST_FUNC
  9171. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9172. {
  9173. return 0;
  9174. }
  9175. static int FAST_FUNC
  9176. execcmd(int argc UNUSED_PARAM, char **argv)
  9177. {
  9178. optionarg = NULL;
  9179. while (nextopt("a:") != '\0')
  9180. /* nextopt() sets optionarg to "-a ARGV0" */;
  9181. argv = argptr;
  9182. if (argv[0]) {
  9183. char *prog;
  9184. iflag = 0; /* exit on error */
  9185. mflag = 0;
  9186. optschanged();
  9187. /* We should set up signals for "exec CMD"
  9188. * the same way as for "CMD" without "exec".
  9189. * But optschanged->setinteractive->setsignal
  9190. * still thought we are a root shell. Therefore, for example,
  9191. * SIGQUIT is still set to IGN. Fix it:
  9192. */
  9193. shlvl++;
  9194. setsignal(SIGQUIT);
  9195. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9196. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9197. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9198. prog = argv[0];
  9199. if (optionarg)
  9200. argv[0] = optionarg;
  9201. shellexec(prog, argv, pathval(), 0);
  9202. /* NOTREACHED */
  9203. }
  9204. return 0;
  9205. }
  9206. /*
  9207. * The return command.
  9208. */
  9209. static int FAST_FUNC
  9210. returncmd(int argc UNUSED_PARAM, char **argv)
  9211. {
  9212. int skip;
  9213. int status;
  9214. /*
  9215. * If called outside a function, do what ksh does;
  9216. * skip the rest of the file.
  9217. */
  9218. if (argv[1]) {
  9219. skip = SKIPFUNC;
  9220. status = number(argv[1]);
  9221. } else {
  9222. skip = SKIPFUNCDEF;
  9223. status = exitstatus;
  9224. }
  9225. evalskip = skip;
  9226. return status;
  9227. }
  9228. /* Forward declarations for builtintab[] */
  9229. static int breakcmd(int, char **) FAST_FUNC;
  9230. static int dotcmd(int, char **) FAST_FUNC;
  9231. static int evalcmd(int, char **, int) FAST_FUNC;
  9232. static int exitcmd(int, char **) FAST_FUNC;
  9233. static int exportcmd(int, char **) FAST_FUNC;
  9234. #if ENABLE_ASH_GETOPTS
  9235. static int getoptscmd(int, char **) FAST_FUNC;
  9236. #endif
  9237. #if ENABLE_ASH_HELP
  9238. static int helpcmd(int, char **) FAST_FUNC;
  9239. #endif
  9240. #if MAX_HISTORY
  9241. static int historycmd(int, char **) FAST_FUNC;
  9242. #endif
  9243. #if ENABLE_FEATURE_SH_MATH
  9244. static int letcmd(int, char **) FAST_FUNC;
  9245. #endif
  9246. static int readcmd(int, char **) FAST_FUNC;
  9247. static int setcmd(int, char **) FAST_FUNC;
  9248. static int shiftcmd(int, char **) FAST_FUNC;
  9249. static int timescmd(int, char **) FAST_FUNC;
  9250. static int trapcmd(int, char **) FAST_FUNC;
  9251. static int umaskcmd(int, char **) FAST_FUNC;
  9252. static int unsetcmd(int, char **) FAST_FUNC;
  9253. static int ulimitcmd(int, char **) FAST_FUNC;
  9254. #define BUILTIN_NOSPEC "0"
  9255. #define BUILTIN_SPECIAL "1"
  9256. #define BUILTIN_REGULAR "2"
  9257. #define BUILTIN_SPEC_REG "3"
  9258. #define BUILTIN_ASSIGN "4"
  9259. #define BUILTIN_SPEC_ASSG "5"
  9260. #define BUILTIN_REG_ASSG "6"
  9261. #define BUILTIN_SPEC_REG_ASSG "7"
  9262. /* Stubs for calling non-FAST_FUNC's */
  9263. #if ENABLE_ASH_ECHO
  9264. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9265. #endif
  9266. #if ENABLE_ASH_PRINTF
  9267. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9268. #endif
  9269. #if ENABLE_ASH_TEST || BASH_TEST2
  9270. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9271. #endif
  9272. #if ENABLE_ASH_SLEEP
  9273. static int FAST_FUNC sleepcmd(int argc, char **argv) { return sleep_main(argc, argv); }
  9274. #endif
  9275. /* Keep these in proper order since it is searched via bsearch() */
  9276. static const struct builtincmd builtintab[] = {
  9277. { BUILTIN_SPEC_REG "." , dotcmd },
  9278. { BUILTIN_SPEC_REG ":" , truecmd },
  9279. #if ENABLE_ASH_TEST
  9280. { BUILTIN_REGULAR "[" , testcmd },
  9281. #endif
  9282. #if BASH_TEST2
  9283. { BUILTIN_REGULAR "[[" , testcmd },
  9284. #endif
  9285. #if ENABLE_ASH_ALIAS
  9286. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9287. #endif
  9288. #if JOBS
  9289. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9290. #endif
  9291. { BUILTIN_SPEC_REG "break" , breakcmd },
  9292. { BUILTIN_REGULAR "cd" , cdcmd },
  9293. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9294. #if ENABLE_ASH_CMDCMD
  9295. { BUILTIN_REGULAR "command" , commandcmd },
  9296. #endif
  9297. { BUILTIN_SPEC_REG "continue", breakcmd },
  9298. #if ENABLE_ASH_ECHO
  9299. { BUILTIN_REGULAR "echo" , echocmd },
  9300. #endif
  9301. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9302. { BUILTIN_SPEC_REG "exec" , execcmd },
  9303. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9304. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9305. { BUILTIN_REGULAR "false" , falsecmd },
  9306. #if JOBS
  9307. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9308. #endif
  9309. #if ENABLE_ASH_GETOPTS
  9310. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9311. #endif
  9312. { BUILTIN_REGULAR "hash" , hashcmd },
  9313. #if ENABLE_ASH_HELP
  9314. { BUILTIN_NOSPEC "help" , helpcmd },
  9315. #endif
  9316. #if MAX_HISTORY
  9317. { BUILTIN_NOSPEC "history" , historycmd },
  9318. #endif
  9319. #if JOBS
  9320. { BUILTIN_REGULAR "jobs" , jobscmd },
  9321. { BUILTIN_REGULAR "kill" , killcmd },
  9322. #endif
  9323. #if ENABLE_FEATURE_SH_MATH
  9324. { BUILTIN_NOSPEC "let" , letcmd },
  9325. #endif
  9326. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9327. #if ENABLE_ASH_PRINTF
  9328. { BUILTIN_REGULAR "printf" , printfcmd },
  9329. #endif
  9330. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9331. { BUILTIN_REGULAR "read" , readcmd },
  9332. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9333. { BUILTIN_SPEC_REG "return" , returncmd },
  9334. { BUILTIN_SPEC_REG "set" , setcmd },
  9335. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9336. #if ENABLE_ASH_SLEEP
  9337. { BUILTIN_REGULAR "sleep" , sleepcmd },
  9338. #endif
  9339. #if BASH_SOURCE
  9340. { BUILTIN_SPEC_REG "source" , dotcmd },
  9341. #endif
  9342. #if ENABLE_ASH_TEST
  9343. { BUILTIN_REGULAR "test" , testcmd },
  9344. #endif
  9345. { BUILTIN_SPEC_REG "times" , timescmd },
  9346. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9347. { BUILTIN_REGULAR "true" , truecmd },
  9348. { BUILTIN_REGULAR "type" , typecmd },
  9349. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9350. { BUILTIN_REGULAR "umask" , umaskcmd },
  9351. #if ENABLE_ASH_ALIAS
  9352. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9353. #endif
  9354. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9355. { BUILTIN_REGULAR "wait" , waitcmd },
  9356. };
  9357. /* Should match the above table! */
  9358. #define COMMANDCMD (builtintab + \
  9359. /* . : */ 2 + \
  9360. /* [ */ 1 * ENABLE_ASH_TEST + \
  9361. /* [[ */ 1 * BASH_TEST2 + \
  9362. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9363. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9364. /* break cd cddir */ 3)
  9365. #define EVALCMD (COMMANDCMD + \
  9366. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9367. /* continue */ 1 + \
  9368. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9369. 0)
  9370. #define EXECCMD (EVALCMD + \
  9371. /* eval */ 1)
  9372. /*
  9373. * Search the table of builtin commands.
  9374. */
  9375. static int
  9376. pstrcmp1(const void *a, const void *b)
  9377. {
  9378. return strcmp((char*)a, *(char**)b + 1);
  9379. }
  9380. static struct builtincmd *
  9381. find_builtin(const char *name)
  9382. {
  9383. struct builtincmd *bp;
  9384. bp = bsearch(
  9385. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9386. pstrcmp1
  9387. );
  9388. return bp;
  9389. }
  9390. #if ENABLE_FEATURE_TAB_COMPLETION
  9391. static const char * FAST_FUNC
  9392. ash_command_name(int i)
  9393. {
  9394. int n;
  9395. if (/*i >= 0 &&*/ i < ARRAY_SIZE(builtintab))
  9396. return builtintab[i].name + 1;
  9397. i -= ARRAY_SIZE(builtintab);
  9398. for (n = 0; n < CMDTABLESIZE; n++) {
  9399. struct tblentry *cmdp;
  9400. for (cmdp = cmdtable[n]; cmdp; cmdp = cmdp->next) {
  9401. if (cmdp->cmdtype == CMDFUNCTION && --i < 0)
  9402. return cmdp->cmdname;
  9403. }
  9404. }
  9405. # if ENABLE_ASH_ALIAS
  9406. for (n = 0; n < ATABSIZE; n++) {
  9407. struct alias *ap;
  9408. for (ap = atab[n]; ap; ap = ap->next) {
  9409. if (--i < 0)
  9410. return ap->name;
  9411. }
  9412. }
  9413. #endif
  9414. return NULL;
  9415. }
  9416. #endif
  9417. /*
  9418. * Execute a simple command.
  9419. */
  9420. static void unwindfiles(struct parsefile *stop);
  9421. static int
  9422. isassignment(const char *p)
  9423. {
  9424. const char *q = endofname(p);
  9425. if (p == q)
  9426. return 0;
  9427. return *q == '=';
  9428. }
  9429. static int FAST_FUNC
  9430. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9431. {
  9432. /* Preserve exitstatus of a previous possible redirection
  9433. * as POSIX mandates */
  9434. return back_exitstatus;
  9435. }
  9436. static int
  9437. evalcommand(union node *cmd, int flags)
  9438. {
  9439. static const struct builtincmd null_bltin = {
  9440. BUILTIN_REGULAR "", bltincmd
  9441. };
  9442. struct localvar_list *localvar_stop;
  9443. struct parsefile *file_stop;
  9444. struct redirtab *redir_stop;
  9445. union node *argp;
  9446. struct arglist arglist;
  9447. struct arglist varlist;
  9448. char **argv;
  9449. int argc;
  9450. struct strlist *osp;
  9451. const struct strlist *sp;
  9452. struct cmdentry cmdentry;
  9453. struct job *jp;
  9454. char *lastarg;
  9455. const char *path;
  9456. int spclbltin;
  9457. int cmd_flag;
  9458. int status;
  9459. char **nargv;
  9460. smallint cmd_is_exec;
  9461. int vflags;
  9462. int vlocal;
  9463. errlinno = lineno = cmd->ncmd.linno;
  9464. /* First expand the arguments. */
  9465. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9466. #if BASH_PROCESS_SUBST
  9467. redir_stop = redirlist;
  9468. #endif
  9469. file_stop = g_parsefile;
  9470. back_exitstatus = 0;
  9471. cmdentry.cmdtype = CMDBUILTIN;
  9472. cmdentry.u.cmd = &null_bltin;
  9473. varlist.lastp = &varlist.list;
  9474. *varlist.lastp = NULL;
  9475. arglist.lastp = &arglist.list;
  9476. *arglist.lastp = NULL;
  9477. cmd_flag = 0;
  9478. cmd_is_exec = 0;
  9479. spclbltin = -1;
  9480. vflags = 0;
  9481. vlocal = 0;
  9482. path = NULL;
  9483. argc = 0;
  9484. argp = cmd->ncmd.args;
  9485. osp = fill_arglist(&arglist, &argp);
  9486. if (osp) {
  9487. int pseudovarflag = 0;
  9488. for (;;) {
  9489. find_command(arglist.list->text, &cmdentry,
  9490. cmd_flag | DO_REGBLTIN, pathval());
  9491. vlocal++;
  9492. /* implement bltin and command here */
  9493. if (cmdentry.cmdtype != CMDBUILTIN)
  9494. break;
  9495. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9496. if (spclbltin < 0) {
  9497. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9498. vlocal = !spclbltin;
  9499. }
  9500. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9501. #if ENABLE_ASH_CMDCMD
  9502. if (cmdentry.u.cmd != COMMANDCMD)
  9503. break;
  9504. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9505. if (!cmd_flag)
  9506. #endif
  9507. break;
  9508. }
  9509. for (; argp; argp = argp->narg.next)
  9510. expandarg(argp, &arglist,
  9511. pseudovarflag &&
  9512. isassignment(argp->narg.text) ?
  9513. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9514. for (sp = arglist.list; sp; sp = sp->next)
  9515. argc++;
  9516. if (cmd_is_exec && argc > 1)
  9517. vflags = VEXPORT;
  9518. }
  9519. localvar_stop = pushlocalvars(vlocal);
  9520. /* Reserve one extra spot at the front for shellexec. */
  9521. nargv = stalloc(sizeof(char *) * (argc + 2));
  9522. argv = ++nargv;
  9523. for (sp = arglist.list; sp; sp = sp->next) {
  9524. TRACE(("evalcommand arg: %s\n", sp->text));
  9525. *nargv++ = sp->text;
  9526. }
  9527. *nargv = NULL;
  9528. lastarg = NULL;
  9529. if (iflag && funcline == 0 && argc > 0)
  9530. lastarg = nargv[-1];
  9531. expredir(cmd->ncmd.redirect);
  9532. #if !BASH_PROCESS_SUBST
  9533. redir_stop = pushredir(cmd->ncmd.redirect);
  9534. #else
  9535. pushredir(cmd->ncmd.redirect);
  9536. #endif
  9537. preverrout_fd = 2;
  9538. if (BASH_XTRACEFD && xflag) {
  9539. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9540. * we do not emulate this. We only use its value.
  9541. */
  9542. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9543. if (xtracefd && is_number(xtracefd))
  9544. preverrout_fd = atoi(xtracefd);
  9545. }
  9546. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9547. if (status) {
  9548. bail:
  9549. exitstatus = status;
  9550. /* We have a redirection error. */
  9551. if (spclbltin > 0)
  9552. raise_exception(EXERROR); /* does not return */
  9553. goto out;
  9554. }
  9555. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9556. struct strlist **spp;
  9557. spp = varlist.lastp;
  9558. expandarg(argp, &varlist, EXP_VARTILDE);
  9559. if (vlocal)
  9560. mklocal((*spp)->text, VEXPORT);
  9561. else
  9562. setvareq((*spp)->text, vflags);
  9563. }
  9564. /* Print the command if xflag is set. */
  9565. if (xflag && !inps4) {
  9566. const char *pfx = "";
  9567. inps4 = 1;
  9568. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9569. inps4 = 0;
  9570. sp = varlist.list;
  9571. while (sp) {
  9572. char *varval = sp->text;
  9573. char *eq = strchrnul(varval, '=');
  9574. if (*eq)
  9575. eq++;
  9576. fdprintf(preverrout_fd, "%s%.*s%s",
  9577. pfx,
  9578. (int)(eq - varval), varval,
  9579. maybe_single_quote(eq)
  9580. );
  9581. sp = sp->next;
  9582. pfx = " ";
  9583. }
  9584. sp = arglist.list;
  9585. while (sp) {
  9586. fdprintf(preverrout_fd, "%s%s",
  9587. pfx,
  9588. /* always quote if matches reserved word: */
  9589. findkwd(sp->text)
  9590. ? single_quote(sp->text)
  9591. : maybe_single_quote(sp->text)
  9592. );
  9593. sp = sp->next;
  9594. pfx = " ";
  9595. }
  9596. safe_write(preverrout_fd, "\n", 1);
  9597. }
  9598. /* Now locate the command. */
  9599. if (cmdentry.cmdtype != CMDBUILTIN
  9600. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9601. ) {
  9602. path = path ? path : pathval();
  9603. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9604. }
  9605. jp = NULL;
  9606. /* Execute the command. */
  9607. switch (cmdentry.cmdtype) {
  9608. case CMDUNKNOWN:
  9609. status = 127;
  9610. flush_stdout_stderr();
  9611. goto bail;
  9612. default: {
  9613. #if ENABLE_FEATURE_SH_STANDALONE \
  9614. && ENABLE_FEATURE_SH_NOFORK \
  9615. && NUM_APPLETS > 1
  9616. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9617. * around run_nofork_applet() call.
  9618. * (2) Should this check also be done in forkshell()?
  9619. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9620. */
  9621. /* find_command() encodes applet_no as (-2 - applet_no) */
  9622. int applet_no = (- cmdentry.u.index - 2);
  9623. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9624. char **sv_environ;
  9625. INT_OFF;
  9626. sv_environ = environ;
  9627. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9628. /*
  9629. * Run <applet>_main().
  9630. * Signals (^C) can't interrupt here.
  9631. * Otherwise we can mangle stdio or malloc internal state.
  9632. * This makes applets which can run for a long time
  9633. * and/or wait for user input ineligible for NOFORK:
  9634. * for example, "yes" or "rm" (rm -i waits for input).
  9635. */
  9636. exitstatus = run_nofork_applet(applet_no, argv);
  9637. environ = sv_environ;
  9638. /*
  9639. * Try enabling NOFORK for "yes" applet.
  9640. * ^C _will_ stop it (write returns EINTR),
  9641. * but this causes stdout FILE to be stuck
  9642. * and needing clearerr(). What if other applets
  9643. * also can get EINTRs? Do we need to switch
  9644. * our signals to SA_RESTART?
  9645. */
  9646. /*clearerr(stdout);*/
  9647. INT_ON;
  9648. break;
  9649. }
  9650. #endif
  9651. /* Can we avoid forking? For example, very last command
  9652. * in a script or a subshell does not need forking,
  9653. * we can just exec it.
  9654. */
  9655. if (!(flags & EV_EXIT) || may_have_traps) {
  9656. /* No, forking off a child is necessary */
  9657. INT_OFF;
  9658. get_tty_state();
  9659. jp = makejob(/*cmd,*/ 1);
  9660. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9661. /* parent */
  9662. break;
  9663. }
  9664. /* child */
  9665. FORCE_INT_ON;
  9666. /* fall through to exec'ing external program */
  9667. }
  9668. shellexec(argv[0], argv, path, cmdentry.u.index);
  9669. /* NOTREACHED */
  9670. } /* default */
  9671. case CMDBUILTIN:
  9672. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9673. && !(exception_type == EXERROR && spclbltin <= 0)
  9674. ) {
  9675. raise:
  9676. longjmp(exception_handler->loc, 1);
  9677. }
  9678. break;
  9679. case CMDFUNCTION:
  9680. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9681. goto raise;
  9682. break;
  9683. } /* switch */
  9684. status = waitforjob(jp);
  9685. if (jp)
  9686. TRACE(("forked child exited with %d\n", status));
  9687. FORCE_INT_ON;
  9688. out:
  9689. if (cmd->ncmd.redirect)
  9690. popredir(/*drop:*/ cmd_is_exec);
  9691. unwindredir(redir_stop);
  9692. unwindfiles(file_stop);
  9693. unwindlocalvars(localvar_stop);
  9694. if (lastarg) {
  9695. /* dsl: I think this is intended to be used to support
  9696. * '_' in 'vi' command mode during line editing...
  9697. * However I implemented that within libedit itself.
  9698. */
  9699. setvar0("_", lastarg);
  9700. }
  9701. return status;
  9702. }
  9703. static int
  9704. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9705. {
  9706. char *volatile savecmdname;
  9707. struct jmploc *volatile savehandler;
  9708. struct jmploc jmploc;
  9709. int status;
  9710. int i;
  9711. savecmdname = commandname;
  9712. savehandler = exception_handler;
  9713. i = setjmp(jmploc.loc);
  9714. if (i)
  9715. goto cmddone;
  9716. exception_handler = &jmploc;
  9717. commandname = argv[0];
  9718. argptr = argv + 1;
  9719. optptr = NULL; /* initialize nextopt */
  9720. if (cmd == EVALCMD)
  9721. status = evalcmd(argc, argv, flags);
  9722. else
  9723. status = (*cmd->builtin)(argc, argv);
  9724. flush_stdout_stderr();
  9725. status |= ferror(stdout);
  9726. exitstatus = status;
  9727. cmddone:
  9728. clearerr(stdout);
  9729. commandname = savecmdname;
  9730. exception_handler = savehandler;
  9731. return i;
  9732. }
  9733. static int
  9734. goodname(const char *p)
  9735. {
  9736. return endofname(p)[0] == '\0';
  9737. }
  9738. /*
  9739. * Search for a command. This is called before we fork so that the
  9740. * location of the command will be available in the parent as well as
  9741. * the child. The check for "goodname" is an overly conservative
  9742. * check that the name will not be subject to expansion.
  9743. */
  9744. static void
  9745. prehash(union node *n)
  9746. {
  9747. struct cmdentry entry;
  9748. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9749. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9750. }
  9751. /* ============ Builtin commands
  9752. *
  9753. * Builtin commands whose functions are closely tied to evaluation
  9754. * are implemented here.
  9755. */
  9756. /*
  9757. * Handle break and continue commands. Break, continue, and return are
  9758. * all handled by setting the evalskip flag. The evaluation routines
  9759. * above all check this flag, and if it is set they start skipping
  9760. * commands rather than executing them. The variable skipcount is
  9761. * the number of loops to break/continue, or the number of function
  9762. * levels to return. (The latter is always 1.) It should probably
  9763. * be an error to break out of more loops than exist, but it isn't
  9764. * in the standard shell so we don't make it one here.
  9765. */
  9766. static int FAST_FUNC
  9767. breakcmd(int argc UNUSED_PARAM, char **argv)
  9768. {
  9769. int n = argv[1] ? number(argv[1]) : 1;
  9770. if (n <= 0)
  9771. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9772. if (n > loopnest)
  9773. n = loopnest;
  9774. if (n > 0) {
  9775. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9776. skipcount = n;
  9777. }
  9778. return 0;
  9779. }
  9780. /*
  9781. * This implements the input routines used by the parser.
  9782. */
  9783. enum {
  9784. INPUT_PUSH_FILE = 1,
  9785. INPUT_NOFILE_OK = 2,
  9786. };
  9787. static smallint checkkwd;
  9788. /* values of checkkwd variable */
  9789. #define CHKALIAS 0x1
  9790. #define CHKKWD 0x2
  9791. #define CHKNL 0x4
  9792. #define CHKEOFMARK 0x8
  9793. /*
  9794. * Push a string back onto the input at this current parsefile level.
  9795. * We handle aliases this way.
  9796. */
  9797. #if !ENABLE_ASH_ALIAS
  9798. #define pushstring(s, ap) pushstring(s)
  9799. #endif
  9800. static void
  9801. pushstring(char *s, struct alias *ap)
  9802. {
  9803. struct strpush *sp;
  9804. int len;
  9805. len = strlen(s);
  9806. INT_OFF;
  9807. if (g_parsefile->strpush || g_parsefile->spfree) {
  9808. sp = ckzalloc(sizeof(*sp));
  9809. sp->prev = g_parsefile->strpush;
  9810. } else {
  9811. sp = &(g_parsefile->basestrpush);
  9812. }
  9813. g_parsefile->strpush = sp;
  9814. sp->prev_string = g_parsefile->next_to_pgetc;
  9815. sp->prev_left_in_line = g_parsefile->left_in_line;
  9816. sp->unget = g_parsefile->unget;
  9817. sp->spfree = g_parsefile->spfree;
  9818. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9819. #if ENABLE_ASH_ALIAS
  9820. sp->ap = ap;
  9821. if (ap) {
  9822. ap->flag |= ALIASINUSE;
  9823. sp->string = s;
  9824. }
  9825. #endif
  9826. g_parsefile->next_to_pgetc = s;
  9827. g_parsefile->left_in_line = len;
  9828. g_parsefile->unget = 0;
  9829. g_parsefile->spfree = NULL;
  9830. INT_ON;
  9831. }
  9832. static void popstring(void)
  9833. {
  9834. struct strpush *sp = g_parsefile->strpush;
  9835. INT_OFF;
  9836. #if ENABLE_ASH_ALIAS
  9837. if (sp->ap) {
  9838. if (g_parsefile->next_to_pgetc[-1] == ' '
  9839. || g_parsefile->next_to_pgetc[-1] == '\t'
  9840. ) {
  9841. checkkwd |= CHKALIAS;
  9842. }
  9843. if (sp->string != sp->ap->val) {
  9844. free(sp->string);
  9845. }
  9846. }
  9847. #endif
  9848. g_parsefile->next_to_pgetc = sp->prev_string;
  9849. g_parsefile->left_in_line = sp->prev_left_in_line;
  9850. g_parsefile->unget = sp->unget;
  9851. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9852. g_parsefile->strpush = sp->prev;
  9853. g_parsefile->spfree = sp;
  9854. INT_ON;
  9855. }
  9856. static int
  9857. preadfd(void)
  9858. {
  9859. int nr;
  9860. char *buf = g_parsefile->buf;
  9861. g_parsefile->next_to_pgetc = buf;
  9862. #if ENABLE_FEATURE_EDITING
  9863. /* retry: */
  9864. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9865. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9866. else {
  9867. # if ENABLE_ASH_IDLE_TIMEOUT
  9868. int timeout = -1;
  9869. const char *tmout_var = lookupvar("TMOUT");
  9870. if (tmout_var) {
  9871. timeout = atoi(tmout_var) * 1000;
  9872. if (timeout <= 0)
  9873. timeout = -1;
  9874. }
  9875. line_input_state->timeout = timeout;
  9876. # endif
  9877. # if ENABLE_FEATURE_TAB_COMPLETION
  9878. line_input_state->path_lookup = pathval();
  9879. # endif
  9880. reinit_unicode_for_ash();
  9881. again:
  9882. /* For shell, LI_INTERRUPTIBLE is set:
  9883. * read_line_input will abort on either
  9884. * getting EINTR in poll() and bb_got_signal became != 0,
  9885. * or if it sees bb_got_signal != 0
  9886. * (IOW: if signal arrives before poll() is reached).
  9887. * Interactive testcases:
  9888. * (while kill -INT $$; do sleep 1; done) &
  9889. * #^^^ prints ^C, prints prompt, repeats
  9890. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  9891. * #^^^ prints ^C, prints "I", prints prompt, repeats
  9892. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  9893. * #^^^ prints "T", prints prompt, repeats
  9894. * #(bash 5.0.17 exits after first "T", looks like a bug)
  9895. */
  9896. bb_got_signal = 0;
  9897. INT_OFF; /* no longjmp'ing out of read_line_input please */
  9898. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9899. if (bb_got_signal == SIGINT)
  9900. write(STDOUT_FILENO, "^C\n", 3);
  9901. INT_ON; /* here non-blocked SIGINT will longjmp */
  9902. if (nr == 0) {
  9903. /* ^C pressed, "convert" to SIGINT */
  9904. write(STDOUT_FILENO, "^C\n", 3);
  9905. raise(SIGINT); /* here non-blocked SIGINT will longjmp */
  9906. /* raise(SIGINT) did not work! (e.g. if SIGINT
  9907. * is SIG_IGNed on startup, it stays SIG_IGNed)
  9908. */
  9909. if (trap[SIGINT]) {
  9910. empty_line_input:
  9911. buf[0] = '\n';
  9912. buf[1] = '\0';
  9913. return 1;
  9914. }
  9915. exitstatus = 128 + SIGINT;
  9916. /* bash behavior on ^C + ignored SIGINT: */
  9917. goto again;
  9918. }
  9919. if (nr < 0) {
  9920. if (errno == 0) {
  9921. /* ^D pressed */
  9922. nr = 0;
  9923. }
  9924. else if (errno == EINTR) { /* got signal? */
  9925. if (bb_got_signal != SIGINT)
  9926. write(STDOUT_FILENO, "\n", 1);
  9927. goto empty_line_input;
  9928. }
  9929. # if ENABLE_ASH_IDLE_TIMEOUT
  9930. else if (errno == EAGAIN && timeout > 0) {
  9931. puts("\007timed out waiting for input: auto-logout");
  9932. exitshell();
  9933. }
  9934. # endif
  9935. }
  9936. }
  9937. #else
  9938. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9939. #endif
  9940. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9941. if (nr < 0) {
  9942. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9943. int flags = fcntl(0, F_GETFL);
  9944. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9945. flags &= ~O_NONBLOCK;
  9946. if (fcntl(0, F_SETFL, flags) >= 0) {
  9947. out2str("sh: turning off NDELAY mode\n");
  9948. goto retry;
  9949. }
  9950. }
  9951. }
  9952. }
  9953. #endif
  9954. return nr;
  9955. }
  9956. /*
  9957. * Refill the input buffer and return the next input character:
  9958. *
  9959. * 1) If a string was pushed back on the input, pop it;
  9960. * 2) If we are reading from a string we can't refill the buffer, return EOF.
  9961. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9962. * 4) Process input up to the next newline, deleting nul characters.
  9963. */
  9964. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9965. #define pgetc_debug(...) ((void)0)
  9966. static int __pgetc(void);
  9967. static int
  9968. preadbuffer(void)
  9969. {
  9970. char *q;
  9971. int more;
  9972. if (unlikely(g_parsefile->strpush)) {
  9973. popstring();
  9974. return __pgetc();
  9975. }
  9976. if (g_parsefile->buf == NULL) {
  9977. pgetc_debug("preadbuffer PEOF1");
  9978. return PEOF;
  9979. }
  9980. more = g_parsefile->left_in_buffer;
  9981. if (more <= 0) {
  9982. flush_stdout_stderr();
  9983. again:
  9984. more = preadfd();
  9985. if (more <= 0) {
  9986. g_parsefile->left_in_buffer = g_parsefile->left_in_line = 0;
  9987. pgetc_debug("preadbuffer PEOF2");
  9988. return PEOF;
  9989. }
  9990. }
  9991. /* Find out where's the end of line.
  9992. * Set g_parsefile->left_in_line
  9993. * and g_parsefile->left_in_buffer acordingly.
  9994. * NUL chars are deleted.
  9995. */
  9996. q = g_parsefile->next_to_pgetc;
  9997. for (;;) {
  9998. char c;
  9999. more--;
  10000. c = *q;
  10001. if (c == '\0') {
  10002. memmove(q, q + 1, more);
  10003. } else {
  10004. q++;
  10005. if (c == '\n') {
  10006. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  10007. break;
  10008. }
  10009. }
  10010. if (more <= 0) {
  10011. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  10012. if (g_parsefile->left_in_line < 0)
  10013. goto again;
  10014. break;
  10015. }
  10016. }
  10017. g_parsefile->left_in_buffer = more;
  10018. if (vflag) {
  10019. char save = *q;
  10020. *q = '\0';
  10021. out2str(g_parsefile->next_to_pgetc);
  10022. *q = save;
  10023. }
  10024. pgetc_debug("preadbuffer at %d:%p'%s'",
  10025. g_parsefile->left_in_line,
  10026. g_parsefile->next_to_pgetc,
  10027. g_parsefile->next_to_pgetc);
  10028. return (unsigned char)*g_parsefile->next_to_pgetc++;
  10029. }
  10030. static void
  10031. nlprompt(void)
  10032. {
  10033. if (trap_depth == 0)
  10034. g_parsefile->linno++;
  10035. setprompt_if(doprompt, 2);
  10036. }
  10037. static void
  10038. nlnoprompt(void)
  10039. {
  10040. if (trap_depth == 0)
  10041. g_parsefile->linno++;
  10042. needprompt = doprompt;
  10043. }
  10044. static void freestrings(struct strpush *sp)
  10045. {
  10046. INT_OFF;
  10047. do {
  10048. struct strpush *psp;
  10049. #if ENABLE_ASH_ALIAS
  10050. if (sp->ap) {
  10051. sp->ap->flag &= ~ALIASINUSE;
  10052. if (sp->ap->flag & ALIASDEAD) {
  10053. unalias(sp->ap->name);
  10054. }
  10055. }
  10056. #endif
  10057. psp = sp;
  10058. sp = sp->spfree;
  10059. if (psp != &(g_parsefile->basestrpush))
  10060. free(psp);
  10061. } while (sp);
  10062. g_parsefile->spfree = NULL;
  10063. INT_ON;
  10064. }
  10065. static int __pgetc(void)
  10066. {
  10067. int c;
  10068. pgetc_debug("pgetc at %d:%p'%s'",
  10069. g_parsefile->left_in_line,
  10070. g_parsefile->next_to_pgetc,
  10071. g_parsefile->next_to_pgetc);
  10072. if (g_parsefile->unget)
  10073. return g_parsefile->lastc[--g_parsefile->unget];
  10074. if (--g_parsefile->left_in_line >= 0)
  10075. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  10076. else
  10077. c = preadbuffer();
  10078. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  10079. g_parsefile->lastc[0] = c;
  10080. return c;
  10081. }
  10082. /*
  10083. * Read a character from the script, returning PEOF on end of file.
  10084. * Nul characters in the input are silently discarded.
  10085. */
  10086. static int pgetc(void)
  10087. {
  10088. struct strpush *sp = g_parsefile->spfree;
  10089. if (unlikely(sp))
  10090. freestrings(sp);
  10091. return __pgetc();
  10092. }
  10093. /*
  10094. * Undo a call to pgetc. Only two characters may be pushed back.
  10095. * PEOF may be pushed back.
  10096. */
  10097. static void
  10098. pungetc(void)
  10099. {
  10100. g_parsefile->unget++;
  10101. }
  10102. /* This one eats backslash+newline */
  10103. static int
  10104. pgetc_eatbnl(void)
  10105. {
  10106. int c;
  10107. while ((c = pgetc()) == '\\') {
  10108. if (pgetc() != '\n') {
  10109. pungetc();
  10110. break;
  10111. }
  10112. nlprompt();
  10113. }
  10114. return c;
  10115. }
  10116. struct synstack {
  10117. smalluint syntax;
  10118. uint8_t innerdq :1;
  10119. uint8_t varpushed :1;
  10120. uint8_t dblquote :1;
  10121. int varnest; /* levels of variables expansion */
  10122. int dqvarnest; /* levels of variables expansion within double quotes */
  10123. int parenlevel; /* levels of parens in arithmetic */
  10124. struct synstack *prev;
  10125. struct synstack *next;
  10126. };
  10127. static int
  10128. pgetc_top(struct synstack *stack)
  10129. {
  10130. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  10131. }
  10132. static void
  10133. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  10134. {
  10135. memset(next, 0, sizeof(*next));
  10136. next->syntax = syntax;
  10137. next->next = *stack;
  10138. (*stack)->prev = next;
  10139. *stack = next;
  10140. }
  10141. static ALWAYS_INLINE void
  10142. synstack_pop(struct synstack **stack)
  10143. {
  10144. *stack = (*stack)->next;
  10145. }
  10146. /*
  10147. * To handle the "." command, a stack of input files is used. Pushfile
  10148. * adds a new entry to the stack and popfile restores the previous level.
  10149. */
  10150. static void
  10151. pushfile(void)
  10152. {
  10153. struct parsefile *pf;
  10154. pf = ckzalloc(sizeof(*pf));
  10155. pf->prev = g_parsefile;
  10156. pf->pf_fd = -1;
  10157. /*pf->strpush = NULL; - ckzalloc did it */
  10158. /*pf->spfree = NULL;*/
  10159. /*pf->basestrpush.prev = NULL;*/
  10160. /*pf->unget = 0;*/
  10161. g_parsefile = pf;
  10162. }
  10163. static void
  10164. popfile(void)
  10165. {
  10166. struct parsefile *pf = g_parsefile;
  10167. if (pf == &basepf)
  10168. return;
  10169. INT_OFF;
  10170. if (pf->pf_fd >= 0)
  10171. close(pf->pf_fd);
  10172. free(pf->buf);
  10173. if (g_parsefile->spfree)
  10174. freestrings(g_parsefile->spfree);
  10175. while (pf->strpush) {
  10176. popstring();
  10177. freestrings(g_parsefile->spfree);
  10178. }
  10179. g_parsefile = pf->prev;
  10180. free(pf);
  10181. INT_ON;
  10182. }
  10183. static void
  10184. unwindfiles(struct parsefile *stop)
  10185. {
  10186. while (g_parsefile != stop)
  10187. popfile();
  10188. }
  10189. /*
  10190. * Return to top level.
  10191. */
  10192. static void
  10193. popallfiles(void)
  10194. {
  10195. unwindfiles(&basepf);
  10196. }
  10197. /*
  10198. * Close the file(s) that the shell is reading commands from. Called
  10199. * after a fork is done.
  10200. */
  10201. static void
  10202. closescript(void)
  10203. {
  10204. popallfiles();
  10205. if (g_parsefile->pf_fd > 0) {
  10206. close(g_parsefile->pf_fd);
  10207. g_parsefile->pf_fd = 0;
  10208. }
  10209. }
  10210. /*
  10211. * Like setinputfile, but takes an open file descriptor. Call this with
  10212. * interrupts off.
  10213. */
  10214. static void
  10215. setinputfd(int fd, int push)
  10216. {
  10217. if (push) {
  10218. pushfile();
  10219. g_parsefile->buf = NULL;
  10220. }
  10221. g_parsefile->pf_fd = fd;
  10222. if (g_parsefile->buf == NULL)
  10223. g_parsefile->buf = ckmalloc(IBUFSIZ);
  10224. g_parsefile->left_in_buffer = 0;
  10225. g_parsefile->left_in_line = 0;
  10226. g_parsefile->linno = 1;
  10227. }
  10228. /*
  10229. * Set the input to take input from a file. If push is set, push the
  10230. * old input onto the stack first.
  10231. */
  10232. static int
  10233. setinputfile(const char *fname, int flags)
  10234. {
  10235. int fd;
  10236. INT_OFF;
  10237. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10238. if (fd < 0) {
  10239. if (flags & INPUT_NOFILE_OK)
  10240. goto out;
  10241. exitstatus = 127;
  10242. ash_msg_and_raise_perror("can't open '%s'", fname);
  10243. }
  10244. if (fd < 10)
  10245. fd = savefd(fd);
  10246. else if (O_CLOEXEC == 0) /* old libc */
  10247. close_on_exec_on(fd);
  10248. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10249. out:
  10250. INT_ON;
  10251. return fd;
  10252. }
  10253. /*
  10254. * Like setinputfile, but takes input from a string.
  10255. */
  10256. static void
  10257. setinputstring(char *string)
  10258. {
  10259. INT_OFF;
  10260. pushfile();
  10261. g_parsefile->next_to_pgetc = string;
  10262. g_parsefile->left_in_line = strlen(string);
  10263. g_parsefile->buf = NULL;
  10264. g_parsefile->linno = lineno;
  10265. INT_ON;
  10266. }
  10267. /*
  10268. * Routines to check for mail.
  10269. */
  10270. #if ENABLE_ASH_MAIL
  10271. /* Hash of mtimes of mailboxes */
  10272. /* Cleared to 0 if MAIL or MAILPATH is changed */
  10273. static unsigned mailtime_hash;
  10274. /*
  10275. * Print appropriate message(s) if mail has arrived.
  10276. * If mailtime_hash is zero,
  10277. * then the value of MAIL has changed,
  10278. * so we just update the hash value.
  10279. */
  10280. static void
  10281. chkmail(void)
  10282. {
  10283. const char *mpath;
  10284. char *p;
  10285. char *q;
  10286. unsigned new_hash;
  10287. struct stackmark smark;
  10288. struct stat statb;
  10289. setstackmark(&smark);
  10290. mpath = mpathset() ? mpathval() : mailval();
  10291. new_hash = 0;
  10292. for (;;) {
  10293. int len;
  10294. len = padvance_magic(&mpath, nullstr, 2);
  10295. if (len < 0)
  10296. break;
  10297. p = stackblock();
  10298. if (*p == '\0')
  10299. continue;
  10300. for (q = p; *q; q++)
  10301. continue;
  10302. #if DEBUG
  10303. if (q[-1] != '/')
  10304. abort();
  10305. #endif
  10306. q[-1] = '\0'; /* delete trailing '/' */
  10307. if (stat(p, &statb) < 0) {
  10308. continue;
  10309. }
  10310. /* Very simplistic "hash": just a sum of all mtimes */
  10311. new_hash += (unsigned)statb.st_mtime;
  10312. }
  10313. if (mailtime_hash != new_hash) {
  10314. if (mailtime_hash != 0)
  10315. out2str("you have mail\n");
  10316. mailtime_hash = new_hash;
  10317. }
  10318. popstackmark(&smark);
  10319. }
  10320. static void FAST_FUNC
  10321. changemail(const char *val UNUSED_PARAM)
  10322. {
  10323. mailtime_hash = 0;
  10324. }
  10325. #else
  10326. # define chkmail() ((void)0)
  10327. #endif /* ASH_MAIL */
  10328. /* ============ ??? */
  10329. /*
  10330. * Set the shell parameters.
  10331. */
  10332. static void
  10333. setparam(char **argv)
  10334. {
  10335. char **newparam;
  10336. char **ap;
  10337. int nparam;
  10338. for (nparam = 0; argv[nparam]; nparam++)
  10339. continue;
  10340. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10341. while (*argv) {
  10342. *ap++ = ckstrdup(*argv++);
  10343. }
  10344. *ap = NULL;
  10345. freeparam(&shellparam);
  10346. shellparam.malloced = 1;
  10347. shellparam.nparam = nparam;
  10348. shellparam.p = newparam;
  10349. #if ENABLE_ASH_GETOPTS
  10350. shellparam.optind = 1;
  10351. shellparam.optoff = -1;
  10352. #endif
  10353. }
  10354. /*
  10355. * Process shell options. The global variable argptr contains a pointer
  10356. * to the argument list; we advance it past the options.
  10357. *
  10358. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10359. * For a non-interactive shell, an error condition encountered
  10360. * by a special built-in ... shall cause the shell to write a diagnostic message
  10361. * to standard error and exit as shown in the following table:
  10362. * Error Special Built-In
  10363. * ...
  10364. * Utility syntax error (option or operand error) Shall exit
  10365. * ...
  10366. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10367. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10368. * and shell continues), and people rely on this behavior!
  10369. * Testcase:
  10370. * set -o barfoo 2>/dev/null
  10371. * echo $?
  10372. *
  10373. * Oh well. Let's mimic that.
  10374. */
  10375. static int
  10376. plus_minus_o(char *name, int val)
  10377. {
  10378. int i;
  10379. if (name) {
  10380. for (i = 0; i < NOPTS; i++) {
  10381. if (strcmp(name, optnames(i)) == 0) {
  10382. optlist[i] = val;
  10383. return 0;
  10384. }
  10385. }
  10386. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10387. return 1;
  10388. }
  10389. for (i = 0; i < NOPTS; i++) {
  10390. if (optnames(i)[0] == '\0')
  10391. continue;
  10392. if (val) {
  10393. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10394. } else {
  10395. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10396. }
  10397. }
  10398. return 0;
  10399. }
  10400. static void
  10401. setoption(int flag, int val)
  10402. {
  10403. int i;
  10404. for (i = 0; i < NOPTS; i++) {
  10405. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10406. optlist[i] = val;
  10407. return;
  10408. }
  10409. }
  10410. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10411. /* NOTREACHED */
  10412. }
  10413. /* If login_sh is not NULL, we are called to parse command line opts,
  10414. * not "set -opts"
  10415. */
  10416. static int
  10417. options(int *login_sh)
  10418. {
  10419. char *p;
  10420. int val;
  10421. int c;
  10422. if (login_sh != NULL) /* if we came from startup code */
  10423. minusc = NULL;
  10424. while ((p = *argptr) != NULL) {
  10425. c = *p++;
  10426. if (c != '-' && c != '+')
  10427. break;
  10428. argptr++;
  10429. val = 0; /* val = 0 if c == '+' */
  10430. if (c == '-') {
  10431. val = 1;
  10432. if (p[0] == '\0' || LONE_DASH(p)) {
  10433. if (login_sh == NULL) { /* we came from setcmd() */
  10434. /* "-" means turn off -x and -v */
  10435. if (p[0] == '\0')
  10436. xflag = vflag = 0;
  10437. /* "--" means reset params */
  10438. else if (*argptr == NULL)
  10439. setparam(argptr);
  10440. }
  10441. break; /* "-" or "--" terminates options */
  10442. }
  10443. }
  10444. /* first char was + or - */
  10445. while ((c = *p++) != '\0') {
  10446. if (login_sh != NULL) { /* if we came from startup code */
  10447. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10448. if (c == 'c') {
  10449. minusc = p; /* command is after shell args */
  10450. cflag = 1;
  10451. continue;
  10452. }
  10453. if (c == 's') { /* -s, +s */
  10454. sflag = 1;
  10455. continue;
  10456. }
  10457. if (c == 'i') { /* -i, +i */
  10458. iflag = 1;
  10459. continue;
  10460. }
  10461. if (c == 'l') {
  10462. *login_sh = 1; /* -l or +l == --login */
  10463. continue;
  10464. }
  10465. /* bash does not accept +-login, we also won't */
  10466. if (val && (c == '-')) { /* long options */
  10467. if (strcmp(p, "login") == 0) {
  10468. *login_sh = 1;
  10469. }
  10470. /* TODO: --noprofile: e.g. if I want to run emergency shell from sulogin,
  10471. * I want minimal/no shell init scripts - but it insists on running it as "-ash"...
  10472. */
  10473. break;
  10474. }
  10475. }
  10476. if (c == 'o') {
  10477. if (plus_minus_o(*argptr, val)) {
  10478. /* it already printed err message */
  10479. return 1; /* error */
  10480. }
  10481. if (*argptr)
  10482. argptr++;
  10483. } else {
  10484. setoption(c, val);
  10485. }
  10486. }
  10487. }
  10488. return 0;
  10489. }
  10490. /*
  10491. * The shift builtin command.
  10492. */
  10493. static int FAST_FUNC
  10494. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10495. {
  10496. int n;
  10497. char **ap1, **ap2;
  10498. n = 1;
  10499. if (argv[1])
  10500. n = number(argv[1]);
  10501. if (n > shellparam.nparam)
  10502. return 1;
  10503. INT_OFF;
  10504. shellparam.nparam -= n;
  10505. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10506. if (shellparam.malloced)
  10507. free(*ap1);
  10508. }
  10509. ap2 = shellparam.p;
  10510. while ((*ap2++ = *ap1++) != NULL)
  10511. continue;
  10512. #if ENABLE_ASH_GETOPTS
  10513. shellparam.optind = 1;
  10514. shellparam.optoff = -1;
  10515. #endif
  10516. INT_ON;
  10517. return 0;
  10518. }
  10519. /*
  10520. * POSIX requires that 'set' (but not export or readonly) output the
  10521. * variables in lexicographic order - by the locale's collating order (sigh).
  10522. * Maybe we could keep them in an ordered balanced binary tree
  10523. * instead of hashed lists.
  10524. * For now just roll 'em through qsort for printing...
  10525. */
  10526. static int
  10527. showvars(const char *sep_prefix, int on, int off)
  10528. {
  10529. const char *sep;
  10530. char **ep, **epend;
  10531. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10532. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10533. sep = *sep_prefix ? " " : sep_prefix;
  10534. for (; ep < epend; ep++) {
  10535. const char *p;
  10536. const char *q;
  10537. p = endofname(*ep);
  10538. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10539. * makes "export -p" to have output not suitable for "eval":
  10540. * import os
  10541. * os.environ["test-test"]="test"
  10542. * if os.fork() == 0:
  10543. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10544. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10545. */
  10546. q = nullstr;
  10547. if (*p == '=')
  10548. q = single_quote(++p);
  10549. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10550. }
  10551. return 0;
  10552. }
  10553. /*
  10554. * The set command builtin.
  10555. */
  10556. static int FAST_FUNC
  10557. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10558. {
  10559. int retval;
  10560. if (!argv[1])
  10561. return showvars(nullstr, 0, VUNSET);
  10562. INT_OFF;
  10563. retval = options(/*login_sh:*/ NULL);
  10564. if (retval == 0) { /* if no parse error... */
  10565. optschanged();
  10566. if (*argptr != NULL) {
  10567. setparam(argptr);
  10568. }
  10569. }
  10570. INT_ON;
  10571. return retval;
  10572. }
  10573. #if ENABLE_ASH_RANDOM_SUPPORT
  10574. static void FAST_FUNC
  10575. change_random(const char *value)
  10576. {
  10577. uint32_t t;
  10578. if (value == NULL) {
  10579. /* "get", generate */
  10580. t = next_random(&random_gen);
  10581. /* set without recursion */
  10582. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10583. vrandom.flags &= ~VNOFUNC;
  10584. } else {
  10585. /* set/reset */
  10586. t = strtoul(value, NULL, 10);
  10587. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10588. }
  10589. }
  10590. #endif
  10591. #if BASH_EPOCH_VARS
  10592. static void FAST_FUNC
  10593. change_epoch(struct var *vepoch, const char *fmt)
  10594. {
  10595. struct timeval tv;
  10596. char buffer[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  10597. xgettimeofday(&tv);
  10598. sprintf(buffer, fmt, (unsigned long long)tv.tv_sec, (unsigned)tv.tv_usec);
  10599. setvar(vepoch->var_text, buffer, VNOFUNC);
  10600. vepoch->flags &= ~VNOFUNC;
  10601. }
  10602. static void FAST_FUNC
  10603. change_seconds(const char *value UNUSED_PARAM)
  10604. {
  10605. change_epoch(&vepochs, "%llu");
  10606. }
  10607. static void FAST_FUNC
  10608. change_realtime(const char *value UNUSED_PARAM)
  10609. {
  10610. change_epoch(&vepochr, "%llu.%06u");
  10611. }
  10612. #endif
  10613. #if ENABLE_ASH_GETOPTS
  10614. static int
  10615. getopts(char *optstr, char *optvar, char **optfirst)
  10616. {
  10617. char *p, *q;
  10618. char c = '?';
  10619. int done = 0;
  10620. char sbuf[2];
  10621. char **optnext;
  10622. int ind = shellparam.optind;
  10623. int off = shellparam.optoff;
  10624. sbuf[1] = '\0';
  10625. shellparam.optind = -1;
  10626. optnext = optfirst + ind - 1;
  10627. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10628. p = NULL;
  10629. else
  10630. p = optnext[-1] + off;
  10631. if (p == NULL || *p == '\0') {
  10632. /* Current word is done, advance */
  10633. p = *optnext;
  10634. if (p == NULL || *p != '-' || *++p == '\0') {
  10635. atend:
  10636. unsetvar("OPTARG");
  10637. p = NULL;
  10638. done = 1;
  10639. goto out;
  10640. }
  10641. optnext++;
  10642. if (LONE_DASH(p)) /* check for "--" */
  10643. goto atend;
  10644. }
  10645. c = *p++;
  10646. for (q = optstr; *q != c;) {
  10647. if (*q == '\0') {
  10648. /* OPTERR is a bashism */
  10649. const char *cp = lookupvar("OPTERR");
  10650. if ((cp && LONE_CHAR(cp, '0'))
  10651. || (optstr[0] == ':')
  10652. ) {
  10653. sbuf[0] = c;
  10654. /*sbuf[1] = '\0'; - already is */
  10655. setvar0("OPTARG", sbuf);
  10656. } else {
  10657. fprintf(stderr, "Illegal option -%c\n", c);
  10658. unsetvar("OPTARG");
  10659. }
  10660. c = '?';
  10661. goto out;
  10662. }
  10663. if (*++q == ':')
  10664. q++;
  10665. }
  10666. if (*++q == ':') {
  10667. if (*p == '\0' && (p = *optnext) == NULL) {
  10668. /* OPTERR is a bashism */
  10669. const char *cp = lookupvar("OPTERR");
  10670. if ((cp && LONE_CHAR(cp, '0'))
  10671. || (optstr[0] == ':')
  10672. ) {
  10673. sbuf[0] = c;
  10674. /*sbuf[1] = '\0'; - already is */
  10675. setvar0("OPTARG", sbuf);
  10676. c = ':';
  10677. } else {
  10678. fprintf(stderr, "No arg for -%c option\n", c);
  10679. unsetvar("OPTARG");
  10680. c = '?';
  10681. }
  10682. goto out;
  10683. }
  10684. if (p == *optnext)
  10685. optnext++;
  10686. setvar0("OPTARG", p);
  10687. p = NULL;
  10688. } else
  10689. setvar0("OPTARG", nullstr);
  10690. out:
  10691. ind = optnext - optfirst + 1;
  10692. setvar("OPTIND", itoa(ind), VNOFUNC);
  10693. sbuf[0] = c;
  10694. /*sbuf[1] = '\0'; - already is */
  10695. setvar0(optvar, sbuf);
  10696. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10697. shellparam.optind = ind;
  10698. return done;
  10699. }
  10700. /*
  10701. * The getopts builtin. Shellparam.optnext points to the next argument
  10702. * to be processed. Shellparam.optptr points to the next character to
  10703. * be processed in the current argument. If shellparam.optnext is NULL,
  10704. * then it's the first time getopts has been called.
  10705. */
  10706. static int FAST_FUNC
  10707. getoptscmd(int argc, char **argv)
  10708. {
  10709. char **optbase;
  10710. if (argc < 3)
  10711. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10712. if (argc == 3) {
  10713. optbase = shellparam.p;
  10714. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10715. shellparam.optind = 1;
  10716. shellparam.optoff = -1;
  10717. }
  10718. } else {
  10719. optbase = &argv[3];
  10720. if ((unsigned)shellparam.optind > argc - 2) {
  10721. shellparam.optind = 1;
  10722. shellparam.optoff = -1;
  10723. }
  10724. }
  10725. return getopts(argv[1], argv[2], optbase);
  10726. }
  10727. #endif /* ASH_GETOPTS */
  10728. /* ============ Shell parser */
  10729. struct heredoc {
  10730. struct heredoc *next; /* next here document in list */
  10731. union node *here; /* redirection node */
  10732. char *eofmark; /* string indicating end of input */
  10733. smallint striptabs; /* if set, strip leading tabs */
  10734. };
  10735. static smallint tokpushback; /* last token pushed back */
  10736. static smallint quoteflag; /* set if (part of) last token was quoted */
  10737. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10738. static struct heredoc *heredoclist; /* list of here documents to read */
  10739. static char *wordtext; /* text of last word returned by readtoken */
  10740. static struct nodelist *backquotelist;
  10741. static union node *redirnode;
  10742. static struct heredoc *heredoc;
  10743. static const char *
  10744. tokname(char *buf, int tok)
  10745. {
  10746. if (tok < TSEMI)
  10747. return tokname_array[tok];
  10748. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10749. return buf;
  10750. }
  10751. /* raise_error_unexpected_syntax:
  10752. * Called when an unexpected token is read during the parse. The argument
  10753. * is the token that is expected, or -1 if more than one type of token can
  10754. * occur at this point.
  10755. */
  10756. static void raise_error_unexpected_syntax(int) NORETURN;
  10757. static void
  10758. raise_error_unexpected_syntax(int token)
  10759. {
  10760. char msg[64];
  10761. char buf[16];
  10762. int l;
  10763. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10764. if (token >= 0)
  10765. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10766. raise_error_syntax(msg);
  10767. /* NOTREACHED */
  10768. }
  10769. /* parsing is heavily cross-recursive, need these forward decls */
  10770. static union node *andor(void);
  10771. static union node *pipeline(void);
  10772. static union node *parse_command(void);
  10773. static void parseheredoc(void);
  10774. static int readtoken(void);
  10775. static union node *
  10776. list(int nlflag)
  10777. {
  10778. int chknl = nlflag & 1 ? 0 : CHKNL;
  10779. union node *n1, *n2, *n3;
  10780. int tok;
  10781. n1 = NULL;
  10782. for (;;) {
  10783. checkkwd = chknl | CHKKWD | CHKALIAS;
  10784. tok = readtoken();
  10785. switch (tok) {
  10786. case TNL:
  10787. parseheredoc();
  10788. return n1;
  10789. case TEOF:
  10790. if (!n1 && !chknl)
  10791. n1 = NODE_EOF;
  10792. out_eof:
  10793. parseheredoc();
  10794. tokpushback++;
  10795. lasttoken = TEOF;
  10796. return n1;
  10797. }
  10798. tokpushback++;
  10799. if (nlflag == 2 && ((1 << tok) & tokendlist))
  10800. return n1;
  10801. nlflag |= 2;
  10802. n2 = andor();
  10803. tok = readtoken();
  10804. if (tok == TBACKGND) {
  10805. if (n2->type == NPIPE) {
  10806. n2->npipe.pipe_backgnd = 1;
  10807. } else {
  10808. if (n2->type != NREDIR) {
  10809. n3 = stzalloc(sizeof(struct nredir));
  10810. n3->nredir.n = n2;
  10811. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10812. n2 = n3;
  10813. }
  10814. n2->type = NBACKGND;
  10815. }
  10816. }
  10817. if (n1 == NULL) {
  10818. n1 = n2;
  10819. } else {
  10820. n3 = stzalloc(sizeof(struct nbinary));
  10821. n3->type = NSEMI;
  10822. n3->nbinary.ch1 = n1;
  10823. n3->nbinary.ch2 = n2;
  10824. n1 = n3;
  10825. }
  10826. switch (tok) {
  10827. case TEOF:
  10828. goto out_eof;
  10829. case TNL:
  10830. tokpushback = 1;
  10831. /* fall through */
  10832. case TBACKGND:
  10833. case TSEMI:
  10834. break;
  10835. default:
  10836. if (!chknl)
  10837. raise_error_unexpected_syntax(-1);
  10838. tokpushback = 1;
  10839. return n1;
  10840. }
  10841. }
  10842. }
  10843. static union node *
  10844. andor(void)
  10845. {
  10846. union node *n1, *n2, *n3;
  10847. int t;
  10848. n1 = pipeline();
  10849. for (;;) {
  10850. t = readtoken();
  10851. if (t == TAND) {
  10852. t = NAND;
  10853. } else if (t == TOR) {
  10854. t = NOR;
  10855. } else {
  10856. tokpushback = 1;
  10857. return n1;
  10858. }
  10859. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10860. n2 = pipeline();
  10861. n3 = stzalloc(sizeof(struct nbinary));
  10862. n3->type = t;
  10863. n3->nbinary.ch1 = n1;
  10864. n3->nbinary.ch2 = n2;
  10865. n1 = n3;
  10866. }
  10867. }
  10868. static union node *
  10869. pipeline(void)
  10870. {
  10871. union node *n1, *n2, *pipenode;
  10872. struct nodelist *lp, *prev;
  10873. int negate;
  10874. negate = 0;
  10875. TRACE(("pipeline: entered\n"));
  10876. if (readtoken() == TNOT) {
  10877. negate = !negate;
  10878. checkkwd = CHKKWD | CHKALIAS;
  10879. } else
  10880. tokpushback = 1;
  10881. n1 = parse_command();
  10882. if (readtoken() == TPIPE) {
  10883. pipenode = stzalloc(sizeof(struct npipe));
  10884. pipenode->type = NPIPE;
  10885. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10886. lp = stzalloc(sizeof(struct nodelist));
  10887. pipenode->npipe.cmdlist = lp;
  10888. lp->n = n1;
  10889. do {
  10890. prev = lp;
  10891. lp = stzalloc(sizeof(struct nodelist));
  10892. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10893. lp->n = parse_command();
  10894. prev->next = lp;
  10895. } while (readtoken() == TPIPE);
  10896. lp->next = NULL;
  10897. n1 = pipenode;
  10898. }
  10899. tokpushback = 1;
  10900. if (negate) {
  10901. n2 = stzalloc(sizeof(struct nnot));
  10902. n2->type = NNOT;
  10903. n2->nnot.com = n1;
  10904. return n2;
  10905. }
  10906. return n1;
  10907. }
  10908. static union node *
  10909. makename(void)
  10910. {
  10911. union node *n;
  10912. n = stzalloc(sizeof(struct narg));
  10913. n->type = NARG;
  10914. /*n->narg.next = NULL; - stzalloc did it */
  10915. n->narg.text = wordtext;
  10916. n->narg.backquote = backquotelist;
  10917. return n;
  10918. }
  10919. static void
  10920. fixredir(union node *n, const char *text, int err)
  10921. {
  10922. int fd;
  10923. TRACE(("Fix redir %s %d\n", text, err));
  10924. if (!err)
  10925. n->ndup.vname = NULL;
  10926. fd = bb_strtou(text, NULL, 10);
  10927. if (!errno && fd >= 0)
  10928. n->ndup.dupfd = fd;
  10929. else if (LONE_DASH(text))
  10930. n->ndup.dupfd = -1;
  10931. else {
  10932. if (err)
  10933. raise_error_syntax("bad fd number");
  10934. n->ndup.vname = makename();
  10935. }
  10936. }
  10937. static void
  10938. parsefname(void)
  10939. {
  10940. union node *n = redirnode;
  10941. if (n->type == NHERE)
  10942. checkkwd = CHKEOFMARK;
  10943. if (readtoken() != TWORD)
  10944. raise_error_unexpected_syntax(-1);
  10945. if (n->type == NHERE) {
  10946. struct heredoc *here = heredoc;
  10947. struct heredoc *p;
  10948. if (quoteflag == 0)
  10949. n->type = NXHERE;
  10950. TRACE(("Here document %d\n", n->type));
  10951. rmescapes(wordtext, 0, NULL);
  10952. here->eofmark = wordtext;
  10953. here->next = NULL;
  10954. if (heredoclist == NULL)
  10955. heredoclist = here;
  10956. else {
  10957. for (p = heredoclist; p->next; p = p->next)
  10958. continue;
  10959. p->next = here;
  10960. }
  10961. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10962. fixredir(n, wordtext, 0);
  10963. } else {
  10964. n->nfile.fname = makename();
  10965. }
  10966. }
  10967. static union node *
  10968. simplecmd(void)
  10969. {
  10970. union node *args, **app;
  10971. union node *n = NULL;
  10972. union node *vars, **vpp;
  10973. union node **rpp, *redir;
  10974. int savecheckkwd;
  10975. int savelinno;
  10976. #if BASH_TEST2
  10977. smallint double_brackets_flag = 0;
  10978. #endif
  10979. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10980. args = NULL;
  10981. app = &args;
  10982. vars = NULL;
  10983. vpp = &vars;
  10984. redir = NULL;
  10985. rpp = &redir;
  10986. savecheckkwd = CHKALIAS;
  10987. savelinno = g_parsefile->linno;
  10988. for (;;) {
  10989. int t;
  10990. checkkwd = savecheckkwd;
  10991. t = readtoken();
  10992. switch (t) {
  10993. #if BASH_FUNCTION
  10994. case TFUNCTION:
  10995. if (readtoken() != TWORD)
  10996. raise_error_unexpected_syntax(TWORD);
  10997. tokpushback = 1;
  10998. function_flag = 1;
  10999. break;
  11000. #endif
  11001. #if BASH_TEST2
  11002. case TAND: /* "&&" */
  11003. case TOR: /* "||" */
  11004. if (!double_brackets_flag) {
  11005. tokpushback = 1;
  11006. goto out;
  11007. }
  11008. /* pass "&&" or "||" to [[ ]] as literal args */
  11009. wordtext = (char *) (t == TAND ? "&&" : "||");
  11010. #endif
  11011. case TWORD:
  11012. n = stzalloc(sizeof(struct narg));
  11013. n->type = NARG;
  11014. /*n->narg.next = NULL; - stzalloc did it */
  11015. n->narg.text = wordtext;
  11016. #if BASH_TEST2
  11017. if (strcmp("[[", wordtext) == 0)
  11018. double_brackets_flag = 1;
  11019. else if (strcmp("]]", wordtext) == 0)
  11020. double_brackets_flag = 0;
  11021. #endif
  11022. n->narg.backquote = backquotelist;
  11023. if (savecheckkwd && isassignment(wordtext)) {
  11024. *vpp = n;
  11025. vpp = &n->narg.next;
  11026. } else {
  11027. *app = n;
  11028. app = &n->narg.next;
  11029. savecheckkwd = 0;
  11030. }
  11031. #if BASH_FUNCTION
  11032. if (function_flag) {
  11033. checkkwd = CHKNL | CHKKWD;
  11034. t = readtoken();
  11035. tokpushback = 1;
  11036. switch (t) {
  11037. case TBEGIN:
  11038. case TIF:
  11039. case TCASE:
  11040. case TUNTIL:
  11041. case TWHILE:
  11042. case TFOR:
  11043. goto do_func;
  11044. case TLP:
  11045. function_flag = 0;
  11046. break;
  11047. # if BASH_TEST2
  11048. case TWORD:
  11049. if (strcmp("[[", wordtext) == 0)
  11050. goto do_func;
  11051. /* fall through */
  11052. # endif
  11053. default:
  11054. raise_error_unexpected_syntax(-1);
  11055. }
  11056. }
  11057. #endif
  11058. break;
  11059. case TREDIR:
  11060. *rpp = n = redirnode;
  11061. rpp = &n->nfile.next;
  11062. parsefname(); /* read name of redirection file */
  11063. break;
  11064. case TLP:
  11065. IF_BASH_FUNCTION(do_func:)
  11066. if (args && app == &args->narg.next
  11067. && !vars && !redir
  11068. ) {
  11069. // struct builtincmd *bcmd;
  11070. // const char *name;
  11071. /* We have a function */
  11072. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  11073. raise_error_unexpected_syntax(TRP);
  11074. //bash allows functions named "123", "..", "return"!
  11075. // name = n->narg.text;
  11076. // if (!goodname(name)
  11077. // || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  11078. // ) {
  11079. // raise_error_syntax("bad function name");
  11080. // }
  11081. n->type = NDEFUN;
  11082. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11083. n->ndefun.text = n->narg.text;
  11084. n->ndefun.linno = g_parsefile->linno;
  11085. n->ndefun.body = parse_command();
  11086. return n;
  11087. }
  11088. IF_BASH_FUNCTION(function_flag = 0;)
  11089. /* fall through */
  11090. default:
  11091. tokpushback = 1;
  11092. goto out;
  11093. }
  11094. }
  11095. out:
  11096. *app = NULL;
  11097. *vpp = NULL;
  11098. *rpp = NULL;
  11099. n = stzalloc(sizeof(struct ncmd));
  11100. if (NCMD != 0)
  11101. n->type = NCMD;
  11102. n->ncmd.linno = savelinno;
  11103. n->ncmd.args = args;
  11104. n->ncmd.assign = vars;
  11105. n->ncmd.redirect = redir;
  11106. return n;
  11107. }
  11108. static union node *
  11109. parse_command(void)
  11110. {
  11111. union node *n1, *n2;
  11112. union node *ap, **app;
  11113. union node *cp, **cpp;
  11114. union node *redir, **rpp;
  11115. union node **rpp2;
  11116. int t;
  11117. int savelinno;
  11118. redir = NULL;
  11119. rpp2 = &redir;
  11120. savelinno = g_parsefile->linno;
  11121. switch (readtoken()) {
  11122. default:
  11123. raise_error_unexpected_syntax(-1);
  11124. /* NOTREACHED */
  11125. case TIF:
  11126. n1 = stzalloc(sizeof(struct nif));
  11127. n1->type = NIF;
  11128. n1->nif.test = list(0);
  11129. if (readtoken() != TTHEN)
  11130. raise_error_unexpected_syntax(TTHEN);
  11131. n1->nif.ifpart = list(0);
  11132. n2 = n1;
  11133. while (readtoken() == TELIF) {
  11134. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  11135. n2 = n2->nif.elsepart;
  11136. n2->type = NIF;
  11137. n2->nif.test = list(0);
  11138. if (readtoken() != TTHEN)
  11139. raise_error_unexpected_syntax(TTHEN);
  11140. n2->nif.ifpart = list(0);
  11141. }
  11142. if (lasttoken == TELSE)
  11143. n2->nif.elsepart = list(0);
  11144. else {
  11145. n2->nif.elsepart = NULL;
  11146. tokpushback = 1;
  11147. }
  11148. t = TFI;
  11149. break;
  11150. case TWHILE:
  11151. case TUNTIL: {
  11152. int got;
  11153. n1 = stzalloc(sizeof(struct nbinary));
  11154. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  11155. n1->nbinary.ch1 = list(0);
  11156. got = readtoken();
  11157. if (got != TDO) {
  11158. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  11159. got == TWORD ? wordtext : ""));
  11160. raise_error_unexpected_syntax(TDO);
  11161. }
  11162. n1->nbinary.ch2 = list(0);
  11163. t = TDONE;
  11164. break;
  11165. }
  11166. case TFOR:
  11167. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  11168. raise_error_syntax("bad for loop variable");
  11169. n1 = stzalloc(sizeof(struct nfor));
  11170. n1->type = NFOR;
  11171. n1->nfor.linno = savelinno;
  11172. n1->nfor.var = wordtext;
  11173. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11174. if (readtoken() == TIN) {
  11175. app = &ap;
  11176. while (readtoken() == TWORD) {
  11177. n2 = stzalloc(sizeof(struct narg));
  11178. n2->type = NARG;
  11179. /*n2->narg.next = NULL; - stzalloc did it */
  11180. n2->narg.text = wordtext;
  11181. n2->narg.backquote = backquotelist;
  11182. *app = n2;
  11183. app = &n2->narg.next;
  11184. }
  11185. *app = NULL;
  11186. n1->nfor.args = ap;
  11187. if (lasttoken != TNL && lasttoken != TSEMI)
  11188. raise_error_unexpected_syntax(-1);
  11189. } else {
  11190. n2 = stzalloc(sizeof(struct narg));
  11191. n2->type = NARG;
  11192. /*n2->narg.next = NULL; - stzalloc did it */
  11193. n2->narg.text = (char *)dolatstr;
  11194. /*n2->narg.backquote = NULL;*/
  11195. n1->nfor.args = n2;
  11196. /*
  11197. * Newline or semicolon here is optional (but note
  11198. * that the original Bourne shell only allowed NL).
  11199. */
  11200. if (lasttoken != TSEMI)
  11201. tokpushback = 1;
  11202. }
  11203. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11204. if (readtoken() != TDO)
  11205. raise_error_unexpected_syntax(TDO);
  11206. n1->nfor.body = list(0);
  11207. t = TDONE;
  11208. break;
  11209. case TCASE:
  11210. n1 = stzalloc(sizeof(struct ncase));
  11211. n1->type = NCASE;
  11212. n1->ncase.linno = savelinno;
  11213. if (readtoken() != TWORD)
  11214. raise_error_unexpected_syntax(TWORD);
  11215. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  11216. n2->type = NARG;
  11217. /*n2->narg.next = NULL; - stzalloc did it */
  11218. n2->narg.text = wordtext;
  11219. n2->narg.backquote = backquotelist;
  11220. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11221. if (readtoken() != TIN)
  11222. raise_error_unexpected_syntax(TIN);
  11223. cpp = &n1->ncase.cases;
  11224. next_case:
  11225. checkkwd = CHKNL | CHKKWD;
  11226. t = readtoken();
  11227. while (t != TESAC) {
  11228. if (lasttoken == TLP)
  11229. readtoken();
  11230. *cpp = cp = stzalloc(sizeof(struct nclist));
  11231. cp->type = NCLIST;
  11232. app = &cp->nclist.pattern;
  11233. for (;;) {
  11234. *app = ap = stzalloc(sizeof(struct narg));
  11235. ap->type = NARG;
  11236. /*ap->narg.next = NULL; - stzalloc did it */
  11237. ap->narg.text = wordtext;
  11238. ap->narg.backquote = backquotelist;
  11239. if (readtoken() != TPIPE)
  11240. break;
  11241. app = &ap->narg.next;
  11242. readtoken();
  11243. }
  11244. //ap->narg.next = NULL;
  11245. if (lasttoken != TRP)
  11246. raise_error_unexpected_syntax(TRP);
  11247. cp->nclist.body = list(2);
  11248. cpp = &cp->nclist.next;
  11249. checkkwd = CHKNL | CHKKWD;
  11250. t = readtoken();
  11251. if (t != TESAC) {
  11252. if (t != TENDCASE)
  11253. raise_error_unexpected_syntax(TENDCASE);
  11254. goto next_case;
  11255. }
  11256. }
  11257. *cpp = NULL;
  11258. goto redir;
  11259. case TLP:
  11260. n1 = stzalloc(sizeof(struct nredir));
  11261. n1->type = NSUBSHELL;
  11262. n1->nredir.linno = savelinno;
  11263. n1->nredir.n = list(0);
  11264. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11265. t = TRP;
  11266. break;
  11267. case TBEGIN:
  11268. n1 = list(0);
  11269. t = TEND;
  11270. break;
  11271. IF_BASH_FUNCTION(case TFUNCTION:)
  11272. case TWORD:
  11273. case TREDIR:
  11274. tokpushback = 1;
  11275. return simplecmd();
  11276. }
  11277. if (readtoken() != t)
  11278. raise_error_unexpected_syntax(t);
  11279. redir:
  11280. /* Now check for redirection which may follow command */
  11281. checkkwd = CHKKWD | CHKALIAS;
  11282. rpp = rpp2;
  11283. while (readtoken() == TREDIR) {
  11284. *rpp = n2 = redirnode;
  11285. rpp = &n2->nfile.next;
  11286. parsefname();
  11287. }
  11288. tokpushback = 1;
  11289. *rpp = NULL;
  11290. if (redir) {
  11291. if (n1->type != NSUBSHELL) {
  11292. n2 = stzalloc(sizeof(struct nredir));
  11293. n2->type = NREDIR;
  11294. n2->nredir.linno = savelinno;
  11295. n2->nredir.n = n1;
  11296. n1 = n2;
  11297. }
  11298. n1->nredir.redirect = redir;
  11299. }
  11300. return n1;
  11301. }
  11302. #if BASH_DOLLAR_SQUOTE
  11303. static int
  11304. decode_dollar_squote(void)
  11305. {
  11306. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11307. int c, cnt;
  11308. char *p;
  11309. char buf[4];
  11310. c = pgetc();
  11311. p = strchr(C_escapes, c);
  11312. if (p) {
  11313. buf[0] = c;
  11314. p = buf;
  11315. cnt = 3;
  11316. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11317. do {
  11318. c = pgetc();
  11319. *++p = c;
  11320. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11321. pungetc();
  11322. } else if (c == 'x') { /* \xHH */
  11323. do {
  11324. c = pgetc();
  11325. *++p = c;
  11326. } while (isxdigit(c) && --cnt);
  11327. pungetc();
  11328. if (cnt == 3) { /* \x but next char is "bad" */
  11329. c = 'x';
  11330. goto unrecognized;
  11331. }
  11332. } else { /* simple seq like \\ or \t */
  11333. p++;
  11334. }
  11335. *p = '\0';
  11336. p = buf;
  11337. c = bb_process_escape_sequence((void*)&p);
  11338. } else { /* unrecognized "\z": print both chars unless ' or " */
  11339. if (c != '\'' && c != '"') {
  11340. unrecognized:
  11341. c |= 0x100; /* "please encode \, then me" */
  11342. }
  11343. }
  11344. return c;
  11345. }
  11346. #endif
  11347. /* Used by expandstr to get here-doc like behaviour. */
  11348. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11349. static ALWAYS_INLINE int
  11350. realeofmark(const char *eofmark)
  11351. {
  11352. return eofmark && eofmark != FAKEEOFMARK;
  11353. }
  11354. /*
  11355. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11356. * is not NULL, read a here document. In the latter case, eofmark is the
  11357. * word which marks the end of the document and striptabs is true if
  11358. * leading tabs should be stripped from the document. The argument c
  11359. * is the first character of the input token or document.
  11360. *
  11361. * Because C does not have internal subroutines, I have simulated them
  11362. * using goto's to implement the subroutine linkage. The following macros
  11363. * will run code that appears at the end of readtoken1.
  11364. */
  11365. #define CHECKEND() {goto checkend; checkend_return:;}
  11366. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11367. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11368. #define PARSEBACKQOLD() {style = OLD; goto parsebackq; parsebackq_oldreturn:;}
  11369. #define PARSEBACKQNEW() {style = NEW; goto parsebackq; parsebackq_newreturn:;}
  11370. #define PARSEPROCSUB() {style = PSUB; goto parsebackq; parsebackq_psreturn:;}
  11371. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11372. static int
  11373. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11374. {
  11375. /* NB: syntax parameter fits into smallint */
  11376. /* c parameter is an unsigned char or PEOF */
  11377. char *out;
  11378. size_t len;
  11379. struct nodelist *bqlist;
  11380. smallint quotef;
  11381. smallint style;
  11382. enum { OLD, NEW, PSUB };
  11383. #define oldstyle (style == OLD)
  11384. smallint pssyntax; /* we are expanding a prompt string */
  11385. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11386. /* syntax stack */
  11387. struct synstack synbase = { };
  11388. struct synstack *synstack = &synbase;
  11389. #if ENABLE_ASH_EXPAND_PRMT
  11390. pssyntax = (syntax == PSSYNTAX);
  11391. if (pssyntax)
  11392. syntax = DQSYNTAX;
  11393. #else
  11394. pssyntax = 0; /* constant */
  11395. #endif
  11396. synstack->syntax = syntax;
  11397. if (syntax == DQSYNTAX)
  11398. synstack->dblquote = 1;
  11399. quotef = 0;
  11400. bqlist = NULL;
  11401. STARTSTACKSTR(out);
  11402. loop:
  11403. /* For each line, until end of word */
  11404. CHECKEND(); /* set c to PEOF if at end of here document */
  11405. for (;;) { /* until end of line or end of word */
  11406. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11407. switch (SIT(c, synstack->syntax)) {
  11408. case CNL: /* '\n' */
  11409. if (synstack->syntax == BASESYNTAX
  11410. && !synstack->varnest
  11411. ) {
  11412. goto endword; /* exit outer loop */
  11413. }
  11414. USTPUTC(c, out);
  11415. nlprompt();
  11416. c = pgetc_top(synstack);
  11417. goto loop; /* continue outer loop */
  11418. case CWORD:
  11419. USTPUTC(c, out);
  11420. break;
  11421. case CCTL:
  11422. #if BASH_DOLLAR_SQUOTE
  11423. if (c == '\\' && bash_dollar_squote) {
  11424. c = decode_dollar_squote();
  11425. if (c == '\0') {
  11426. /* skip $'\000', $'\x00' (like bash) */
  11427. break;
  11428. }
  11429. if (c & 0x100) {
  11430. /* Unknown escape. Encode as '\z' */
  11431. c = (unsigned char)c;
  11432. if (eofmark == NULL || synstack->dblquote)
  11433. USTPUTC(CTLESC, out);
  11434. USTPUTC('\\', out);
  11435. }
  11436. }
  11437. #endif
  11438. if (!eofmark || synstack->dblquote || synstack->varnest)
  11439. USTPUTC(CTLESC, out);
  11440. USTPUTC(c, out);
  11441. break;
  11442. case CBACK: /* backslash */
  11443. c = pgetc();
  11444. if (c == PEOF) {
  11445. USTPUTC(CTLESC, out);
  11446. USTPUTC('\\', out);
  11447. pungetc();
  11448. } else {
  11449. if (pssyntax && c == '$') {
  11450. USTPUTC(CTLESC, out);
  11451. USTPUTC('\\', out);
  11452. }
  11453. /* Backslash is retained if we are in "str"
  11454. * and next char isn't dquote-special.
  11455. */
  11456. if (synstack->dblquote
  11457. && c != '\\'
  11458. && c != '`'
  11459. && c != '$'
  11460. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11461. && (c != '}' || !synstack->varnest)
  11462. ) {
  11463. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11464. USTPUTC('\\', out);
  11465. }
  11466. USTPUTC(CTLESC, out);
  11467. USTPUTC(c, out);
  11468. quotef = 1;
  11469. }
  11470. break;
  11471. case CSQUOTE:
  11472. synstack->syntax = SQSYNTAX;
  11473. quotemark:
  11474. if (eofmark == NULL) {
  11475. USTPUTC(CTLQUOTEMARK, out);
  11476. }
  11477. break;
  11478. case CDQUOTE:
  11479. synstack->syntax = DQSYNTAX;
  11480. synstack->dblquote = 1;
  11481. toggledq:
  11482. if (synstack->varnest)
  11483. synstack->innerdq ^= 1;
  11484. goto quotemark;
  11485. case CENDQUOTE:
  11486. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11487. if (eofmark != NULL && synstack->varnest == 0) {
  11488. USTPUTC(c, out);
  11489. break;
  11490. }
  11491. if (synstack->dqvarnest == 0) {
  11492. synstack->syntax = BASESYNTAX;
  11493. synstack->dblquote = 0;
  11494. }
  11495. quotef = 1;
  11496. if (c == '"')
  11497. goto toggledq;
  11498. goto quotemark;
  11499. case CVAR: /* '$' */
  11500. PARSESUB(); /* parse substitution */
  11501. break;
  11502. case CENDVAR: /* '}' */
  11503. if (!synstack->innerdq && synstack->varnest > 0) {
  11504. if (!--synstack->varnest && synstack->varpushed)
  11505. synstack_pop(&synstack);
  11506. else if (synstack->dqvarnest > 0)
  11507. synstack->dqvarnest--;
  11508. c = CTLENDVAR;
  11509. }
  11510. USTPUTC(c, out);
  11511. break;
  11512. #if ENABLE_FEATURE_SH_MATH
  11513. case CLP: /* '(' in arithmetic */
  11514. synstack->parenlevel++;
  11515. USTPUTC(c, out);
  11516. break;
  11517. case CRP: /* ')' in arithmetic */
  11518. if (synstack->parenlevel > 0) {
  11519. synstack->parenlevel--;
  11520. } else {
  11521. if (pgetc_eatbnl() == ')') {
  11522. c = CTLENDARI;
  11523. synstack_pop(&synstack);
  11524. } else {
  11525. /*
  11526. * unbalanced parens
  11527. * (don't 2nd guess - no error)
  11528. */
  11529. pungetc();
  11530. }
  11531. }
  11532. USTPUTC(c, out);
  11533. break;
  11534. #endif
  11535. case CBQUOTE: /* '`' */
  11536. if (checkkwd & CHKEOFMARK) {
  11537. quotef = 1;
  11538. USTPUTC('`', out);
  11539. break;
  11540. }
  11541. PARSEBACKQOLD();
  11542. break;
  11543. case CENDFILE:
  11544. goto endword; /* exit outer loop */
  11545. default:
  11546. if (synstack->varnest == 0) {
  11547. #if BASH_REDIR_OUTPUT
  11548. if (c == '&') {
  11549. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11550. if (pgetc() == '>')
  11551. c = 0x100 + '>'; /* flag &> */
  11552. pungetc();
  11553. }
  11554. #endif
  11555. #if BASH_PROCESS_SUBST
  11556. if (c == '<' || c == '>') {
  11557. if (pgetc() == '(') {
  11558. PARSEPROCSUB();
  11559. break;
  11560. }
  11561. pungetc();
  11562. }
  11563. #endif
  11564. goto endword; /* exit outer loop */
  11565. }
  11566. USTPUTC(c, out);
  11567. }
  11568. c = pgetc_top(synstack);
  11569. } /* for (;;) */
  11570. endword:
  11571. #if ENABLE_FEATURE_SH_MATH
  11572. if (synstack->syntax == ARISYNTAX)
  11573. raise_error_syntax("missing '))'");
  11574. #endif
  11575. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11576. raise_error_syntax("unterminated quoted string");
  11577. if (synstack->varnest != 0) {
  11578. /* { */
  11579. raise_error_syntax("missing '}'");
  11580. }
  11581. USTPUTC('\0', out);
  11582. len = out - (char *)stackblock();
  11583. out = stackblock();
  11584. if (eofmark == NULL) {
  11585. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11586. && quotef == 0
  11587. ) {
  11588. if (isdigit_str9(out)) {
  11589. PARSEREDIR(); /* passed as params: out, c */
  11590. lasttoken = TREDIR;
  11591. return lasttoken;
  11592. }
  11593. /* else: non-number X seen, interpret it
  11594. * as "NNNX>file" = "NNNX >file" */
  11595. }
  11596. pungetc();
  11597. }
  11598. quoteflag = quotef;
  11599. backquotelist = bqlist;
  11600. grabstackblock(len);
  11601. wordtext = out;
  11602. lasttoken = TWORD;
  11603. return lasttoken;
  11604. /* end of readtoken routine */
  11605. /*
  11606. * Check to see whether we are at the end of the here document. When this
  11607. * is called, c is set to the first character of the next input line. If
  11608. * we are at the end of the here document, this routine sets the c to PEOF.
  11609. */
  11610. checkend: {
  11611. if (realeofmark(eofmark)) {
  11612. int markloc;
  11613. char *p;
  11614. if (striptabs) {
  11615. while (c == '\t')
  11616. c = pgetc();
  11617. }
  11618. markloc = out - (char *)stackblock();
  11619. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11620. if (c != *p)
  11621. goto more_heredoc;
  11622. /* FIXME: fails for backslash-newlined terminator:
  11623. * cat <<EOF
  11624. * ...
  11625. * EO\
  11626. * F
  11627. * (see heredoc_bkslash_newline2.tests)
  11628. */
  11629. c = pgetc();
  11630. }
  11631. if (c == '\n' || c == PEOF) {
  11632. c = PEOF;
  11633. if (trap_depth == 0)
  11634. g_parsefile->linno++;
  11635. needprompt = doprompt;
  11636. } else {
  11637. int len_here;
  11638. more_heredoc:
  11639. p = (char *)stackblock() + markloc + 1;
  11640. len_here = out - p;
  11641. if (len_here) {
  11642. len_here -= (c >= PEOF);
  11643. c = p[-1];
  11644. if (len_here) {
  11645. char *str;
  11646. str = alloca(len_here + 1);
  11647. *(char *)mempcpy(str, p, len_here) = '\0';
  11648. pushstring(str, NULL);
  11649. }
  11650. }
  11651. }
  11652. STADJUST((char *)stackblock() + markloc - out, out);
  11653. }
  11654. goto checkend_return;
  11655. }
  11656. /*
  11657. * Parse a redirection operator. The variable "out" points to a string
  11658. * specifying the fd to be redirected. The variable "c" contains the
  11659. * first character of the redirection operator.
  11660. */
  11661. parseredir: {
  11662. /* out is already checked to be a valid number or "" */
  11663. int fd = (*out == '\0' ? -1 : atoi(out));
  11664. union node *np;
  11665. np = stzalloc(sizeof(struct nfile));
  11666. if (c == '>') {
  11667. np->nfile.fd = 1;
  11668. c = pgetc_eatbnl();
  11669. if (c == '>')
  11670. np->type = NAPPEND;
  11671. else if (c == '|')
  11672. np->type = NCLOBBER;
  11673. else if (c == '&')
  11674. np->type = NTOFD;
  11675. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11676. else {
  11677. np->type = NTO;
  11678. pungetc();
  11679. }
  11680. }
  11681. #if BASH_REDIR_OUTPUT
  11682. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11683. np->nfile.fd = 1;
  11684. pgetc(); /* this is '>', no need to check */
  11685. np->type = NTO2;
  11686. }
  11687. #endif
  11688. else { /* c == '<' */
  11689. /*np->nfile.fd = 0; - stzalloc did it */
  11690. c = pgetc_eatbnl();
  11691. switch (c) {
  11692. case '<':
  11693. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11694. np = stzalloc(sizeof(struct nhere));
  11695. /*np->nfile.fd = 0; - stzalloc did it */
  11696. }
  11697. np->type = NHERE;
  11698. heredoc = stzalloc(sizeof(struct heredoc));
  11699. heredoc->here = np;
  11700. c = pgetc_eatbnl();
  11701. if (c == '-') {
  11702. heredoc->striptabs = 1;
  11703. } else {
  11704. /*heredoc->striptabs = 0; - stzalloc did it */
  11705. pungetc();
  11706. }
  11707. break;
  11708. case '&':
  11709. np->type = NFROMFD;
  11710. break;
  11711. case '>':
  11712. np->type = NFROMTO;
  11713. break;
  11714. default:
  11715. np->type = NFROM;
  11716. pungetc();
  11717. break;
  11718. }
  11719. }
  11720. if (fd >= 0)
  11721. np->nfile.fd = fd;
  11722. redirnode = np;
  11723. goto parseredir_return;
  11724. }
  11725. /*
  11726. * Parse a substitution. At this point, we have read the dollar sign
  11727. * and nothing else.
  11728. */
  11729. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11730. * (assuming ascii char codes, as the original implementation did) */
  11731. #define is_special(c) \
  11732. (((unsigned)(c) - 33 < 32) \
  11733. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11734. parsesub: {
  11735. unsigned char subtype;
  11736. int typeloc;
  11737. c = pgetc_eatbnl();
  11738. if ((checkkwd & CHKEOFMARK)
  11739. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11740. ) {
  11741. #if BASH_DOLLAR_SQUOTE
  11742. if (synstack->syntax != DQSYNTAX && c == '\'')
  11743. bash_dollar_squote = 1;
  11744. else
  11745. #endif
  11746. USTPUTC('$', out);
  11747. pungetc();
  11748. } else if (c == '(') {
  11749. /* $(command) or $((arith)) */
  11750. if (pgetc_eatbnl() == '(') {
  11751. #if ENABLE_FEATURE_SH_MATH
  11752. PARSEARITH();
  11753. #else
  11754. raise_error_syntax("support for $((arith)) is disabled");
  11755. #endif
  11756. } else {
  11757. pungetc();
  11758. PARSEBACKQNEW();
  11759. }
  11760. } else {
  11761. /* $VAR, $<specialchar>, ${...}, or PEOF */
  11762. smalluint newsyn = synstack->syntax;
  11763. USTPUTC(CTLVAR, out);
  11764. typeloc = out - (char *)stackblock();
  11765. STADJUST(1, out);
  11766. subtype = VSNORMAL;
  11767. if (c == '{') {
  11768. c = pgetc_eatbnl();
  11769. subtype = 0;
  11770. }
  11771. varname:
  11772. if (is_name(c)) {
  11773. /* $[{[#]]NAME[}] */
  11774. do {
  11775. STPUTC(c, out);
  11776. c = pgetc_eatbnl();
  11777. } while (is_in_name(c));
  11778. } else if (isdigit(c)) {
  11779. /* $[{[#]]NUM[}] */
  11780. do {
  11781. STPUTC(c, out);
  11782. c = pgetc_eatbnl();
  11783. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11784. } else if (c != '}') {
  11785. /* $[{[#]]<specialchar>[}] */
  11786. int cc = c;
  11787. c = pgetc_eatbnl();
  11788. if (!subtype && cc == '#') {
  11789. subtype = VSLENGTH;
  11790. if (c == '_' || isalnum(c))
  11791. goto varname;
  11792. cc = c;
  11793. c = pgetc_eatbnl();
  11794. if (cc == '}' || c != '}') {
  11795. pungetc();
  11796. subtype = 0;
  11797. c = cc;
  11798. cc = '#';
  11799. }
  11800. }
  11801. if (!is_special(cc)) {
  11802. if (subtype == VSLENGTH)
  11803. subtype = 0;
  11804. goto badsub;
  11805. }
  11806. USTPUTC(cc, out);
  11807. } else
  11808. goto badsub;
  11809. if (subtype == 0) {
  11810. static const char types[] ALIGN1 = "}-+?=";
  11811. /* ${VAR...} but not $VAR or ${#VAR} */
  11812. /* c == first char after VAR */
  11813. int cc = c;
  11814. switch (c) {
  11815. case ':':
  11816. c = pgetc_eatbnl();
  11817. #if BASH_SUBSTR
  11818. /* This check is only needed to not misinterpret
  11819. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11820. * constructs.
  11821. */
  11822. if (!strchr(types, c)) {
  11823. subtype = VSSUBSTR;
  11824. pungetc();
  11825. break; /* "goto badsub" is bigger (!) */
  11826. }
  11827. #endif
  11828. subtype = VSNUL;
  11829. /*FALLTHROUGH*/
  11830. default: {
  11831. const char *p = strchr(types, c);
  11832. if (p == NULL)
  11833. break;
  11834. subtype |= p - types + VSNORMAL;
  11835. break;
  11836. }
  11837. case '%':
  11838. case '#':
  11839. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11840. c = pgetc_eatbnl();
  11841. if (c == cc)
  11842. subtype++;
  11843. else
  11844. pungetc();
  11845. newsyn = BASESYNTAX;
  11846. break;
  11847. #if BASH_PATTERN_SUBST
  11848. case '/':
  11849. /* ${v/[/]pattern/repl} */
  11850. //TODO: encode pattern and repl separately.
  11851. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11852. // are broken (should print "ONE")
  11853. subtype = VSREPLACE;
  11854. newsyn = BASESYNTAX;
  11855. c = pgetc_eatbnl();
  11856. if (c != '/')
  11857. goto badsub;
  11858. subtype++; /* VSREPLACEALL */
  11859. break;
  11860. #endif
  11861. }
  11862. } else {
  11863. if (subtype == VSLENGTH && c != '}')
  11864. subtype = 0;
  11865. badsub:
  11866. pungetc();
  11867. }
  11868. if (newsyn == ARISYNTAX)
  11869. newsyn = DQSYNTAX;
  11870. if ((newsyn != synstack->syntax || synstack->innerdq)
  11871. && subtype != VSNORMAL
  11872. ) {
  11873. synstack_push(&synstack,
  11874. synstack->prev ?: alloca(sizeof(*synstack)),
  11875. newsyn);
  11876. synstack->varpushed = 1;
  11877. synstack->dblquote = newsyn != BASESYNTAX;
  11878. }
  11879. ((unsigned char *)stackblock())[typeloc] = subtype;
  11880. if (subtype != VSNORMAL) {
  11881. synstack->varnest++;
  11882. if (synstack->dblquote)
  11883. synstack->dqvarnest++;
  11884. }
  11885. STPUTC('=', out);
  11886. }
  11887. goto parsesub_return;
  11888. }
  11889. /*
  11890. * Called to parse command substitutions. Newstyle is set if the command
  11891. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11892. * list of commands (passed by reference), and savelen is the number of
  11893. * characters on the top of the stack which must be preserved.
  11894. */
  11895. parsebackq: {
  11896. struct nodelist **nlpp;
  11897. union node *n;
  11898. char *str;
  11899. size_t savelen;
  11900. struct heredoc *saveheredoclist;
  11901. smallint saveprompt = 0;
  11902. str = NULL;
  11903. savelen = out - (char *)stackblock();
  11904. if (savelen > 0) {
  11905. /*
  11906. * FIXME: this can allocate very large block on stack and SEGV.
  11907. * Example:
  11908. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11909. * allocates 100kb for every command subst. With about
  11910. * a hundred command substitutions stack overflows.
  11911. * With larger prepended string, SEGV happens sooner.
  11912. */
  11913. str = alloca(savelen);
  11914. memcpy(str, stackblock(), savelen);
  11915. }
  11916. if (oldstyle) {
  11917. /* We must read until the closing backquote, giving special
  11918. * treatment to some slashes, and then push the string and
  11919. * reread it as input, interpreting it normally.
  11920. */
  11921. char *pout;
  11922. size_t psavelen;
  11923. char *pstr;
  11924. STARTSTACKSTR(pout);
  11925. for (;;) {
  11926. int pc;
  11927. setprompt_if(needprompt, 2);
  11928. pc = pgetc_eatbnl();
  11929. switch (pc) {
  11930. case '`':
  11931. goto done;
  11932. case '\\':
  11933. pc = pgetc(); /* not pgetc_eatbnl! */
  11934. if (pc != '\\' && pc != '`' && pc != '$'
  11935. && (!synstack->dblquote || pc != '"')
  11936. ) {
  11937. STPUTC('\\', pout);
  11938. }
  11939. break;
  11940. case PEOF:
  11941. raise_error_syntax("EOF in backquote substitution");
  11942. case '\n':
  11943. nlnoprompt();
  11944. break;
  11945. default:
  11946. break;
  11947. }
  11948. STPUTC(pc, pout);
  11949. }
  11950. done:
  11951. STPUTC('\0', pout);
  11952. psavelen = pout - (char *)stackblock();
  11953. if (psavelen > 0) {
  11954. pstr = grabstackstr(pout);
  11955. setinputstring(pstr);
  11956. }
  11957. }
  11958. nlpp = &bqlist;
  11959. while (*nlpp)
  11960. nlpp = &(*nlpp)->next;
  11961. *nlpp = stzalloc(sizeof(**nlpp));
  11962. /* (*nlpp)->next = NULL; - stzalloc did it */
  11963. saveheredoclist = heredoclist;
  11964. heredoclist = NULL;
  11965. if (oldstyle) {
  11966. saveprompt = doprompt;
  11967. doprompt = 0;
  11968. }
  11969. n = list(2);
  11970. if (oldstyle)
  11971. doprompt = saveprompt;
  11972. else {
  11973. if (readtoken() != TRP)
  11974. raise_error_unexpected_syntax(TRP);
  11975. setinputstring(nullstr);
  11976. }
  11977. parseheredoc();
  11978. heredoclist = saveheredoclist;
  11979. (*nlpp)->n = n;
  11980. /* Start reading from old file again. */
  11981. popfile();
  11982. /* Ignore any pushed back tokens left from the backquote parsing. */
  11983. if (oldstyle)
  11984. tokpushback = 0;
  11985. out = growstackto(savelen + 1);
  11986. if (str) {
  11987. memcpy(out, str, savelen);
  11988. STADJUST(savelen, out);
  11989. }
  11990. #if BASH_PROCESS_SUBST
  11991. if (style == PSUB)
  11992. USTPUTC(c == '<' ? CTLFROMPROC : CTLTOPROC, out);
  11993. else
  11994. #endif
  11995. USTPUTC(CTLBACKQ, out);
  11996. if (oldstyle)
  11997. goto parsebackq_oldreturn;
  11998. #if BASH_PROCESS_SUBST
  11999. else if (style == PSUB)
  12000. goto parsebackq_psreturn;
  12001. #endif
  12002. goto parsebackq_newreturn;
  12003. }
  12004. #if ENABLE_FEATURE_SH_MATH
  12005. /*
  12006. * Parse an arithmetic expansion (indicate start of one and set state)
  12007. */
  12008. parsearith: {
  12009. synstack_push(&synstack,
  12010. synstack->prev ?: alloca(sizeof(*synstack)),
  12011. ARISYNTAX);
  12012. synstack->dblquote = 1;
  12013. USTPUTC(CTLARI, out);
  12014. goto parsearith_return;
  12015. }
  12016. #endif
  12017. } /* end of readtoken */
  12018. /*
  12019. * Read the next input token.
  12020. * If the token is a word, we set backquotelist to the list of cmds in
  12021. * backquotes. We set quoteflag to true if any part of the word was
  12022. * quoted.
  12023. * If the token is TREDIR, then we set redirnode to a structure containing
  12024. * the redirection.
  12025. *
  12026. * [Change comment: here documents and internal procedures]
  12027. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  12028. * word parsing code into a separate routine. In this case, readtoken
  12029. * doesn't need to have any internal procedures, but parseword does.
  12030. * We could also make parseoperator in essence the main routine, and
  12031. * have parseword (readtoken1?) handle both words and redirection.]
  12032. */
  12033. #define NEW_xxreadtoken
  12034. #ifdef NEW_xxreadtoken
  12035. /* singles must be first! */
  12036. static const char xxreadtoken_chars[7] ALIGN1 = {
  12037. '\n', '(', ')', /* singles */
  12038. '&', '|', ';', /* doubles */
  12039. 0
  12040. };
  12041. #define xxreadtoken_singles 3
  12042. #define xxreadtoken_doubles 3
  12043. static const char xxreadtoken_tokens[] ALIGN1 = {
  12044. TNL, TLP, TRP, /* only single occurrence allowed */
  12045. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  12046. TEOF, /* corresponds to trailing nul */
  12047. TAND, TOR, TENDCASE /* if double occurrence */
  12048. };
  12049. static int
  12050. xxreadtoken(void)
  12051. {
  12052. int c;
  12053. if (tokpushback) {
  12054. tokpushback = 0;
  12055. return lasttoken;
  12056. }
  12057. setprompt_if(needprompt, 2);
  12058. for (;;) { /* until token or start of word found */
  12059. c = pgetc_eatbnl();
  12060. if (c == ' ' || c == '\t')
  12061. continue;
  12062. if (c == '#') {
  12063. while ((c = pgetc()) != '\n' && c != PEOF)
  12064. continue;
  12065. pungetc();
  12066. } else if (c == '\\') {
  12067. break; /* return readtoken1(...) */
  12068. } else {
  12069. const char *p;
  12070. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  12071. if (c != PEOF) {
  12072. if (c == '\n') {
  12073. nlnoprompt();
  12074. }
  12075. p = strchr(xxreadtoken_chars, c);
  12076. if (p == NULL)
  12077. break; /* return readtoken1(...) */
  12078. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  12079. int cc = pgetc_eatbnl();
  12080. if (cc == c) { /* double occurrence? */
  12081. p += xxreadtoken_doubles + 1;
  12082. } else {
  12083. pungetc();
  12084. #if BASH_REDIR_OUTPUT
  12085. if (c == '&' && cc == '>') /* &> */
  12086. break; /* return readtoken1(...) */
  12087. #endif
  12088. }
  12089. }
  12090. }
  12091. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  12092. return lasttoken;
  12093. }
  12094. } /* for (;;) */
  12095. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  12096. }
  12097. #else /* old xxreadtoken */
  12098. #define RETURN(token) return lasttoken = token
  12099. static int
  12100. xxreadtoken(void)
  12101. {
  12102. int c;
  12103. if (tokpushback) {
  12104. tokpushback = 0;
  12105. return lasttoken;
  12106. }
  12107. setprompt_if(needprompt, 2);
  12108. for (;;) { /* until token or start of word found */
  12109. c = pgetc_eatbnl();
  12110. switch (c) {
  12111. case ' ': case '\t':
  12112. continue;
  12113. case '#':
  12114. while ((c = pgetc()) != '\n' && c != PEOF)
  12115. continue;
  12116. pungetc();
  12117. continue;
  12118. case '\n':
  12119. nlnoprompt();
  12120. RETURN(TNL);
  12121. case PEOF:
  12122. RETURN(TEOF);
  12123. case '&':
  12124. if (pgetc_eatbnl() == '&')
  12125. RETURN(TAND);
  12126. pungetc();
  12127. RETURN(TBACKGND);
  12128. case '|':
  12129. if (pgetc_eatbnl() == '|')
  12130. RETURN(TOR);
  12131. pungetc();
  12132. RETURN(TPIPE);
  12133. case ';':
  12134. if (pgetc_eatbnl() == ';')
  12135. RETURN(TENDCASE);
  12136. pungetc();
  12137. RETURN(TSEMI);
  12138. case '(':
  12139. RETURN(TLP);
  12140. case ')':
  12141. RETURN(TRP);
  12142. }
  12143. break;
  12144. }
  12145. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  12146. #undef RETURN
  12147. }
  12148. #endif /* old xxreadtoken */
  12149. static int
  12150. readtoken(void)
  12151. {
  12152. int t;
  12153. int kwd = checkkwd;
  12154. #if DEBUG
  12155. smallint alreadyseen = tokpushback;
  12156. #endif
  12157. #if ENABLE_ASH_ALIAS
  12158. top:
  12159. #endif
  12160. t = xxreadtoken();
  12161. /*
  12162. * eat newlines
  12163. */
  12164. if (kwd & CHKNL) {
  12165. while (t == TNL) {
  12166. parseheredoc();
  12167. checkkwd = 0;
  12168. t = xxreadtoken();
  12169. }
  12170. }
  12171. kwd |= checkkwd;
  12172. checkkwd = 0;
  12173. if (t != TWORD || quoteflag) {
  12174. goto out;
  12175. }
  12176. /*
  12177. * check for keywords
  12178. */
  12179. if (kwd & CHKKWD) {
  12180. const char *const *pp;
  12181. pp = findkwd(wordtext);
  12182. if (pp) {
  12183. lasttoken = t = pp - tokname_array;
  12184. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  12185. goto out;
  12186. }
  12187. }
  12188. if (kwd & CHKALIAS) {
  12189. #if ENABLE_ASH_ALIAS
  12190. struct alias *ap;
  12191. ap = lookupalias(wordtext, 1);
  12192. if (ap != NULL) {
  12193. if (*ap->val) {
  12194. pushstring(ap->val, ap);
  12195. }
  12196. goto top;
  12197. }
  12198. #endif
  12199. }
  12200. out:
  12201. #if DEBUG
  12202. if (!alreadyseen)
  12203. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12204. else
  12205. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12206. #endif
  12207. return t;
  12208. }
  12209. /*
  12210. * Read and parse a command. Returns NODE_EOF on end of file.
  12211. * (NULL is a valid parse tree indicating a blank line.)
  12212. */
  12213. static union node *
  12214. parsecmd(int interact)
  12215. {
  12216. tokpushback = 0;
  12217. checkkwd = 0;
  12218. heredoclist = 0;
  12219. doprompt = interact;
  12220. setprompt_if(doprompt, doprompt);
  12221. needprompt = 0;
  12222. return list(1);
  12223. }
  12224. /*
  12225. * Input any here documents.
  12226. */
  12227. static void
  12228. parseheredoc(void)
  12229. {
  12230. struct heredoc *here;
  12231. union node *n;
  12232. here = heredoclist;
  12233. heredoclist = NULL;
  12234. while (here) {
  12235. tokpushback = 0;
  12236. setprompt_if(needprompt, 2);
  12237. if (here->here->type == NHERE)
  12238. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  12239. else
  12240. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  12241. n = stzalloc(sizeof(struct narg));
  12242. n->narg.type = NARG;
  12243. /*n->narg.next = NULL; - stzalloc did it */
  12244. n->narg.text = wordtext;
  12245. n->narg.backquote = backquotelist;
  12246. here->here->nhere.doc = n;
  12247. here = here->next;
  12248. }
  12249. }
  12250. static const char *
  12251. expandstr(const char *ps, int syntax_type)
  12252. {
  12253. struct parsefile *file_stop;
  12254. struct jmploc *volatile savehandler;
  12255. struct heredoc *saveheredoclist;
  12256. const char *result;
  12257. int saveprompt;
  12258. struct jmploc jmploc;
  12259. union node n;
  12260. int err;
  12261. file_stop = g_parsefile;
  12262. /* XXX Fix (char *) cast. */
  12263. setinputstring((char *)ps);
  12264. saveheredoclist = heredoclist;
  12265. heredoclist = NULL;
  12266. saveprompt = doprompt;
  12267. doprompt = 0;
  12268. result = ps;
  12269. savehandler = exception_handler;
  12270. err = setjmp(jmploc.loc);
  12271. if (err)
  12272. goto out;
  12273. /* readtoken1() might die horribly.
  12274. * Try a prompt with syntactically wrong command:
  12275. * PS1='$(date "+%H:%M:%S) > '
  12276. */
  12277. exception_handler = &jmploc;
  12278. readtoken1(pgetc_eatbnl(), syntax_type, FAKEEOFMARK, 0);
  12279. n.narg.type = NARG;
  12280. n.narg.next = NULL;
  12281. n.narg.text = wordtext;
  12282. n.narg.backquote = backquotelist;
  12283. /* expandarg() might fail too:
  12284. * PS1='$((123+))'
  12285. */
  12286. expandarg(&n, NULL, EXP_QUOTED);
  12287. result = stackblock();
  12288. out:
  12289. exception_handler = savehandler;
  12290. if (err && exception_type != EXERROR)
  12291. longjmp(exception_handler->loc, 1);
  12292. doprompt = saveprompt;
  12293. /* Try: PS1='`xxx(`' */
  12294. unwindfiles(file_stop);
  12295. heredoclist = saveheredoclist;
  12296. return result;
  12297. }
  12298. static inline int
  12299. parser_eof(void)
  12300. {
  12301. return tokpushback && lasttoken == TEOF;
  12302. }
  12303. /*
  12304. * Execute a command or commands contained in a string.
  12305. */
  12306. static int
  12307. evalstring(char *s, int flags)
  12308. {
  12309. struct jmploc *volatile savehandler;
  12310. struct jmploc jmploc;
  12311. int ex;
  12312. union node *n;
  12313. struct stackmark smark;
  12314. int status;
  12315. s = sstrdup(s);
  12316. setinputstring(s);
  12317. setstackmark(&smark);
  12318. status = 0;
  12319. /* On exception inside execution loop, we must popfile().
  12320. * Try interactively:
  12321. * readonly a=a
  12322. * command eval "a=b" # throws "is read only" error
  12323. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12324. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12325. */
  12326. savehandler = exception_handler;
  12327. ex = setjmp(jmploc.loc);
  12328. if (ex)
  12329. goto out;
  12330. exception_handler = &jmploc;
  12331. while ((n = parsecmd(0)) != NODE_EOF) {
  12332. int i;
  12333. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12334. if (n)
  12335. status = i;
  12336. popstackmark(&smark);
  12337. if (evalskip)
  12338. break;
  12339. }
  12340. out:
  12341. popstackmark(&smark);
  12342. popfile();
  12343. stunalloc(s);
  12344. exception_handler = savehandler;
  12345. if (ex)
  12346. longjmp(exception_handler->loc, ex);
  12347. return status;
  12348. }
  12349. /*
  12350. * The eval command.
  12351. */
  12352. static int FAST_FUNC
  12353. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12354. {
  12355. char *p;
  12356. char *concat;
  12357. if (argv[1]) {
  12358. p = argv[1];
  12359. argv += 2;
  12360. if (argv[0]) {
  12361. STARTSTACKSTR(concat);
  12362. for (;;) {
  12363. concat = stack_putstr(p, concat);
  12364. p = *argv++;
  12365. if (p == NULL)
  12366. break;
  12367. STPUTC(' ', concat);
  12368. }
  12369. STPUTC('\0', concat);
  12370. p = grabstackstr(concat);
  12371. }
  12372. return evalstring(p, flags & EV_TESTED);
  12373. }
  12374. return 0;
  12375. }
  12376. /*
  12377. * Read and execute commands.
  12378. * "Top" is nonzero for the top level command loop;
  12379. * it turns on prompting if the shell is interactive.
  12380. */
  12381. static int
  12382. cmdloop(int top)
  12383. {
  12384. union node *n;
  12385. struct stackmark smark;
  12386. int inter;
  12387. int status = 0;
  12388. int numeof = 0;
  12389. TRACE(("cmdloop(%d) called\n", top));
  12390. for (;;) {
  12391. int skip;
  12392. setstackmark(&smark);
  12393. #if JOBS
  12394. if (doing_jobctl)
  12395. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12396. #endif
  12397. inter = 0;
  12398. if (iflag && top) {
  12399. inter++;
  12400. chkmail();
  12401. }
  12402. n = parsecmd(inter);
  12403. #if DEBUG
  12404. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12405. showtree(n);
  12406. #endif
  12407. if (n == NODE_EOF) {
  12408. if (!top || numeof >= 50)
  12409. break;
  12410. if (!stoppedjobs()) {
  12411. if (!iflag)
  12412. break;
  12413. if (!Iflag) {
  12414. newline_and_flush(stderr);
  12415. break;
  12416. }
  12417. /* "set -o ignoreeof" active, do not exit command loop on ^D */
  12418. out2str("\nUse \"exit\" to leave shell.\n");
  12419. }
  12420. numeof++;
  12421. } else {
  12422. int i;
  12423. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12424. job_warning >>= 1;
  12425. numeof = 0;
  12426. i = evaltree(n, 0);
  12427. if (n)
  12428. status = i;
  12429. }
  12430. popstackmark(&smark);
  12431. skip = evalskip;
  12432. if (skip) {
  12433. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12434. break;
  12435. }
  12436. }
  12437. return status;
  12438. }
  12439. /*
  12440. * Take commands from a file. To be compatible we should do a path
  12441. * search for the file, which is necessary to find sub-commands.
  12442. */
  12443. static char *
  12444. find_dot_file(char *basename)
  12445. {
  12446. char *fullname;
  12447. const char *path;
  12448. struct stat statb;
  12449. int len;
  12450. /* don't try this for absolute or relative paths */
  12451. if (strchr(basename, '/'))
  12452. return basename;
  12453. path = pathval();
  12454. while ((len = padvance(&path, basename)) >= 0) {
  12455. fullname = stackblock();
  12456. if ((!pathopt || *pathopt == 'f')
  12457. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12458. ) {
  12459. /* This will be freed by the caller. */
  12460. return stalloc(len);
  12461. }
  12462. }
  12463. /* not found in PATH */
  12464. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12465. return basename;
  12466. #else
  12467. ash_msg_and_raise_error("%s: not found", basename);
  12468. /* NOTREACHED */
  12469. #endif
  12470. }
  12471. static int FAST_FUNC
  12472. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12473. {
  12474. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12475. int status = 0;
  12476. char *fullname;
  12477. char **argv;
  12478. char *args_need_save;
  12479. volatile struct shparam saveparam;
  12480. //???
  12481. // struct strlist *sp;
  12482. // for (sp = cmdenviron; sp; sp = sp->next)
  12483. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12484. nextopt(nullstr); /* handle possible "--" */
  12485. argv = argptr;
  12486. if (!argv[0]) {
  12487. /* bash says: "bash: .: filename argument required" */
  12488. return 2; /* bash compat */
  12489. }
  12490. /* This aborts if file isn't found, which is POSIXly correct.
  12491. * bash returns exitcode 1 instead.
  12492. */
  12493. fullname = find_dot_file(argv[0]);
  12494. argv++;
  12495. args_need_save = argv[0];
  12496. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12497. int argc;
  12498. saveparam = shellparam;
  12499. shellparam.malloced = 0;
  12500. argc = 1;
  12501. while (argv[argc])
  12502. argc++;
  12503. shellparam.nparam = argc;
  12504. shellparam.p = argv;
  12505. };
  12506. /* This aborts if file can't be opened, which is POSIXly correct.
  12507. * bash returns exitcode 1 instead.
  12508. */
  12509. setinputfile(fullname, INPUT_PUSH_FILE);
  12510. commandname = fullname;
  12511. status = cmdloop(0);
  12512. popfile();
  12513. if (args_need_save) {
  12514. freeparam(&shellparam);
  12515. shellparam = saveparam;
  12516. };
  12517. return status;
  12518. }
  12519. static int FAST_FUNC
  12520. exitcmd(int argc UNUSED_PARAM, char **argv)
  12521. {
  12522. if (stoppedjobs())
  12523. return 0;
  12524. if (argv[1])
  12525. savestatus = number(argv[1]);
  12526. //TODO: this script
  12527. // trap 'echo trap:$FUNCNAME' EXIT
  12528. // f() { exit; }
  12529. // f
  12530. //prints "trap:f" in bash. We can call exitshell() here to achieve this.
  12531. //For now, keeping dash code:
  12532. raise_exception(EXEXIT);
  12533. /* NOTREACHED */
  12534. }
  12535. /*
  12536. * Read a file containing shell functions.
  12537. */
  12538. static void
  12539. readcmdfile(char *name)
  12540. {
  12541. setinputfile(name, INPUT_PUSH_FILE);
  12542. cmdloop(0);
  12543. popfile();
  12544. }
  12545. /* ============ find_command inplementation */
  12546. /*
  12547. * Resolve a command name. If you change this routine, you may have to
  12548. * change the shellexec routine as well.
  12549. */
  12550. static void
  12551. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12552. {
  12553. struct tblentry *cmdp;
  12554. int idx;
  12555. int prev;
  12556. char *fullname;
  12557. struct stat statb;
  12558. int e;
  12559. int updatetbl;
  12560. struct builtincmd *bcmd;
  12561. int len;
  12562. /* If name contains a slash, don't use PATH or hash table */
  12563. if (strchr(name, '/') != NULL) {
  12564. entry->u.index = -1;
  12565. if (act & DO_ABS) {
  12566. while (stat(name, &statb) < 0) {
  12567. #ifdef SYSV
  12568. if (errno == EINTR)
  12569. continue;
  12570. #endif
  12571. entry->cmdtype = CMDUNKNOWN;
  12572. return;
  12573. }
  12574. }
  12575. entry->cmdtype = CMDNORMAL;
  12576. return;
  12577. }
  12578. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12579. updatetbl = (path == pathval());
  12580. if (!updatetbl)
  12581. act |= DO_ALTPATH;
  12582. /* If name is in the table, check answer will be ok */
  12583. cmdp = cmdlookup(name, 0);
  12584. if (cmdp != NULL) {
  12585. int bit;
  12586. switch (cmdp->cmdtype) {
  12587. default:
  12588. #if DEBUG
  12589. abort();
  12590. #endif
  12591. case CMDNORMAL:
  12592. bit = DO_ALTPATH | DO_REGBLTIN;
  12593. break;
  12594. case CMDFUNCTION:
  12595. bit = DO_NOFUNC;
  12596. break;
  12597. case CMDBUILTIN:
  12598. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12599. break;
  12600. }
  12601. if (act & bit) {
  12602. if (act & bit & DO_REGBLTIN)
  12603. goto fail;
  12604. updatetbl = 0;
  12605. cmdp = NULL;
  12606. } else if (cmdp->rehash == 0)
  12607. /* if not invalidated by cd, we're done */
  12608. goto success;
  12609. }
  12610. /* If %builtin not in path, check for builtin next */
  12611. bcmd = find_builtin(name);
  12612. if (bcmd) {
  12613. if (IS_BUILTIN_REGULAR(bcmd))
  12614. goto builtin_success;
  12615. if (act & DO_ALTPATH)
  12616. goto builtin_success;
  12617. if (builtinloc <= 0)
  12618. goto builtin_success;
  12619. }
  12620. if (act & DO_REGBLTIN)
  12621. goto fail;
  12622. #if ENABLE_FEATURE_SH_STANDALONE
  12623. {
  12624. int applet_no = find_applet_by_name(name);
  12625. if (applet_no >= 0) {
  12626. entry->cmdtype = CMDNORMAL;
  12627. entry->u.index = -2 - applet_no;
  12628. return;
  12629. }
  12630. }
  12631. #endif
  12632. /* We have to search path. */
  12633. prev = -1; /* where to start */
  12634. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12635. if (cmdp->cmdtype == CMDBUILTIN)
  12636. prev = builtinloc;
  12637. else
  12638. prev = cmdp->param.index;
  12639. }
  12640. e = ENOENT;
  12641. idx = -1;
  12642. loop:
  12643. while ((len = padvance(&path, name)) >= 0) {
  12644. const char *lpathopt = pathopt;
  12645. fullname = stackblock();
  12646. idx++;
  12647. if (lpathopt) {
  12648. if (*lpathopt == 'b') {
  12649. if (bcmd)
  12650. goto builtin_success;
  12651. continue;
  12652. } else if (!(act & DO_NOFUNC)) {
  12653. /* handled below */
  12654. } else {
  12655. /* ignore unimplemented options */
  12656. continue;
  12657. }
  12658. }
  12659. /* if rehash, don't redo absolute path names */
  12660. if (fullname[0] == '/' && idx <= prev) {
  12661. if (idx < prev)
  12662. continue;
  12663. TRACE(("searchexec \"%s\": no change\n", name));
  12664. goto success;
  12665. }
  12666. while (stat(fullname, &statb) < 0) {
  12667. #ifdef SYSV
  12668. if (errno == EINTR)
  12669. continue;
  12670. #endif
  12671. if (errno != ENOENT && errno != ENOTDIR)
  12672. e = errno;
  12673. goto loop;
  12674. }
  12675. e = EACCES; /* if we fail, this will be the error */
  12676. if (!S_ISREG(statb.st_mode))
  12677. continue;
  12678. if (lpathopt) { /* this is a %func directory */
  12679. stalloc(len);
  12680. /* NB: stalloc will return space pointed by fullname
  12681. * (because we don't have any intervening allocations
  12682. * between stunalloc above and this stalloc) */
  12683. readcmdfile(fullname);
  12684. cmdp = cmdlookup(name, 0);
  12685. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12686. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12687. stunalloc(fullname);
  12688. goto success;
  12689. }
  12690. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12691. if (!updatetbl) {
  12692. entry->cmdtype = CMDNORMAL;
  12693. entry->u.index = idx;
  12694. return;
  12695. }
  12696. INT_OFF;
  12697. cmdp = cmdlookup(name, 1);
  12698. cmdp->cmdtype = CMDNORMAL;
  12699. cmdp->param.index = idx;
  12700. INT_ON;
  12701. goto success;
  12702. }
  12703. /* We failed. If there was an entry for this command, delete it */
  12704. if (cmdp && updatetbl)
  12705. delete_cmd_entry();
  12706. if (act & DO_ERR) {
  12707. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12708. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12709. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12710. char *argv[3];
  12711. argv[0] = (char*) "command_not_found_handle";
  12712. argv[1] = name;
  12713. argv[2] = NULL;
  12714. evalfun(hookp->param.func, 2, argv, 0);
  12715. entry->cmdtype = CMDUNKNOWN;
  12716. return;
  12717. }
  12718. #endif
  12719. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12720. }
  12721. fail:
  12722. entry->cmdtype = CMDUNKNOWN;
  12723. return;
  12724. builtin_success:
  12725. if (!updatetbl) {
  12726. entry->cmdtype = CMDBUILTIN;
  12727. entry->u.cmd = bcmd;
  12728. return;
  12729. }
  12730. INT_OFF;
  12731. cmdp = cmdlookup(name, 1);
  12732. cmdp->cmdtype = CMDBUILTIN;
  12733. cmdp->param.cmd = bcmd;
  12734. INT_ON;
  12735. success:
  12736. cmdp->rehash = 0;
  12737. entry->cmdtype = cmdp->cmdtype;
  12738. entry->u = cmdp->param;
  12739. }
  12740. /*
  12741. * The trap builtin.
  12742. */
  12743. static int FAST_FUNC
  12744. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12745. {
  12746. char *action;
  12747. char **ap;
  12748. int signo, exitcode;
  12749. nextopt(nullstr);
  12750. ap = argptr;
  12751. if (!*ap) {
  12752. for (signo = 0; signo <= NTRAP_LAST; signo++) {
  12753. char *tr = trap_ptr[signo];
  12754. if (tr) {
  12755. /* note: bash adds "SIG", but only if invoked
  12756. * as "bash". If called as "sh", or if set -o posix,
  12757. * then it prints short signal names.
  12758. * We are printing short names: */
  12759. out1fmt("trap -- %s %s\n",
  12760. single_quote(tr),
  12761. (signo == NTRAP_ERR) ? "ERR" : get_signame(signo));
  12762. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12763. * In this case, we will exit very soon, no need to free(). */
  12764. /* if (trap_ptr != trap && tp[0]) */
  12765. /* free(tr); */
  12766. }
  12767. }
  12768. /*
  12769. if (trap_ptr != trap) {
  12770. free(trap_ptr);
  12771. trap_ptr = trap;
  12772. }
  12773. */
  12774. return 0;
  12775. }
  12776. /* Why the second check?
  12777. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12778. * In this case, NUM is signal no, not an action.
  12779. */
  12780. action = NULL;
  12781. if (ap[1] && !is_number(ap[0]))
  12782. action = *ap++;
  12783. exitcode = 0;
  12784. while (*ap) {
  12785. signo = strcmp(*ap, "ERR") == 0 ? NTRAP_ERR : get_signum(*ap);
  12786. if (signo < 0) {
  12787. /* Mimic bash message exactly */
  12788. ash_msg("%s: invalid signal specification", *ap);
  12789. exitcode = 1;
  12790. goto next;
  12791. }
  12792. INT_OFF;
  12793. if (action) {
  12794. if (LONE_DASH(action))
  12795. action = NULL;
  12796. else {
  12797. if (action[0]) /* not NULL and not "" and not "-" */
  12798. may_have_traps = 1;
  12799. action = ckstrdup(action);
  12800. }
  12801. }
  12802. free(trap[signo]);
  12803. trap[signo] = action;
  12804. if (signo != 0 && signo < NSIG)
  12805. setsignal(signo);
  12806. INT_ON;
  12807. next:
  12808. ap++;
  12809. }
  12810. return exitcode;
  12811. }
  12812. /* ============ Builtins */
  12813. #if ENABLE_ASH_HELP
  12814. static int FAST_FUNC
  12815. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12816. {
  12817. unsigned col;
  12818. unsigned i;
  12819. out1fmt(
  12820. "Built-in commands:\n"
  12821. "------------------\n");
  12822. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12823. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12824. builtintab[i].name + 1);
  12825. if (col > 60) {
  12826. out1fmt("\n");
  12827. col = 0;
  12828. }
  12829. }
  12830. # if ENABLE_FEATURE_SH_STANDALONE
  12831. {
  12832. const char *a = applet_names;
  12833. while (*a) {
  12834. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12835. if (col > 60) {
  12836. out1fmt("\n");
  12837. col = 0;
  12838. }
  12839. while (*a++ != '\0')
  12840. continue;
  12841. }
  12842. }
  12843. # endif
  12844. newline_and_flush(stdout);
  12845. return EXIT_SUCCESS;
  12846. }
  12847. #endif
  12848. #if MAX_HISTORY
  12849. static int FAST_FUNC
  12850. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12851. {
  12852. show_history(line_input_state);
  12853. return EXIT_SUCCESS;
  12854. }
  12855. #endif
  12856. /*
  12857. * The export and readonly commands.
  12858. */
  12859. static int FAST_FUNC
  12860. exportcmd(int argc UNUSED_PARAM, char **argv)
  12861. {
  12862. struct var *vp;
  12863. char *name;
  12864. const char *p;
  12865. char **aptr;
  12866. char opt;
  12867. int flag;
  12868. int flag_off;
  12869. /* "readonly" in bash accepts, but ignores -n.
  12870. * We do the same: it saves a conditional in nextopt's param.
  12871. */
  12872. flag_off = 0;
  12873. while ((opt = nextopt("np")) != '\0') {
  12874. if (opt == 'n')
  12875. flag_off = VEXPORT;
  12876. }
  12877. flag = VEXPORT;
  12878. if (argv[0][0] == 'r') {
  12879. flag = VREADONLY;
  12880. flag_off = 0; /* readonly ignores -n */
  12881. }
  12882. flag_off = ~flag_off;
  12883. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12884. {
  12885. aptr = argptr;
  12886. name = *aptr;
  12887. if (name) {
  12888. do {
  12889. p = strchr(name, '=');
  12890. if (p != NULL) {
  12891. p++;
  12892. } else {
  12893. vp = *findvar(hashvar(name), name);
  12894. if (vp) {
  12895. vp->flags = ((vp->flags | flag) & flag_off);
  12896. continue;
  12897. }
  12898. }
  12899. setvar(name, p, (flag & flag_off));
  12900. } while ((name = *++aptr) != NULL);
  12901. return 0;
  12902. }
  12903. }
  12904. /* No arguments. Show the list of exported or readonly vars.
  12905. * -n is ignored.
  12906. */
  12907. showvars(argv[0], flag, 0);
  12908. return 0;
  12909. }
  12910. /*
  12911. * Delete a function if it exists.
  12912. */
  12913. static void
  12914. unsetfunc(const char *name)
  12915. {
  12916. struct tblentry *cmdp;
  12917. cmdp = cmdlookup(name, 0);
  12918. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12919. delete_cmd_entry();
  12920. }
  12921. /*
  12922. * The unset builtin command. We unset the function before we unset the
  12923. * variable to allow a function to be unset when there is a readonly variable
  12924. * with the same name.
  12925. */
  12926. static int FAST_FUNC
  12927. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12928. {
  12929. char **ap;
  12930. int i;
  12931. int flag = 0;
  12932. while ((i = nextopt("vf")) != 0) {
  12933. flag = i;
  12934. }
  12935. for (ap = argptr; *ap; ap++) {
  12936. if (flag != 'f') {
  12937. unsetvar(*ap);
  12938. continue;
  12939. }
  12940. if (flag != 'v')
  12941. unsetfunc(*ap);
  12942. }
  12943. return 0;
  12944. }
  12945. static const unsigned char timescmd_str[] ALIGN1 = {
  12946. ' ', offsetof(struct tms, tms_utime),
  12947. '\n', offsetof(struct tms, tms_stime),
  12948. ' ', offsetof(struct tms, tms_cutime),
  12949. '\n', offsetof(struct tms, tms_cstime),
  12950. 0
  12951. };
  12952. static int FAST_FUNC
  12953. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12954. {
  12955. unsigned clk_tck;
  12956. const unsigned char *p;
  12957. struct tms buf;
  12958. clk_tck = bb_clk_tck();
  12959. times(&buf);
  12960. p = timescmd_str;
  12961. do {
  12962. unsigned sec, frac;
  12963. unsigned long t;
  12964. t = *(clock_t *)(((char *) &buf) + p[1]);
  12965. sec = t / clk_tck;
  12966. frac = t % clk_tck;
  12967. out1fmt("%um%u.%03us%c",
  12968. sec / 60, sec % 60,
  12969. (frac * 1000) / clk_tck,
  12970. p[0]);
  12971. p += 2;
  12972. } while (*p);
  12973. return 0;
  12974. }
  12975. #if ENABLE_FEATURE_SH_MATH
  12976. /*
  12977. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12978. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12979. *
  12980. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12981. */
  12982. static int FAST_FUNC
  12983. letcmd(int argc UNUSED_PARAM, char **argv)
  12984. {
  12985. arith_t i;
  12986. argv++;
  12987. if (!*argv)
  12988. ash_msg_and_raise_error("expression expected");
  12989. do {
  12990. i = ash_arith(*argv);
  12991. } while (*++argv);
  12992. return !i;
  12993. }
  12994. #endif
  12995. /*
  12996. * The read builtin. Options:
  12997. * -r Do not interpret '\' specially
  12998. * -s Turn off echo (tty only)
  12999. * -n NCHARS Read NCHARS max
  13000. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  13001. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  13002. * -u FD Read from given FD instead of fd 0
  13003. * -d DELIM End on DELIM char, not newline
  13004. * This uses unbuffered input, which may be avoidable in some cases.
  13005. * TODO: bash also has:
  13006. * -a ARRAY Read into array[0],[1],etc
  13007. * -e Use line editing (tty only)
  13008. */
  13009. static int FAST_FUNC
  13010. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13011. {
  13012. struct builtin_read_params params;
  13013. const char *r;
  13014. int i;
  13015. memset(&params, 0, sizeof(params));
  13016. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  13017. switch (i) {
  13018. case 'p':
  13019. params.opt_p = optionarg;
  13020. break;
  13021. case 'n':
  13022. params.opt_n = optionarg;
  13023. break;
  13024. case 's':
  13025. params.read_flags |= BUILTIN_READ_SILENT;
  13026. break;
  13027. case 't':
  13028. params.opt_t = optionarg;
  13029. break;
  13030. case 'r':
  13031. params.read_flags |= BUILTIN_READ_RAW;
  13032. break;
  13033. case 'u':
  13034. params.opt_u = optionarg;
  13035. break;
  13036. #if BASH_READ_D
  13037. case 'd':
  13038. params.opt_d = optionarg;
  13039. break;
  13040. #endif
  13041. default:
  13042. break;
  13043. }
  13044. }
  13045. if (!ENABLE_ASH_BASH_COMPAT && !argptr) {
  13046. bb_simple_error_msg("read: need variable name");
  13047. return 1;
  13048. }
  13049. params.argv = argptr;
  13050. params.setvar = setvar0;
  13051. params.ifs = bltinlookup("IFS"); /* can be NULL */
  13052. /* "read -s" needs to save/restore termios, can't allow ^C
  13053. * to jump out of it.
  13054. */
  13055. again:
  13056. INT_OFF;
  13057. r = shell_builtin_read(&params);
  13058. INT_ON;
  13059. if ((uintptr_t)r == 1 && errno == EINTR) {
  13060. /* To get SIGCHLD: sleep 1 & read x; echo $x
  13061. * Correct behavior is to not exit "read"
  13062. */
  13063. if (pending_sig == 0)
  13064. goto again;
  13065. }
  13066. if ((uintptr_t)r > 1)
  13067. ash_msg_and_raise_error(r);
  13068. return (uintptr_t)r;
  13069. }
  13070. static int FAST_FUNC
  13071. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13072. {
  13073. static const char permuser[3] ALIGN1 = "ogu";
  13074. mode_t mask;
  13075. int symbolic_mode = 0;
  13076. while (nextopt("S") != '\0') {
  13077. symbolic_mode = 1;
  13078. }
  13079. INT_OFF;
  13080. mask = umask(0);
  13081. umask(mask);
  13082. INT_ON;
  13083. if (*argptr == NULL) {
  13084. if (symbolic_mode) {
  13085. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  13086. char *p = buf;
  13087. int i;
  13088. i = 2;
  13089. for (;;) {
  13090. *p++ = ',';
  13091. *p++ = permuser[i];
  13092. *p++ = '=';
  13093. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  13094. if (!(mask & 0400)) *p++ = 'r';
  13095. if (!(mask & 0200)) *p++ = 'w';
  13096. if (!(mask & 0100)) *p++ = 'x';
  13097. mask <<= 3;
  13098. if (--i < 0)
  13099. break;
  13100. }
  13101. *p = '\0';
  13102. puts(buf + 1);
  13103. } else {
  13104. out1fmt("%04o\n", mask);
  13105. }
  13106. } else {
  13107. char *modestr = *argptr;
  13108. /* numeric umasks are taken as-is */
  13109. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  13110. if (!isdigit(modestr[0]))
  13111. mask ^= 0777;
  13112. mask = bb_parse_mode(modestr, mask);
  13113. if ((unsigned)mask > 0777) {
  13114. ash_msg_and_raise_error("illegal mode: %s", modestr);
  13115. }
  13116. if (!isdigit(modestr[0]))
  13117. mask ^= 0777;
  13118. umask(mask);
  13119. }
  13120. return 0;
  13121. }
  13122. static int FAST_FUNC
  13123. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  13124. {
  13125. return shell_builtin_ulimit(argv);
  13126. }
  13127. /* ============ main() and helpers */
  13128. /*
  13129. * This routine is called when an error or an interrupt occurs in an
  13130. * interactive shell and control is returned to the main command loop
  13131. * but prior to exitshell.
  13132. */
  13133. static void
  13134. exitreset(void)
  13135. {
  13136. /* from eval.c: */
  13137. if (savestatus >= 0) {
  13138. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  13139. exitstatus = savestatus;
  13140. savestatus = -1;
  13141. }
  13142. evalskip = 0;
  13143. loopnest = 0;
  13144. inps4 = 0;
  13145. /* from expand.c: */
  13146. ifsfree();
  13147. /* from redir.c: */
  13148. unwindredir(NULL);
  13149. }
  13150. /*
  13151. * This routine is called when an error or an interrupt occurs in an
  13152. * interactive shell and control is returned to the main command loop.
  13153. * (In dash, this function is auto-generated by build machinery).
  13154. */
  13155. static void
  13156. reset(void)
  13157. {
  13158. /* from input.c: */
  13159. g_parsefile->left_in_buffer = 0;
  13160. g_parsefile->left_in_line = 0; /* clear input buffer */
  13161. g_parsefile->unget = 0;
  13162. popallfiles();
  13163. /* from var.c: */
  13164. unwindlocalvars(NULL);
  13165. }
  13166. /*
  13167. * Called to exit the shell.
  13168. */
  13169. static void
  13170. exitshell(void)
  13171. {
  13172. struct jmploc loc;
  13173. char *p;
  13174. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  13175. save_history(line_input_state); /* may be NULL */
  13176. #endif
  13177. savestatus = exitstatus;
  13178. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  13179. if (setjmp(loc.loc))
  13180. goto out;
  13181. exception_handler = &loc;
  13182. p = trap[0];
  13183. if (p) {
  13184. trap[0] = NULL;
  13185. evalskip = 0;
  13186. trap_depth++;
  13187. evalstring(p, 0);
  13188. trap_depth--;
  13189. evalskip = SKIPFUNCDEF;
  13190. /*free(p); - we'll exit soon */
  13191. }
  13192. out:
  13193. exitreset();
  13194. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  13195. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  13196. */
  13197. setjobctl(0);
  13198. flush_stdout_stderr();
  13199. _exit(exitstatus);
  13200. /* NOTREACHED */
  13201. }
  13202. /* Don't inline: conserve stack of caller from having our locals too */
  13203. static NOINLINE void
  13204. init(void)
  13205. {
  13206. /* we will never free this */
  13207. basepf.next_to_pgetc = basepf.buf = ckzalloc(IBUFSIZ);
  13208. basepf.linno = 1;
  13209. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  13210. setsignal(SIGCHLD);
  13211. {
  13212. char **envp;
  13213. const char *p;
  13214. initvar();
  13215. for (envp = environ; envp && *envp; envp++) {
  13216. /* Used to have
  13217. * p = endofname(*envp);
  13218. * if (p != *envp && *p == '=') {
  13219. * here to weed out badly-named variables, but this breaks
  13220. * scenarios where people do want them passed to children:
  13221. * import os
  13222. * os.environ["test-test"]="test"
  13223. * if os.fork() == 0:
  13224. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  13225. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  13226. */
  13227. if (strchr(*envp, '=')) {
  13228. setvareq(*envp, VEXPORT|VTEXTFIXED);
  13229. }
  13230. }
  13231. setvareq((char*)defifsvar, VTEXTFIXED);
  13232. setvareq((char*)defoptindvar, VTEXTFIXED);
  13233. setvar0("PPID", utoa(getppid()));
  13234. #if BASH_SHLVL_VAR
  13235. p = lookupvar("SHLVL");
  13236. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  13237. #endif
  13238. #if BASH_HOSTNAME_VAR
  13239. if (!lookupvar("HOSTNAME")) {
  13240. struct utsname uts;
  13241. uname(&uts);
  13242. setvar0("HOSTNAME", uts.nodename);
  13243. }
  13244. #endif
  13245. p = lookupvar("PWD");
  13246. if (p) {
  13247. struct stat st1, st2;
  13248. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  13249. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  13250. ) {
  13251. p = NULL;
  13252. }
  13253. }
  13254. setpwd(p, 0);
  13255. }
  13256. }
  13257. //usage:#define ash_trivial_usage
  13258. //usage: "[-il] [-|+Cabefmnuvx] [-|+o OPT]... [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  13259. //////// comes from ^^^^^^^^^^optletters
  13260. //usage:#define ash_full_usage "\n\n"
  13261. //usage: "Unix shell interpreter"
  13262. /*
  13263. * Process the shell command line arguments.
  13264. */
  13265. static int
  13266. procargs(char **argv)
  13267. {
  13268. int i;
  13269. const char *xminusc;
  13270. char **xargv;
  13271. int login_sh;
  13272. xargv = argv;
  13273. login_sh = xargv[0] && xargv[0][0] == '-';
  13274. #if NUM_SCRIPTS > 0
  13275. if (minusc)
  13276. goto setarg0;
  13277. #endif
  13278. arg0 = xargv[0];
  13279. /* if (xargv[0]) - mmm, this is always true! */
  13280. xargv++;
  13281. argptr = xargv;
  13282. for (i = 0; i < NOPTS; i++)
  13283. optlist[i] = 2;
  13284. if (options(&login_sh)) {
  13285. /* it already printed err message */
  13286. raise_exception(EXERROR); /* does not return */
  13287. }
  13288. xargv = argptr;
  13289. xminusc = minusc;
  13290. if (*xargv == NULL) {
  13291. if (xminusc)
  13292. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13293. sflag = 1;
  13294. }
  13295. if (iflag == 2 /* no explicit -i given */
  13296. && sflag == 1 /* -s given (or implied) */
  13297. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13298. && isatty(0) && isatty(1) /* we are on tty */
  13299. ) {
  13300. iflag = 1;
  13301. }
  13302. if (mflag == 2)
  13303. mflag = iflag;
  13304. /* Unset options which weren't explicitly set or unset */
  13305. for (i = 0; i < NOPTS; i++)
  13306. optlist[i] &= 1; /* same effect as "if (optlist[i] == 2) optlist[i] = 0;" */
  13307. #if DEBUG == 2
  13308. debug = 1;
  13309. #endif
  13310. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13311. if (xminusc) {
  13312. minusc = *xargv++;
  13313. if (*xargv)
  13314. goto setarg0;
  13315. } else if (!sflag) {
  13316. setinputfile(*xargv, 0);
  13317. setarg0:
  13318. arg0 = *xargv++;
  13319. commandname = arg0;
  13320. }
  13321. shellparam.p = xargv;
  13322. #if ENABLE_ASH_GETOPTS
  13323. shellparam.optind = 1;
  13324. shellparam.optoff = -1;
  13325. #endif
  13326. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13327. while (*xargv) {
  13328. shellparam.nparam++;
  13329. xargv++;
  13330. }
  13331. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13332. * Try:
  13333. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13334. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13335. * NB: must do it before setting up signals (in optschanged())
  13336. * and reading .profile etc (after we return from here):
  13337. */
  13338. if (iflag)
  13339. signal(SIGHUP, SIG_DFL);
  13340. optschanged();
  13341. return login_sh;
  13342. }
  13343. /*
  13344. * Read /etc/profile, ~/.profile, $ENV.
  13345. */
  13346. static void
  13347. read_profile(const char *name)
  13348. {
  13349. name = expandstr(name, DQSYNTAX);
  13350. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13351. return;
  13352. cmdloop(0);
  13353. popfile();
  13354. }
  13355. #if PROFILE
  13356. static short profile_buf[16384];
  13357. extern int etext();
  13358. #endif
  13359. /*
  13360. * Main routine. We initialize things, parse the arguments, execute
  13361. * profiles if we're a login shell, and then call cmdloop to execute
  13362. * commands. The setjmp call sets up the location to jump to when an
  13363. * exception occurs. When an exception occurs the variable "state"
  13364. * is used to figure out how far we had gotten.
  13365. */
  13366. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13367. #if NUM_SCRIPTS > 0
  13368. int ash_main(int argc, char **argv)
  13369. #else
  13370. int ash_main(int argc UNUSED_PARAM, char **argv)
  13371. #endif
  13372. /* note: 'argc' is used only if embedded scripts are enabled */
  13373. {
  13374. volatile smallint state;
  13375. struct jmploc jmploc;
  13376. struct stackmark smark;
  13377. int login_sh;
  13378. /* Initialize global data */
  13379. INIT_G_misc();
  13380. INIT_G_memstack();
  13381. INIT_G_var();
  13382. #if ENABLE_ASH_ALIAS
  13383. INIT_G_alias();
  13384. #endif
  13385. INIT_G_cmdtable();
  13386. #if PROFILE
  13387. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13388. #endif
  13389. state = 0;
  13390. if (setjmp(jmploc.loc)) {
  13391. smallint e;
  13392. smallint s;
  13393. exitreset();
  13394. e = exception_type;
  13395. s = state;
  13396. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13397. exitshell();
  13398. }
  13399. reset();
  13400. if (e == EXINT) {
  13401. newline_and_flush(stderr);
  13402. }
  13403. popstackmark(&smark);
  13404. FORCE_INT_ON; /* enable interrupts */
  13405. if (s == 1)
  13406. goto state1;
  13407. if (s == 2)
  13408. goto state2;
  13409. if (s == 3)
  13410. goto state3;
  13411. goto state4;
  13412. }
  13413. exception_handler = &jmploc;
  13414. rootpid = getpid();
  13415. init();
  13416. setstackmark(&smark);
  13417. #if NUM_SCRIPTS > 0
  13418. if (argc < 0)
  13419. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13420. minusc = get_script_content(-argc - 1);
  13421. #endif
  13422. login_sh = procargs(argv);
  13423. #if DEBUG
  13424. TRACE(("Shell args: "));
  13425. trace_puts_args(argv);
  13426. #endif
  13427. if (login_sh) {
  13428. const char *hp;
  13429. state = 1;
  13430. read_profile("/etc/profile");
  13431. state1:
  13432. state = 2;
  13433. hp = lookupvar("HOME");
  13434. if (hp)
  13435. read_profile("$HOME/.profile");
  13436. }
  13437. state2:
  13438. state = 3;
  13439. if (iflag
  13440. #ifndef linux
  13441. && getuid() == geteuid() && getgid() == getegid()
  13442. #endif
  13443. ) {
  13444. const char *shinit = lookupvar("ENV");
  13445. if (shinit != NULL && *shinit != '\0')
  13446. read_profile(shinit);
  13447. }
  13448. popstackmark(&smark);
  13449. state3:
  13450. state = 4;
  13451. if (minusc) {
  13452. /* evalstring pushes parsefile stack.
  13453. * Ensure we don't falsely claim that 0 (stdin)
  13454. * is one of stacked source fds.
  13455. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13456. // if (!sflag) g_parsefile->pf_fd = -1;
  13457. // ^^ not necessary since now we special-case fd 0
  13458. // in save_fd_on_redirect()
  13459. lineno = 0; // bash compat
  13460. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13461. // The above makes
  13462. // ash -sc 'echo $-'
  13463. // continue reading input from stdin after running 'echo'.
  13464. // bash does not do this: it prints "hBcs" and exits.
  13465. evalstring(minusc, EV_EXIT);
  13466. }
  13467. if (sflag || minusc == NULL) {
  13468. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13469. if (line_input_state) {
  13470. const char *hp = lookupvar("HISTFILE");
  13471. if (!hp) {
  13472. hp = lookupvar("HOME");
  13473. if (hp) {
  13474. INT_OFF;
  13475. hp = concat_path_file(hp, ".ash_history");
  13476. setvar0("HISTFILE", hp);
  13477. free((char*)hp);
  13478. INT_ON;
  13479. hp = lookupvar("HISTFILE");
  13480. }
  13481. }
  13482. if (hp)
  13483. line_input_state->hist_file = xstrdup(hp);
  13484. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13485. hp = lookupvar("HISTFILESIZE");
  13486. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13487. # endif
  13488. }
  13489. #endif
  13490. state4: /* XXX ??? - why isn't this before the "if" statement */
  13491. cmdloop(1);
  13492. }
  13493. #if PROFILE
  13494. monitor(0);
  13495. #endif
  13496. #ifdef GPROF
  13497. {
  13498. extern void _mcleanup(void);
  13499. _mcleanup();
  13500. }
  13501. #endif
  13502. TRACE(("End of main reached\n"));
  13503. exitshell();
  13504. /* NOTREACHED */
  13505. }
  13506. /*-
  13507. * Copyright (c) 1989, 1991, 1993, 1994
  13508. * The Regents of the University of California. All rights reserved.
  13509. *
  13510. * This code is derived from software contributed to Berkeley by
  13511. * Kenneth Almquist.
  13512. *
  13513. * Redistribution and use in source and binary forms, with or without
  13514. * modification, are permitted provided that the following conditions
  13515. * are met:
  13516. * 1. Redistributions of source code must retain the above copyright
  13517. * notice, this list of conditions and the following disclaimer.
  13518. * 2. Redistributions in binary form must reproduce the above copyright
  13519. * notice, this list of conditions and the following disclaimer in the
  13520. * documentation and/or other materials provided with the distribution.
  13521. * 3. Neither the name of the University nor the names of its contributors
  13522. * may be used to endorse or promote products derived from this software
  13523. * without specific prior written permission.
  13524. *
  13525. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13526. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13527. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13528. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13529. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13530. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13531. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13532. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13533. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13534. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13535. * SUCH DAMAGE.
  13536. */