3
0

hush.c 305 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (64 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support process substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef F_DUPFD_CLOEXEC
  356. # define F_DUPFD_CLOEXEC F_DUPFD
  357. #endif
  358. #ifndef PIPE_BUF
  359. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  360. #endif
  361. /* So far, all bash compat is controlled by one config option */
  362. /* Separate defines document which part of code implements what */
  363. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  364. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  365. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  366. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  367. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  368. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  369. /* Build knobs */
  370. #define LEAK_HUNTING 0
  371. #define BUILD_AS_NOMMU 0
  372. /* Enable/disable sanity checks. Ok to enable in production,
  373. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  374. * Keeping 1 for now even in released versions.
  375. */
  376. #define HUSH_DEBUG 1
  377. /* Slightly bigger (+200 bytes), but faster hush.
  378. * So far it only enables a trick with counting SIGCHLDs and forks,
  379. * which allows us to do fewer waitpid's.
  380. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  381. * and therefore waitpid will return the same result as last time)
  382. */
  383. #define ENABLE_HUSH_FAST 0
  384. /* TODO: implement simplified code for users which do not need ${var%...} ops
  385. * So far ${var%...} ops are always enabled:
  386. */
  387. #define ENABLE_HUSH_DOLLAR_OPS 1
  388. #if BUILD_AS_NOMMU
  389. # undef BB_MMU
  390. # undef USE_FOR_NOMMU
  391. # undef USE_FOR_MMU
  392. # define BB_MMU 0
  393. # define USE_FOR_NOMMU(...) __VA_ARGS__
  394. # define USE_FOR_MMU(...)
  395. #endif
  396. #include "NUM_APPLETS.h"
  397. #if NUM_APPLETS == 1
  398. /* STANDALONE does not make sense, and won't compile */
  399. # undef CONFIG_FEATURE_SH_STANDALONE
  400. # undef ENABLE_FEATURE_SH_STANDALONE
  401. # undef IF_FEATURE_SH_STANDALONE
  402. # undef IF_NOT_FEATURE_SH_STANDALONE
  403. # define ENABLE_FEATURE_SH_STANDALONE 0
  404. # define IF_FEATURE_SH_STANDALONE(...)
  405. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  406. #endif
  407. #if !ENABLE_HUSH_INTERACTIVE
  408. # undef ENABLE_FEATURE_EDITING
  409. # define ENABLE_FEATURE_EDITING 0
  410. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  411. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  412. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  413. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  414. #endif
  415. /* Do we support ANY keywords? */
  416. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  417. # define HAS_KEYWORDS 1
  418. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  419. # define IF_HAS_NO_KEYWORDS(...)
  420. #else
  421. # define HAS_KEYWORDS 0
  422. # define IF_HAS_KEYWORDS(...)
  423. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  424. #endif
  425. /* If you comment out one of these below, it will be #defined later
  426. * to perform debug printfs to stderr: */
  427. #define debug_printf(...) do {} while (0)
  428. /* Finer-grained debug switches */
  429. #define debug_printf_parse(...) do {} while (0)
  430. #define debug_print_tree(a, b) do {} while (0)
  431. #define debug_printf_exec(...) do {} while (0)
  432. #define debug_printf_env(...) do {} while (0)
  433. #define debug_printf_jobs(...) do {} while (0)
  434. #define debug_printf_expand(...) do {} while (0)
  435. #define debug_printf_varexp(...) do {} while (0)
  436. #define debug_printf_glob(...) do {} while (0)
  437. #define debug_printf_redir(...) do {} while (0)
  438. #define debug_printf_list(...) do {} while (0)
  439. #define debug_printf_subst(...) do {} while (0)
  440. #define debug_printf_prompt(...) do {} while (0)
  441. #define debug_printf_clean(...) do {} while (0)
  442. #define ERR_PTR ((void*)(long)1)
  443. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  444. #define _SPECIAL_VARS_STR "_*@$!?#"
  445. #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
  446. #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
  447. #if BASH_PATTERN_SUBST
  448. /* Support / and // replace ops */
  449. /* Note that // is stored as \ in "encoded" string representation */
  450. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  451. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  452. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  453. #else
  454. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  455. # define VAR_SUBST_OPS "%#:-=+?"
  456. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  457. #endif
  458. #define SPECIAL_VAR_SYMBOL_STR "\3"
  459. #define SPECIAL_VAR_SYMBOL 3
  460. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  461. #define SPECIAL_VAR_QUOTED_SVS 1
  462. struct variable;
  463. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  464. /* This supports saving pointers malloced in vfork child,
  465. * to be freed in the parent.
  466. */
  467. #if !BB_MMU
  468. typedef struct nommu_save_t {
  469. struct variable *old_vars;
  470. char **argv;
  471. char **argv_from_re_execing;
  472. } nommu_save_t;
  473. #endif
  474. enum {
  475. RES_NONE = 0,
  476. #if ENABLE_HUSH_IF
  477. RES_IF ,
  478. RES_THEN ,
  479. RES_ELIF ,
  480. RES_ELSE ,
  481. RES_FI ,
  482. #endif
  483. #if ENABLE_HUSH_LOOPS
  484. RES_FOR ,
  485. RES_WHILE ,
  486. RES_UNTIL ,
  487. RES_DO ,
  488. RES_DONE ,
  489. #endif
  490. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  491. RES_IN ,
  492. #endif
  493. #if ENABLE_HUSH_CASE
  494. RES_CASE ,
  495. /* three pseudo-keywords support contrived "case" syntax: */
  496. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  497. RES_MATCH , /* "word)" */
  498. RES_CASE_BODY, /* "this command is inside CASE" */
  499. RES_ESAC ,
  500. #endif
  501. RES_XXXX ,
  502. RES_SNTX
  503. };
  504. typedef struct o_string {
  505. char *data;
  506. int length; /* position where data is appended */
  507. int maxlen;
  508. int o_expflags;
  509. /* At least some part of the string was inside '' or "",
  510. * possibly empty one: word"", wo''rd etc. */
  511. smallint has_quoted_part;
  512. smallint has_empty_slot;
  513. } o_string;
  514. enum {
  515. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  516. EXP_FLAG_GLOB = 0x2,
  517. /* Protect newly added chars against globbing
  518. * by prepending \ to *, ?, [, \ */
  519. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  520. };
  521. /* Used for initialization: o_string foo = NULL_O_STRING; */
  522. #define NULL_O_STRING { NULL }
  523. #ifndef debug_printf_parse
  524. static const char *const assignment_flag[] = {
  525. "MAYBE_ASSIGNMENT",
  526. "DEFINITELY_ASSIGNMENT",
  527. "NOT_ASSIGNMENT",
  528. "WORD_IS_KEYWORD",
  529. };
  530. #endif
  531. typedef struct in_str {
  532. const char *p;
  533. int peek_buf[2];
  534. int last_char;
  535. FILE *file;
  536. } in_str;
  537. /* The descrip member of this structure is only used to make
  538. * debugging output pretty */
  539. static const struct {
  540. int mode;
  541. signed char default_fd;
  542. char descrip[3];
  543. } redir_table[] = {
  544. { O_RDONLY, 0, "<" },
  545. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  546. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  547. { O_CREAT|O_RDWR, 1, "<>" },
  548. { O_RDONLY, 0, "<<" },
  549. /* Should not be needed. Bogus default_fd helps in debugging */
  550. /* { O_RDONLY, 77, "<<" }, */
  551. };
  552. struct redir_struct {
  553. struct redir_struct *next;
  554. char *rd_filename; /* filename */
  555. int rd_fd; /* fd to redirect */
  556. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  557. int rd_dup;
  558. smallint rd_type; /* (enum redir_type) */
  559. /* note: for heredocs, rd_filename contains heredoc delimiter,
  560. * and subsequently heredoc itself; and rd_dup is a bitmask:
  561. * bit 0: do we need to trim leading tabs?
  562. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  563. */
  564. };
  565. typedef enum redir_type {
  566. REDIRECT_INPUT = 0,
  567. REDIRECT_OVERWRITE = 1,
  568. REDIRECT_APPEND = 2,
  569. REDIRECT_IO = 3,
  570. REDIRECT_HEREDOC = 4,
  571. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  572. REDIRFD_CLOSE = -3,
  573. REDIRFD_SYNTAX_ERR = -2,
  574. REDIRFD_TO_FILE = -1,
  575. /* otherwise, rd_fd is redirected to rd_dup */
  576. HEREDOC_SKIPTABS = 1,
  577. HEREDOC_QUOTED = 2,
  578. } redir_type;
  579. struct command {
  580. pid_t pid; /* 0 if exited */
  581. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  582. #if ENABLE_HUSH_LINENO_VAR
  583. unsigned lineno;
  584. #endif
  585. smallint cmd_type; /* CMD_xxx */
  586. #define CMD_NORMAL 0
  587. #define CMD_SUBSHELL 1
  588. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  589. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  590. * "export v=t*"
  591. */
  592. # define CMD_SINGLEWORD_NOGLOB 2
  593. #endif
  594. #if ENABLE_HUSH_FUNCTIONS
  595. # define CMD_FUNCDEF 3
  596. #endif
  597. smalluint cmd_exitcode;
  598. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  599. struct pipe *group;
  600. #if !BB_MMU
  601. char *group_as_string;
  602. #endif
  603. #if ENABLE_HUSH_FUNCTIONS
  604. struct function *child_func;
  605. /* This field is used to prevent a bug here:
  606. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  607. * When we execute "f1() {a;}" cmd, we create new function and clear
  608. * cmd->group, cmd->group_as_string, cmd->argv[0].
  609. * When we execute "f1() {b;}", we notice that f1 exists,
  610. * and that its "parent cmd" struct is still "alive",
  611. * we put those fields back into cmd->xxx
  612. * (struct function has ->parent_cmd ptr to facilitate that).
  613. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  614. * Without this trick, loop would execute a;b;b;b;...
  615. * instead of correct sequence a;b;a;b;...
  616. * When command is freed, it severs the link
  617. * (sets ->child_func->parent_cmd to NULL).
  618. */
  619. #endif
  620. char **argv; /* command name and arguments */
  621. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  622. * and on execution these are substituted with their values.
  623. * Substitution can make _several_ words out of one argv[n]!
  624. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  625. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  626. */
  627. struct redir_struct *redirects; /* I/O redirections */
  628. };
  629. /* Is there anything in this command at all? */
  630. #define IS_NULL_CMD(cmd) \
  631. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  632. struct pipe {
  633. struct pipe *next;
  634. int num_cmds; /* total number of commands in pipe */
  635. int alive_cmds; /* number of commands running (not exited) */
  636. int stopped_cmds; /* number of commands alive, but stopped */
  637. #if ENABLE_HUSH_JOB
  638. unsigned jobid; /* job number */
  639. pid_t pgrp; /* process group ID for the job */
  640. char *cmdtext; /* name of job */
  641. #endif
  642. struct command *cmds; /* array of commands in pipe */
  643. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  644. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  645. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  646. };
  647. typedef enum pipe_style {
  648. PIPE_SEQ = 0,
  649. PIPE_AND = 1,
  650. PIPE_OR = 2,
  651. PIPE_BG = 3,
  652. } pipe_style;
  653. /* Is there anything in this pipe at all? */
  654. #define IS_NULL_PIPE(pi) \
  655. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  656. /* This holds pointers to the various results of parsing */
  657. struct parse_context {
  658. /* linked list of pipes */
  659. struct pipe *list_head;
  660. /* last pipe (being constructed right now) */
  661. struct pipe *pipe;
  662. /* last command in pipe (being constructed right now) */
  663. struct command *command;
  664. /* last redirect in command->redirects list */
  665. struct redir_struct *pending_redirect;
  666. o_string word;
  667. #if !BB_MMU
  668. o_string as_string;
  669. #endif
  670. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  671. #if HAS_KEYWORDS
  672. smallint ctx_res_w;
  673. smallint ctx_inverted; /* "! cmd | cmd" */
  674. #if ENABLE_HUSH_CASE
  675. smallint ctx_dsemicolon; /* ";;" seen */
  676. #endif
  677. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  678. int old_flag;
  679. /* group we are enclosed in:
  680. * example: "if pipe1; pipe2; then pipe3; fi"
  681. * when we see "if" or "then", we malloc and copy current context,
  682. * and make ->stack point to it. then we parse pipeN.
  683. * when closing "then" / fi" / whatever is found,
  684. * we move list_head into ->stack->command->group,
  685. * copy ->stack into current context, and delete ->stack.
  686. * (parsing of { list } and ( list ) doesn't use this method)
  687. */
  688. struct parse_context *stack;
  689. #endif
  690. };
  691. enum {
  692. MAYBE_ASSIGNMENT = 0,
  693. DEFINITELY_ASSIGNMENT = 1,
  694. NOT_ASSIGNMENT = 2,
  695. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  696. WORD_IS_KEYWORD = 3,
  697. };
  698. /* On program start, environ points to initial environment.
  699. * putenv adds new pointers into it, unsetenv removes them.
  700. * Neither of these (de)allocates the strings.
  701. * setenv allocates new strings in malloc space and does putenv,
  702. * and thus setenv is unusable (leaky) for shell's purposes */
  703. #define setenv(...) setenv_is_leaky_dont_use()
  704. struct variable {
  705. struct variable *next;
  706. char *varstr; /* points to "name=" portion */
  707. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  708. uint16_t var_nest_level;
  709. smallint flg_export; /* putenv should be done on this var */
  710. smallint flg_read_only;
  711. };
  712. enum {
  713. BC_BREAK = 1,
  714. BC_CONTINUE = 2,
  715. };
  716. #if ENABLE_HUSH_FUNCTIONS
  717. struct function {
  718. struct function *next;
  719. char *name;
  720. struct command *parent_cmd;
  721. struct pipe *body;
  722. # if !BB_MMU
  723. char *body_as_string;
  724. # endif
  725. };
  726. #endif
  727. /* set -/+o OPT support. (TODO: make it optional)
  728. * bash supports the following opts:
  729. * allexport off
  730. * braceexpand on
  731. * emacs on
  732. * errexit off
  733. * errtrace off
  734. * functrace off
  735. * hashall on
  736. * histexpand off
  737. * history on
  738. * ignoreeof off
  739. * interactive-comments on
  740. * keyword off
  741. * monitor on
  742. * noclobber off
  743. * noexec off
  744. * noglob off
  745. * nolog off
  746. * notify off
  747. * nounset off
  748. * onecmd off
  749. * physical off
  750. * pipefail off
  751. * posix off
  752. * privileged off
  753. * verbose off
  754. * vi off
  755. * xtrace off
  756. */
  757. static const char o_opt_strings[] ALIGN1 =
  758. "pipefail\0"
  759. "noexec\0"
  760. "errexit\0"
  761. #if ENABLE_HUSH_MODE_X
  762. "xtrace\0"
  763. #endif
  764. ;
  765. enum {
  766. OPT_O_PIPEFAIL,
  767. OPT_O_NOEXEC,
  768. OPT_O_ERREXIT,
  769. #if ENABLE_HUSH_MODE_X
  770. OPT_O_XTRACE,
  771. #endif
  772. NUM_OPT_O
  773. };
  774. struct FILE_list {
  775. struct FILE_list *next;
  776. FILE *fp;
  777. int fd;
  778. };
  779. /* "Globals" within this file */
  780. /* Sorted roughly by size (smaller offsets == smaller code) */
  781. struct globals {
  782. /* interactive_fd != 0 means we are an interactive shell.
  783. * If we are, then saved_tty_pgrp can also be != 0, meaning
  784. * that controlling tty is available. With saved_tty_pgrp == 0,
  785. * job control still works, but terminal signals
  786. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  787. * process groups can only be created with "cmd &".
  788. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  789. * to give tty to the foreground process group,
  790. * and will take it back when the group is stopped (^Z)
  791. * or killed (^C).
  792. */
  793. #if ENABLE_HUSH_INTERACTIVE
  794. /* 'interactive_fd' is a fd# open to ctty, if we have one
  795. * _AND_ if we decided to act interactively */
  796. int interactive_fd;
  797. const char *PS1;
  798. IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
  799. # define G_interactive_fd (G.interactive_fd)
  800. #else
  801. # define G_interactive_fd 0
  802. #endif
  803. #if ENABLE_FEATURE_EDITING
  804. line_input_t *line_input_state;
  805. #endif
  806. pid_t root_pid;
  807. pid_t root_ppid;
  808. pid_t last_bg_pid;
  809. #if ENABLE_HUSH_RANDOM_SUPPORT
  810. random_t random_gen;
  811. #endif
  812. #if ENABLE_HUSH_JOB
  813. int run_list_level;
  814. unsigned last_jobid;
  815. pid_t saved_tty_pgrp;
  816. struct pipe *job_list;
  817. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  818. #else
  819. # define G_saved_tty_pgrp 0
  820. #endif
  821. /* How deeply are we in context where "set -e" is ignored */
  822. int errexit_depth;
  823. /* "set -e" rules (do we follow them correctly?):
  824. * Exit if pipe, list, or compound command exits with a non-zero status.
  825. * Shell does not exit if failed command is part of condition in
  826. * if/while, part of && or || list except the last command, any command
  827. * in a pipe but the last, or if the command's return value is being
  828. * inverted with !. If a compound command other than a subshell returns a
  829. * non-zero status because a command failed while -e was being ignored, the
  830. * shell does not exit. A trap on ERR, if set, is executed before the shell
  831. * exits [ERR is a bashism].
  832. *
  833. * If a compound command or function executes in a context where -e is
  834. * ignored, none of the commands executed within are affected by the -e
  835. * setting. If a compound command or function sets -e while executing in a
  836. * context where -e is ignored, that setting does not have any effect until
  837. * the compound command or the command containing the function call completes.
  838. */
  839. char o_opt[NUM_OPT_O];
  840. #if ENABLE_HUSH_MODE_X
  841. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  842. #else
  843. # define G_x_mode 0
  844. #endif
  845. #if ENABLE_HUSH_INTERACTIVE
  846. smallint promptmode; /* 0: PS1, 1: PS2 */
  847. #endif
  848. smallint flag_SIGINT;
  849. #if ENABLE_HUSH_LOOPS
  850. smallint flag_break_continue;
  851. #endif
  852. #if ENABLE_HUSH_FUNCTIONS
  853. /* 0: outside of a function (or sourced file)
  854. * -1: inside of a function, ok to use return builtin
  855. * 1: return is invoked, skip all till end of func
  856. */
  857. smallint flag_return_in_progress;
  858. # define G_flag_return_in_progress (G.flag_return_in_progress)
  859. #else
  860. # define G_flag_return_in_progress 0
  861. #endif
  862. smallint exiting; /* used to prevent EXIT trap recursion */
  863. /* These support $?, $#, and $1 */
  864. smalluint last_exitcode;
  865. smalluint expand_exitcode;
  866. smalluint last_bg_pid_exitcode;
  867. #if ENABLE_HUSH_SET
  868. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  869. smalluint global_args_malloced;
  870. # define G_global_args_malloced (G.global_args_malloced)
  871. #else
  872. # define G_global_args_malloced 0
  873. #endif
  874. /* how many non-NULL argv's we have. NB: $# + 1 */
  875. int global_argc;
  876. char **global_argv;
  877. #if !BB_MMU
  878. char *argv0_for_re_execing;
  879. #endif
  880. #if ENABLE_HUSH_LOOPS
  881. unsigned depth_break_continue;
  882. unsigned depth_of_loop;
  883. #endif
  884. #if ENABLE_HUSH_GETOPTS
  885. unsigned getopt_count;
  886. #endif
  887. const char *ifs;
  888. char *ifs_whitespace; /* = G.ifs or malloced */
  889. const char *cwd;
  890. struct variable *top_var;
  891. char **expanded_assignments;
  892. struct variable **shadowed_vars_pp;
  893. unsigned var_nest_level;
  894. #if ENABLE_HUSH_FUNCTIONS
  895. # if ENABLE_HUSH_LOCAL
  896. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  897. # endif
  898. struct function *top_func;
  899. #endif
  900. /* Signal and trap handling */
  901. #if ENABLE_HUSH_FAST
  902. unsigned count_SIGCHLD;
  903. unsigned handled_SIGCHLD;
  904. smallint we_have_children;
  905. #endif
  906. #if ENABLE_HUSH_LINENO_VAR
  907. unsigned lineno;
  908. char *lineno_var;
  909. #endif
  910. struct FILE_list *FILE_list;
  911. /* Which signals have non-DFL handler (even with no traps set)?
  912. * Set at the start to:
  913. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  914. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  915. * The rest is cleared right before execv syscalls.
  916. * Other than these two times, never modified.
  917. */
  918. unsigned special_sig_mask;
  919. #if ENABLE_HUSH_JOB
  920. unsigned fatal_sig_mask;
  921. # define G_fatal_sig_mask (G.fatal_sig_mask)
  922. #else
  923. # define G_fatal_sig_mask 0
  924. #endif
  925. #if ENABLE_HUSH_TRAP
  926. char **traps; /* char *traps[NSIG] */
  927. # define G_traps G.traps
  928. #else
  929. # define G_traps ((char**)NULL)
  930. #endif
  931. sigset_t pending_set;
  932. #if ENABLE_HUSH_MEMLEAK
  933. unsigned long memleak_value;
  934. #endif
  935. #if HUSH_DEBUG
  936. int debug_indent;
  937. #endif
  938. struct sigaction sa;
  939. #if ENABLE_FEATURE_EDITING
  940. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  941. #endif
  942. };
  943. #define G (*ptr_to_globals)
  944. /* Not #defining name to G.name - this quickly gets unwieldy
  945. * (too many defines). Also, I actually prefer to see when a variable
  946. * is global, thus "G." prefix is a useful hint */
  947. #define INIT_G() do { \
  948. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  949. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  950. sigfillset(&G.sa.sa_mask); \
  951. G.sa.sa_flags = SA_RESTART; \
  952. } while (0)
  953. /* Function prototypes for builtins */
  954. static int builtin_cd(char **argv) FAST_FUNC;
  955. #if ENABLE_HUSH_ECHO
  956. static int builtin_echo(char **argv) FAST_FUNC;
  957. #endif
  958. static int builtin_eval(char **argv) FAST_FUNC;
  959. static int builtin_exec(char **argv) FAST_FUNC;
  960. static int builtin_exit(char **argv) FAST_FUNC;
  961. #if ENABLE_HUSH_EXPORT
  962. static int builtin_export(char **argv) FAST_FUNC;
  963. #endif
  964. #if ENABLE_HUSH_READONLY
  965. static int builtin_readonly(char **argv) FAST_FUNC;
  966. #endif
  967. #if ENABLE_HUSH_JOB
  968. static int builtin_fg_bg(char **argv) FAST_FUNC;
  969. static int builtin_jobs(char **argv) FAST_FUNC;
  970. #endif
  971. #if ENABLE_HUSH_GETOPTS
  972. static int builtin_getopts(char **argv) FAST_FUNC;
  973. #endif
  974. #if ENABLE_HUSH_HELP
  975. static int builtin_help(char **argv) FAST_FUNC;
  976. #endif
  977. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  978. static int builtin_history(char **argv) FAST_FUNC;
  979. #endif
  980. #if ENABLE_HUSH_LOCAL
  981. static int builtin_local(char **argv) FAST_FUNC;
  982. #endif
  983. #if ENABLE_HUSH_MEMLEAK
  984. static int builtin_memleak(char **argv) FAST_FUNC;
  985. #endif
  986. #if ENABLE_HUSH_PRINTF
  987. static int builtin_printf(char **argv) FAST_FUNC;
  988. #endif
  989. static int builtin_pwd(char **argv) FAST_FUNC;
  990. #if ENABLE_HUSH_READ
  991. static int builtin_read(char **argv) FAST_FUNC;
  992. #endif
  993. #if ENABLE_HUSH_SET
  994. static int builtin_set(char **argv) FAST_FUNC;
  995. #endif
  996. static int builtin_shift(char **argv) FAST_FUNC;
  997. static int builtin_source(char **argv) FAST_FUNC;
  998. #if ENABLE_HUSH_TEST || BASH_TEST2
  999. static int builtin_test(char **argv) FAST_FUNC;
  1000. #endif
  1001. #if ENABLE_HUSH_TRAP
  1002. static int builtin_trap(char **argv) FAST_FUNC;
  1003. #endif
  1004. #if ENABLE_HUSH_TYPE
  1005. static int builtin_type(char **argv) FAST_FUNC;
  1006. #endif
  1007. #if ENABLE_HUSH_TIMES
  1008. static int builtin_times(char **argv) FAST_FUNC;
  1009. #endif
  1010. static int builtin_true(char **argv) FAST_FUNC;
  1011. #if ENABLE_HUSH_UMASK
  1012. static int builtin_umask(char **argv) FAST_FUNC;
  1013. #endif
  1014. #if ENABLE_HUSH_UNSET
  1015. static int builtin_unset(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_KILL
  1018. static int builtin_kill(char **argv) FAST_FUNC;
  1019. #endif
  1020. #if ENABLE_HUSH_WAIT
  1021. static int builtin_wait(char **argv) FAST_FUNC;
  1022. #endif
  1023. #if ENABLE_HUSH_LOOPS
  1024. static int builtin_break(char **argv) FAST_FUNC;
  1025. static int builtin_continue(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if ENABLE_HUSH_FUNCTIONS
  1028. static int builtin_return(char **argv) FAST_FUNC;
  1029. #endif
  1030. /* Table of built-in functions. They can be forked or not, depending on
  1031. * context: within pipes, they fork. As simple commands, they do not.
  1032. * When used in non-forking context, they can change global variables
  1033. * in the parent shell process. If forked, of course they cannot.
  1034. * For example, 'unset foo | whatever' will parse and run, but foo will
  1035. * still be set at the end. */
  1036. struct built_in_command {
  1037. const char *b_cmd;
  1038. int (*b_function)(char **argv) FAST_FUNC;
  1039. #if ENABLE_HUSH_HELP
  1040. const char *b_descr;
  1041. # define BLTIN(cmd, func, help) { cmd, func, help }
  1042. #else
  1043. # define BLTIN(cmd, func, help) { cmd, func }
  1044. #endif
  1045. };
  1046. static const struct built_in_command bltins1[] = {
  1047. BLTIN("." , builtin_source , "Run commands in file"),
  1048. BLTIN(":" , builtin_true , NULL),
  1049. #if ENABLE_HUSH_JOB
  1050. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1051. #endif
  1052. #if ENABLE_HUSH_LOOPS
  1053. BLTIN("break" , builtin_break , "Exit loop"),
  1054. #endif
  1055. BLTIN("cd" , builtin_cd , "Change directory"),
  1056. #if ENABLE_HUSH_LOOPS
  1057. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1058. #endif
  1059. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1060. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1061. BLTIN("exit" , builtin_exit , NULL),
  1062. #if ENABLE_HUSH_EXPORT
  1063. BLTIN("export" , builtin_export , "Set environment variables"),
  1064. #endif
  1065. #if ENABLE_HUSH_JOB
  1066. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1067. #endif
  1068. #if ENABLE_HUSH_GETOPTS
  1069. BLTIN("getopts" , builtin_getopts , NULL),
  1070. #endif
  1071. #if ENABLE_HUSH_HELP
  1072. BLTIN("help" , builtin_help , NULL),
  1073. #endif
  1074. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1075. BLTIN("history" , builtin_history , "Show history"),
  1076. #endif
  1077. #if ENABLE_HUSH_JOB
  1078. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1079. #endif
  1080. #if ENABLE_HUSH_KILL
  1081. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1082. #endif
  1083. #if ENABLE_HUSH_LOCAL
  1084. BLTIN("local" , builtin_local , "Set local variables"),
  1085. #endif
  1086. #if ENABLE_HUSH_MEMLEAK
  1087. BLTIN("memleak" , builtin_memleak , NULL),
  1088. #endif
  1089. #if ENABLE_HUSH_READ
  1090. BLTIN("read" , builtin_read , "Input into variable"),
  1091. #endif
  1092. #if ENABLE_HUSH_READONLY
  1093. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1094. #endif
  1095. #if ENABLE_HUSH_FUNCTIONS
  1096. BLTIN("return" , builtin_return , "Return from function"),
  1097. #endif
  1098. #if ENABLE_HUSH_SET
  1099. BLTIN("set" , builtin_set , "Set positional parameters"),
  1100. #endif
  1101. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1102. #if BASH_SOURCE
  1103. BLTIN("source" , builtin_source , NULL),
  1104. #endif
  1105. #if ENABLE_HUSH_TIMES
  1106. BLTIN("times" , builtin_times , NULL),
  1107. #endif
  1108. #if ENABLE_HUSH_TRAP
  1109. BLTIN("trap" , builtin_trap , "Trap signals"),
  1110. #endif
  1111. BLTIN("true" , builtin_true , NULL),
  1112. #if ENABLE_HUSH_TYPE
  1113. BLTIN("type" , builtin_type , "Show command type"),
  1114. #endif
  1115. #if ENABLE_HUSH_ULIMIT
  1116. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1117. #endif
  1118. #if ENABLE_HUSH_UMASK
  1119. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1120. #endif
  1121. #if ENABLE_HUSH_UNSET
  1122. BLTIN("unset" , builtin_unset , "Unset variables"),
  1123. #endif
  1124. #if ENABLE_HUSH_WAIT
  1125. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1126. #endif
  1127. };
  1128. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1129. * (it's cheaper to run an external program in this case):
  1130. */
  1131. static const struct built_in_command bltins2[] = {
  1132. #if ENABLE_HUSH_TEST
  1133. BLTIN("[" , builtin_test , NULL),
  1134. #endif
  1135. #if BASH_TEST2
  1136. BLTIN("[[" , builtin_test , NULL),
  1137. #endif
  1138. #if ENABLE_HUSH_ECHO
  1139. BLTIN("echo" , builtin_echo , NULL),
  1140. #endif
  1141. #if ENABLE_HUSH_PRINTF
  1142. BLTIN("printf" , builtin_printf , NULL),
  1143. #endif
  1144. BLTIN("pwd" , builtin_pwd , NULL),
  1145. #if ENABLE_HUSH_TEST
  1146. BLTIN("test" , builtin_test , NULL),
  1147. #endif
  1148. };
  1149. /* Debug printouts.
  1150. */
  1151. #if HUSH_DEBUG
  1152. /* prevent disasters with G.debug_indent < 0 */
  1153. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1154. # define debug_enter() (G.debug_indent++)
  1155. # define debug_leave() (G.debug_indent--)
  1156. #else
  1157. # define indent() ((void)0)
  1158. # define debug_enter() ((void)0)
  1159. # define debug_leave() ((void)0)
  1160. #endif
  1161. #ifndef debug_printf
  1162. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1163. #endif
  1164. #ifndef debug_printf_parse
  1165. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1166. #endif
  1167. #ifndef debug_printf_exec
  1168. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1169. #endif
  1170. #ifndef debug_printf_env
  1171. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1172. #endif
  1173. #ifndef debug_printf_jobs
  1174. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1175. # define DEBUG_JOBS 1
  1176. #else
  1177. # define DEBUG_JOBS 0
  1178. #endif
  1179. #ifndef debug_printf_expand
  1180. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1181. # define DEBUG_EXPAND 1
  1182. #else
  1183. # define DEBUG_EXPAND 0
  1184. #endif
  1185. #ifndef debug_printf_varexp
  1186. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1187. #endif
  1188. #ifndef debug_printf_glob
  1189. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1190. # define DEBUG_GLOB 1
  1191. #else
  1192. # define DEBUG_GLOB 0
  1193. #endif
  1194. #ifndef debug_printf_redir
  1195. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1196. #endif
  1197. #ifndef debug_printf_list
  1198. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1199. #endif
  1200. #ifndef debug_printf_subst
  1201. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1202. #endif
  1203. #ifndef debug_printf_prompt
  1204. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1205. #endif
  1206. #ifndef debug_printf_clean
  1207. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1208. # define DEBUG_CLEAN 1
  1209. #else
  1210. # define DEBUG_CLEAN 0
  1211. #endif
  1212. #if DEBUG_EXPAND
  1213. static void debug_print_strings(const char *prefix, char **vv)
  1214. {
  1215. indent();
  1216. fdprintf(2, "%s:\n", prefix);
  1217. while (*vv)
  1218. fdprintf(2, " '%s'\n", *vv++);
  1219. }
  1220. #else
  1221. # define debug_print_strings(prefix, vv) ((void)0)
  1222. #endif
  1223. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1224. */
  1225. #if LEAK_HUNTING
  1226. static void *xxmalloc(int lineno, size_t size)
  1227. {
  1228. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1229. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1230. return ptr;
  1231. }
  1232. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1233. {
  1234. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1235. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1236. return ptr;
  1237. }
  1238. static char *xxstrdup(int lineno, const char *str)
  1239. {
  1240. char *ptr = xstrdup(str);
  1241. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1242. return ptr;
  1243. }
  1244. static void xxfree(void *ptr)
  1245. {
  1246. fdprintf(2, "free %p\n", ptr);
  1247. free(ptr);
  1248. }
  1249. # define xmalloc(s) xxmalloc(__LINE__, s)
  1250. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1251. # define xstrdup(s) xxstrdup(__LINE__, s)
  1252. # define free(p) xxfree(p)
  1253. #endif
  1254. /* Syntax and runtime errors. They always abort scripts.
  1255. * In interactive use they usually discard unparsed and/or unexecuted commands
  1256. * and return to the prompt.
  1257. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1258. */
  1259. #if HUSH_DEBUG < 2
  1260. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1261. # define syntax_error(lineno, msg) syntax_error(msg)
  1262. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1263. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1264. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1265. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1266. #endif
  1267. static void die_if_script(void)
  1268. {
  1269. if (!G_interactive_fd) {
  1270. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1271. xfunc_error_retval = G.last_exitcode;
  1272. xfunc_die();
  1273. }
  1274. }
  1275. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1276. {
  1277. va_list p;
  1278. #if HUSH_DEBUG >= 2
  1279. bb_error_msg("hush.c:%u", lineno);
  1280. #endif
  1281. va_start(p, fmt);
  1282. bb_verror_msg(fmt, p, NULL);
  1283. va_end(p);
  1284. die_if_script();
  1285. }
  1286. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1287. {
  1288. if (msg)
  1289. bb_error_msg("syntax error: %s", msg);
  1290. else
  1291. bb_error_msg("syntax error");
  1292. die_if_script();
  1293. }
  1294. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1295. {
  1296. bb_error_msg("syntax error at '%s'", msg);
  1297. die_if_script();
  1298. }
  1299. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1300. {
  1301. bb_error_msg("syntax error: unterminated %s", s);
  1302. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1303. // die_if_script();
  1304. }
  1305. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1306. {
  1307. char msg[2] = { ch, '\0' };
  1308. syntax_error_unterm_str(lineno, msg);
  1309. }
  1310. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1311. {
  1312. char msg[2];
  1313. msg[0] = ch;
  1314. msg[1] = '\0';
  1315. #if HUSH_DEBUG >= 2
  1316. bb_error_msg("hush.c:%u", lineno);
  1317. #endif
  1318. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1319. die_if_script();
  1320. }
  1321. #if HUSH_DEBUG < 2
  1322. # undef msg_and_die_if_script
  1323. # undef syntax_error
  1324. # undef syntax_error_at
  1325. # undef syntax_error_unterm_ch
  1326. # undef syntax_error_unterm_str
  1327. # undef syntax_error_unexpected_ch
  1328. #else
  1329. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1330. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1331. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1332. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1333. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1334. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1335. #endif
  1336. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1337. static void cmdedit_update_prompt(void);
  1338. #else
  1339. # define cmdedit_update_prompt() ((void)0)
  1340. #endif
  1341. /* Utility functions
  1342. */
  1343. /* Replace each \x with x in place, return ptr past NUL. */
  1344. static char *unbackslash(char *src)
  1345. {
  1346. char *dst = src = strchrnul(src, '\\');
  1347. while (1) {
  1348. if (*src == '\\') {
  1349. src++;
  1350. if (*src != '\0') {
  1351. /* \x -> x */
  1352. *dst++ = *src++;
  1353. continue;
  1354. }
  1355. /* else: "\<nul>". Do not delete this backslash.
  1356. * Testcase: eval 'echo ok\'
  1357. */
  1358. *dst++ = '\\';
  1359. /* fallthrough */
  1360. }
  1361. if ((*dst++ = *src++) == '\0')
  1362. break;
  1363. }
  1364. return dst;
  1365. }
  1366. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1367. {
  1368. int i;
  1369. unsigned count1;
  1370. unsigned count2;
  1371. char **v;
  1372. v = strings;
  1373. count1 = 0;
  1374. if (v) {
  1375. while (*v) {
  1376. count1++;
  1377. v++;
  1378. }
  1379. }
  1380. count2 = 0;
  1381. v = add;
  1382. while (*v) {
  1383. count2++;
  1384. v++;
  1385. }
  1386. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1387. v[count1 + count2] = NULL;
  1388. i = count2;
  1389. while (--i >= 0)
  1390. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1391. return v;
  1392. }
  1393. #if LEAK_HUNTING
  1394. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1395. {
  1396. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1397. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1398. return ptr;
  1399. }
  1400. #define add_strings_to_strings(strings, add, need_to_dup) \
  1401. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1402. #endif
  1403. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1404. static char **add_string_to_strings(char **strings, char *add)
  1405. {
  1406. char *v[2];
  1407. v[0] = add;
  1408. v[1] = NULL;
  1409. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1410. }
  1411. #if LEAK_HUNTING
  1412. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1413. {
  1414. char **ptr = add_string_to_strings(strings, add);
  1415. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1416. return ptr;
  1417. }
  1418. #define add_string_to_strings(strings, add) \
  1419. xx_add_string_to_strings(__LINE__, strings, add)
  1420. #endif
  1421. static void free_strings(char **strings)
  1422. {
  1423. char **v;
  1424. if (!strings)
  1425. return;
  1426. v = strings;
  1427. while (*v) {
  1428. free(*v);
  1429. v++;
  1430. }
  1431. free(strings);
  1432. }
  1433. static int dup_CLOEXEC(int fd, int avoid_fd)
  1434. {
  1435. int newfd;
  1436. repeat:
  1437. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1438. if (newfd >= 0) {
  1439. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1440. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1441. } else { /* newfd < 0 */
  1442. if (errno == EBUSY)
  1443. goto repeat;
  1444. if (errno == EINTR)
  1445. goto repeat;
  1446. }
  1447. return newfd;
  1448. }
  1449. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1450. {
  1451. int newfd;
  1452. repeat:
  1453. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1454. if (newfd < 0) {
  1455. if (errno == EBUSY)
  1456. goto repeat;
  1457. if (errno == EINTR)
  1458. goto repeat;
  1459. /* fd was not open? */
  1460. if (errno == EBADF)
  1461. return fd;
  1462. xfunc_die();
  1463. }
  1464. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1465. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1466. close(fd);
  1467. return newfd;
  1468. }
  1469. /* Manipulating the list of open FILEs */
  1470. static FILE *remember_FILE(FILE *fp)
  1471. {
  1472. if (fp) {
  1473. struct FILE_list *n = xmalloc(sizeof(*n));
  1474. n->next = G.FILE_list;
  1475. G.FILE_list = n;
  1476. n->fp = fp;
  1477. n->fd = fileno(fp);
  1478. close_on_exec_on(n->fd);
  1479. }
  1480. return fp;
  1481. }
  1482. static void fclose_and_forget(FILE *fp)
  1483. {
  1484. struct FILE_list **pp = &G.FILE_list;
  1485. while (*pp) {
  1486. struct FILE_list *cur = *pp;
  1487. if (cur->fp == fp) {
  1488. *pp = cur->next;
  1489. free(cur);
  1490. break;
  1491. }
  1492. pp = &cur->next;
  1493. }
  1494. fclose(fp);
  1495. }
  1496. static int save_FILEs_on_redirect(int fd, int avoid_fd)
  1497. {
  1498. struct FILE_list *fl = G.FILE_list;
  1499. while (fl) {
  1500. if (fd == fl->fd) {
  1501. /* We use it only on script files, they are all CLOEXEC */
  1502. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1503. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1504. return 1;
  1505. }
  1506. fl = fl->next;
  1507. }
  1508. return 0;
  1509. }
  1510. static void restore_redirected_FILEs(void)
  1511. {
  1512. struct FILE_list *fl = G.FILE_list;
  1513. while (fl) {
  1514. int should_be = fileno(fl->fp);
  1515. if (fl->fd != should_be) {
  1516. debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
  1517. xmove_fd(fl->fd, should_be);
  1518. fl->fd = should_be;
  1519. }
  1520. fl = fl->next;
  1521. }
  1522. }
  1523. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1524. static void close_all_FILE_list(void)
  1525. {
  1526. struct FILE_list *fl = G.FILE_list;
  1527. while (fl) {
  1528. /* fclose would also free FILE object.
  1529. * It is disastrous if we share memory with a vforked parent.
  1530. * I'm not sure we never come here after vfork.
  1531. * Therefore just close fd, nothing more.
  1532. */
  1533. /*fclose(fl->fp); - unsafe */
  1534. close(fl->fd);
  1535. fl = fl->next;
  1536. }
  1537. }
  1538. #endif
  1539. static int fd_in_FILEs(int fd)
  1540. {
  1541. struct FILE_list *fl = G.FILE_list;
  1542. while (fl) {
  1543. if (fl->fd == fd)
  1544. return 1;
  1545. fl = fl->next;
  1546. }
  1547. return 0;
  1548. }
  1549. /* Helpers for setting new $n and restoring them back
  1550. */
  1551. typedef struct save_arg_t {
  1552. char *sv_argv0;
  1553. char **sv_g_argv;
  1554. int sv_g_argc;
  1555. IF_HUSH_SET(smallint sv_g_malloced;)
  1556. } save_arg_t;
  1557. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1558. {
  1559. sv->sv_argv0 = argv[0];
  1560. sv->sv_g_argv = G.global_argv;
  1561. sv->sv_g_argc = G.global_argc;
  1562. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1563. argv[0] = G.global_argv[0]; /* retain $0 */
  1564. G.global_argv = argv;
  1565. IF_HUSH_SET(G.global_args_malloced = 0;)
  1566. G.global_argc = 1 + string_array_len(argv + 1);
  1567. }
  1568. static void restore_G_args(save_arg_t *sv, char **argv)
  1569. {
  1570. #if ENABLE_HUSH_SET
  1571. if (G.global_args_malloced) {
  1572. /* someone ran "set -- arg1 arg2 ...", undo */
  1573. char **pp = G.global_argv;
  1574. while (*++pp) /* note: does not free $0 */
  1575. free(*pp);
  1576. free(G.global_argv);
  1577. }
  1578. #endif
  1579. argv[0] = sv->sv_argv0;
  1580. G.global_argv = sv->sv_g_argv;
  1581. G.global_argc = sv->sv_g_argc;
  1582. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1583. }
  1584. /* Basic theory of signal handling in shell
  1585. * ========================================
  1586. * This does not describe what hush does, rather, it is current understanding
  1587. * what it _should_ do. If it doesn't, it's a bug.
  1588. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1589. *
  1590. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1591. * is finished or backgrounded. It is the same in interactive and
  1592. * non-interactive shells, and is the same regardless of whether
  1593. * a user trap handler is installed or a shell special one is in effect.
  1594. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1595. * backgrounds (i.e. stops) or kills all members of currently running
  1596. * pipe.
  1597. *
  1598. * Wait builtin is interruptible by signals for which user trap is set
  1599. * or by SIGINT in interactive shell.
  1600. *
  1601. * Trap handlers will execute even within trap handlers. (right?)
  1602. *
  1603. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1604. * except for handlers set to '' (empty string).
  1605. *
  1606. * If job control is off, backgrounded commands ("cmd &")
  1607. * have SIGINT, SIGQUIT set to SIG_IGN.
  1608. *
  1609. * Commands which are run in command substitution ("`cmd`")
  1610. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1611. *
  1612. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1613. * by the shell from its parent.
  1614. *
  1615. * Signals which differ from SIG_DFL action
  1616. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1617. *
  1618. * SIGQUIT: ignore
  1619. * SIGTERM (interactive): ignore
  1620. * SIGHUP (interactive):
  1621. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1622. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1623. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1624. * that all pipe members are stopped. Try this in bash:
  1625. * while :; do :; done - ^Z does not background it
  1626. * (while :; do :; done) - ^Z backgrounds it
  1627. * SIGINT (interactive): wait for last pipe, ignore the rest
  1628. * of the command line, show prompt. NB: ^C does not send SIGINT
  1629. * to interactive shell while shell is waiting for a pipe,
  1630. * since shell is bg'ed (is not in foreground process group).
  1631. * Example 1: this waits 5 sec, but does not execute ls:
  1632. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1633. * Example 2: this does not wait and does not execute ls:
  1634. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1635. * Example 3: this does not wait 5 sec, but executes ls:
  1636. * "sleep 5; ls -l" + press ^C
  1637. * Example 4: this does not wait and does not execute ls:
  1638. * "sleep 5 & wait; ls -l" + press ^C
  1639. *
  1640. * (What happens to signals which are IGN on shell start?)
  1641. * (What happens with signal mask on shell start?)
  1642. *
  1643. * Old implementation
  1644. * ==================
  1645. * We use in-kernel pending signal mask to determine which signals were sent.
  1646. * We block all signals which we don't want to take action immediately,
  1647. * i.e. we block all signals which need to have special handling as described
  1648. * above, and all signals which have traps set.
  1649. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1650. * and act on them.
  1651. *
  1652. * unsigned special_sig_mask: a mask of such "special" signals
  1653. * sigset_t blocked_set: current blocked signal set
  1654. *
  1655. * "trap - SIGxxx":
  1656. * clear bit in blocked_set unless it is also in special_sig_mask
  1657. * "trap 'cmd' SIGxxx":
  1658. * set bit in blocked_set (even if 'cmd' is '')
  1659. * after [v]fork, if we plan to be a shell:
  1660. * unblock signals with special interactive handling
  1661. * (child shell is not interactive),
  1662. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1663. * after [v]fork, if we plan to exec:
  1664. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1665. * Restore blocked signal set to one inherited by shell just prior to exec.
  1666. *
  1667. * Note: as a result, we do not use signal handlers much. The only uses
  1668. * are to count SIGCHLDs
  1669. * and to restore tty pgrp on signal-induced exit.
  1670. *
  1671. * Note 2 (compat):
  1672. * Standard says "When a subshell is entered, traps that are not being ignored
  1673. * are set to the default actions". bash interprets it so that traps which
  1674. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1675. *
  1676. * Problem: the above approach makes it unwieldy to catch signals while
  1677. * we are in read builtin, or while we read commands from stdin:
  1678. * masked signals are not visible!
  1679. *
  1680. * New implementation
  1681. * ==================
  1682. * We record each signal we are interested in by installing signal handler
  1683. * for them - a bit like emulating kernel pending signal mask in userspace.
  1684. * We are interested in: signals which need to have special handling
  1685. * as described above, and all signals which have traps set.
  1686. * Signals are recorded in pending_set.
  1687. * After each pipe execution, we extract any pending signals
  1688. * and act on them.
  1689. *
  1690. * unsigned special_sig_mask: a mask of shell-special signals.
  1691. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1692. * char *traps[sig] if trap for sig is set (even if it's '').
  1693. * sigset_t pending_set: set of sigs we received.
  1694. *
  1695. * "trap - SIGxxx":
  1696. * if sig is in special_sig_mask, set handler back to:
  1697. * record_pending_signo, or to IGN if it's a tty stop signal
  1698. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1699. * else: set handler back to SIG_DFL
  1700. * "trap 'cmd' SIGxxx":
  1701. * set handler to record_pending_signo.
  1702. * "trap '' SIGxxx":
  1703. * set handler to SIG_IGN.
  1704. * after [v]fork, if we plan to be a shell:
  1705. * set signals with special interactive handling to SIG_DFL
  1706. * (because child shell is not interactive),
  1707. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1708. * after [v]fork, if we plan to exec:
  1709. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1710. *
  1711. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1712. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1713. *
  1714. * Note (compat):
  1715. * Standard says "When a subshell is entered, traps that are not being ignored
  1716. * are set to the default actions". bash interprets it so that traps which
  1717. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1718. */
  1719. enum {
  1720. SPECIAL_INTERACTIVE_SIGS = 0
  1721. | (1 << SIGTERM)
  1722. | (1 << SIGINT)
  1723. | (1 << SIGHUP)
  1724. ,
  1725. SPECIAL_JOBSTOP_SIGS = 0
  1726. #if ENABLE_HUSH_JOB
  1727. | (1 << SIGTTIN)
  1728. | (1 << SIGTTOU)
  1729. | (1 << SIGTSTP)
  1730. #endif
  1731. ,
  1732. };
  1733. static void record_pending_signo(int sig)
  1734. {
  1735. sigaddset(&G.pending_set, sig);
  1736. #if ENABLE_HUSH_FAST
  1737. if (sig == SIGCHLD) {
  1738. G.count_SIGCHLD++;
  1739. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1740. }
  1741. #endif
  1742. }
  1743. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1744. {
  1745. struct sigaction old_sa;
  1746. /* We could use signal() to install handlers... almost:
  1747. * except that we need to mask ALL signals while handlers run.
  1748. * I saw signal nesting in strace, race window isn't small.
  1749. * SA_RESTART is also needed, but in Linux, signal()
  1750. * sets SA_RESTART too.
  1751. */
  1752. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1753. /* sigfillset(&G.sa.sa_mask); - already done */
  1754. /* G.sa.sa_flags = SA_RESTART; - already done */
  1755. G.sa.sa_handler = handler;
  1756. sigaction(sig, &G.sa, &old_sa);
  1757. return old_sa.sa_handler;
  1758. }
  1759. static void hush_exit(int exitcode) NORETURN;
  1760. static void restore_ttypgrp_and__exit(void) NORETURN;
  1761. static void restore_ttypgrp_and__exit(void)
  1762. {
  1763. /* xfunc has failed! die die die */
  1764. /* no EXIT traps, this is an escape hatch! */
  1765. G.exiting = 1;
  1766. hush_exit(xfunc_error_retval);
  1767. }
  1768. #if ENABLE_HUSH_JOB
  1769. /* Needed only on some libc:
  1770. * It was observed that on exit(), fgetc'ed buffered data
  1771. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1772. * With the net effect that even after fork(), not vfork(),
  1773. * exit() in NOEXECed applet in "sh SCRIPT":
  1774. * noexec_applet_here
  1775. * echo END_OF_SCRIPT
  1776. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1777. * This makes "echo END_OF_SCRIPT" executed twice.
  1778. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1779. * and in `cmd` handling.
  1780. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1781. */
  1782. static void fflush_and__exit(void) NORETURN;
  1783. static void fflush_and__exit(void)
  1784. {
  1785. fflush_all();
  1786. _exit(xfunc_error_retval);
  1787. }
  1788. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1789. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1790. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1791. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1792. /* Restores tty foreground process group, and exits.
  1793. * May be called as signal handler for fatal signal
  1794. * (will resend signal to itself, producing correct exit state)
  1795. * or called directly with -EXITCODE.
  1796. * We also call it if xfunc is exiting.
  1797. */
  1798. static void sigexit(int sig) NORETURN;
  1799. static void sigexit(int sig)
  1800. {
  1801. /* Careful: we can end up here after [v]fork. Do not restore
  1802. * tty pgrp then, only top-level shell process does that */
  1803. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1804. /* Disable all signals: job control, SIGPIPE, etc.
  1805. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1806. */
  1807. sigprocmask_allsigs(SIG_BLOCK);
  1808. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1809. }
  1810. /* Not a signal, just exit */
  1811. if (sig <= 0)
  1812. _exit(- sig);
  1813. kill_myself_with_sig(sig); /* does not return */
  1814. }
  1815. #else
  1816. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1817. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1818. #endif
  1819. static sighandler_t pick_sighandler(unsigned sig)
  1820. {
  1821. sighandler_t handler = SIG_DFL;
  1822. if (sig < sizeof(unsigned)*8) {
  1823. unsigned sigmask = (1 << sig);
  1824. #if ENABLE_HUSH_JOB
  1825. /* is sig fatal? */
  1826. if (G_fatal_sig_mask & sigmask)
  1827. handler = sigexit;
  1828. else
  1829. #endif
  1830. /* sig has special handling? */
  1831. if (G.special_sig_mask & sigmask) {
  1832. handler = record_pending_signo;
  1833. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1834. * in order to ignore them: they will be raised
  1835. * in an endless loop when we try to do some
  1836. * terminal ioctls! We do have to _ignore_ these.
  1837. */
  1838. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1839. handler = SIG_IGN;
  1840. }
  1841. }
  1842. return handler;
  1843. }
  1844. /* Restores tty foreground process group, and exits. */
  1845. static void hush_exit(int exitcode)
  1846. {
  1847. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1848. save_history(G.line_input_state);
  1849. #endif
  1850. fflush_all();
  1851. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1852. char *argv[3];
  1853. /* argv[0] is unused */
  1854. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1855. argv[2] = NULL;
  1856. G.exiting = 1; /* prevent EXIT trap recursion */
  1857. /* Note: G_traps[0] is not cleared!
  1858. * "trap" will still show it, if executed
  1859. * in the handler */
  1860. builtin_eval(argv);
  1861. }
  1862. #if ENABLE_FEATURE_CLEAN_UP
  1863. {
  1864. struct variable *cur_var;
  1865. if (G.cwd != bb_msg_unknown)
  1866. free((char*)G.cwd);
  1867. cur_var = G.top_var;
  1868. while (cur_var) {
  1869. struct variable *tmp = cur_var;
  1870. if (!cur_var->max_len)
  1871. free(cur_var->varstr);
  1872. cur_var = cur_var->next;
  1873. free(tmp);
  1874. }
  1875. }
  1876. #endif
  1877. fflush_all();
  1878. #if ENABLE_HUSH_JOB
  1879. sigexit(- (exitcode & 0xff));
  1880. #else
  1881. _exit(exitcode);
  1882. #endif
  1883. }
  1884. //TODO: return a mask of ALL handled sigs?
  1885. static int check_and_run_traps(void)
  1886. {
  1887. int last_sig = 0;
  1888. while (1) {
  1889. int sig;
  1890. if (sigisemptyset(&G.pending_set))
  1891. break;
  1892. sig = 0;
  1893. do {
  1894. sig++;
  1895. if (sigismember(&G.pending_set, sig)) {
  1896. sigdelset(&G.pending_set, sig);
  1897. goto got_sig;
  1898. }
  1899. } while (sig < NSIG);
  1900. break;
  1901. got_sig:
  1902. if (G_traps && G_traps[sig]) {
  1903. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1904. if (G_traps[sig][0]) {
  1905. /* We have user-defined handler */
  1906. smalluint save_rcode;
  1907. char *argv[3];
  1908. /* argv[0] is unused */
  1909. argv[1] = xstrdup(G_traps[sig]);
  1910. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1911. argv[2] = NULL;
  1912. save_rcode = G.last_exitcode;
  1913. builtin_eval(argv);
  1914. free(argv[1]);
  1915. //FIXME: shouldn't it be set to 128 + sig instead?
  1916. G.last_exitcode = save_rcode;
  1917. last_sig = sig;
  1918. } /* else: "" trap, ignoring signal */
  1919. continue;
  1920. }
  1921. /* not a trap: special action */
  1922. switch (sig) {
  1923. case SIGINT:
  1924. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  1925. G.flag_SIGINT = 1;
  1926. last_sig = sig;
  1927. break;
  1928. #if ENABLE_HUSH_JOB
  1929. case SIGHUP: {
  1930. //TODO: why are we doing this? ash and dash don't do this,
  1931. //they have no handler for SIGHUP at all,
  1932. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  1933. struct pipe *job;
  1934. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  1935. /* bash is observed to signal whole process groups,
  1936. * not individual processes */
  1937. for (job = G.job_list; job; job = job->next) {
  1938. if (job->pgrp <= 0)
  1939. continue;
  1940. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  1941. if (kill(- job->pgrp, SIGHUP) == 0)
  1942. kill(- job->pgrp, SIGCONT);
  1943. }
  1944. sigexit(SIGHUP);
  1945. }
  1946. #endif
  1947. #if ENABLE_HUSH_FAST
  1948. case SIGCHLD:
  1949. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  1950. G.count_SIGCHLD++;
  1951. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1952. /* Note:
  1953. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  1954. * This simplifies wait builtin a bit.
  1955. */
  1956. break;
  1957. #endif
  1958. default: /* ignored: */
  1959. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  1960. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  1961. /* Note:
  1962. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  1963. * Example: wait is not interrupted by TERM
  1964. * in interactive shell, because TERM is ignored.
  1965. */
  1966. break;
  1967. }
  1968. }
  1969. return last_sig;
  1970. }
  1971. static const char *get_cwd(int force)
  1972. {
  1973. if (force || G.cwd == NULL) {
  1974. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  1975. * we must not try to free(bb_msg_unknown) */
  1976. if (G.cwd == bb_msg_unknown)
  1977. G.cwd = NULL;
  1978. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  1979. if (!G.cwd)
  1980. G.cwd = bb_msg_unknown;
  1981. }
  1982. return G.cwd;
  1983. }
  1984. /*
  1985. * Shell and environment variable support
  1986. */
  1987. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  1988. {
  1989. struct variable **pp;
  1990. struct variable *cur;
  1991. pp = &G.top_var;
  1992. while ((cur = *pp) != NULL) {
  1993. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  1994. return pp;
  1995. pp = &cur->next;
  1996. }
  1997. return NULL;
  1998. }
  1999. static const char* FAST_FUNC get_local_var_value(const char *name)
  2000. {
  2001. struct variable **vpp;
  2002. unsigned len = strlen(name);
  2003. if (G.expanded_assignments) {
  2004. char **cpp = G.expanded_assignments;
  2005. while (*cpp) {
  2006. char *cp = *cpp;
  2007. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2008. return cp + len + 1;
  2009. cpp++;
  2010. }
  2011. }
  2012. vpp = get_ptr_to_local_var(name, len);
  2013. if (vpp)
  2014. return (*vpp)->varstr + len + 1;
  2015. if (strcmp(name, "PPID") == 0)
  2016. return utoa(G.root_ppid);
  2017. // bash compat: UID? EUID?
  2018. #if ENABLE_HUSH_RANDOM_SUPPORT
  2019. if (strcmp(name, "RANDOM") == 0)
  2020. return utoa(next_random(&G.random_gen));
  2021. #endif
  2022. return NULL;
  2023. }
  2024. static void handle_changed_special_names(const char *name, unsigned name_len)
  2025. {
  2026. if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2027. && name_len == 3 && name[0] == 'P' && name[1] == 'S'
  2028. ) {
  2029. cmdedit_update_prompt();
  2030. return;
  2031. }
  2032. if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
  2033. && name_len == 6
  2034. ) {
  2035. #if ENABLE_HUSH_LINENO_VAR
  2036. if (strncmp(name, "LINENO", 6) == 0) {
  2037. G.lineno_var = NULL;
  2038. return;
  2039. }
  2040. #endif
  2041. #if ENABLE_HUSH_GETOPTS
  2042. if (strncmp(name, "OPTIND", 6) == 0) {
  2043. G.getopt_count = 0;
  2044. return;
  2045. }
  2046. #endif
  2047. }
  2048. }
  2049. /* str holds "NAME=VAL" and is expected to be malloced.
  2050. * We take ownership of it.
  2051. */
  2052. #define SETFLAG_EXPORT (1 << 0)
  2053. #define SETFLAG_UNEXPORT (1 << 1)
  2054. #define SETFLAG_MAKE_RO (1 << 2)
  2055. #define SETFLAG_VARLVL_SHIFT 3
  2056. static int set_local_var(char *str, unsigned flags)
  2057. {
  2058. struct variable **cur_pp;
  2059. struct variable *cur;
  2060. char *free_me = NULL;
  2061. char *eq_sign;
  2062. int name_len;
  2063. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2064. eq_sign = strchr(str, '=');
  2065. if (HUSH_DEBUG && !eq_sign)
  2066. bb_error_msg_and_die("BUG in setvar");
  2067. name_len = eq_sign - str + 1; /* including '=' */
  2068. cur_pp = &G.top_var;
  2069. while ((cur = *cur_pp) != NULL) {
  2070. if (strncmp(cur->varstr, str, name_len) != 0) {
  2071. cur_pp = &cur->next;
  2072. continue;
  2073. }
  2074. /* We found an existing var with this name */
  2075. if (cur->flg_read_only) {
  2076. bb_error_msg("%s: readonly variable", str);
  2077. free(str);
  2078. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2079. //but export per se succeeds (does put the var in env). We don't mimic that.
  2080. return -1;
  2081. }
  2082. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2083. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2084. *eq_sign = '\0';
  2085. unsetenv(str);
  2086. *eq_sign = '=';
  2087. }
  2088. if (cur->var_nest_level < local_lvl) {
  2089. /* bash 3.2.33(1) and exported vars:
  2090. * # export z=z
  2091. * # f() { local z=a; env | grep ^z; }
  2092. * # f
  2093. * z=a
  2094. * # env | grep ^z
  2095. * z=z
  2096. */
  2097. if (cur->flg_export)
  2098. flags |= SETFLAG_EXPORT;
  2099. /* New variable is local ("local VAR=VAL" or
  2100. * "VAR=VAL cmd")
  2101. * and existing one is global, or local
  2102. * on a lower level that new one.
  2103. * Remove it from global variable list:
  2104. */
  2105. *cur_pp = cur->next;
  2106. if (G.shadowed_vars_pp) {
  2107. /* Save in "shadowed" list */
  2108. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2109. cur->flg_export ? "exported " : "",
  2110. cur->varstr, cur->var_nest_level, str, local_lvl
  2111. );
  2112. cur->next = *G.shadowed_vars_pp;
  2113. *G.shadowed_vars_pp = cur;
  2114. } else {
  2115. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2116. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2117. cur->flg_export ? "exported " : "",
  2118. cur->varstr, cur->var_nest_level, str, local_lvl
  2119. );
  2120. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2121. free_me = cur->varstr; /* then free it later */
  2122. free(cur);
  2123. }
  2124. break;
  2125. }
  2126. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2127. debug_printf_env("assignement '%s' does not change anything\n", str);
  2128. free_and_exp:
  2129. free(str);
  2130. goto exp;
  2131. }
  2132. /* Replace the value in the found "struct variable" */
  2133. if (cur->max_len != 0) {
  2134. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2135. /* This one is from startup env, reuse space */
  2136. debug_printf_env("reusing startup env for '%s'\n", str);
  2137. strcpy(cur->varstr, str);
  2138. goto free_and_exp;
  2139. }
  2140. /* Can't reuse */
  2141. cur->max_len = 0;
  2142. goto set_str_and_exp;
  2143. }
  2144. /* max_len == 0 signifies "malloced" var, which we can
  2145. * (and have to) free. But we can't free(cur->varstr) here:
  2146. * if cur->flg_export is 1, it is in the environment.
  2147. * We should either unsetenv+free, or wait until putenv,
  2148. * then putenv(new)+free(old).
  2149. */
  2150. free_me = cur->varstr;
  2151. goto set_str_and_exp;
  2152. }
  2153. /* Not found or shadowed - create new variable struct */
  2154. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2155. cur = xzalloc(sizeof(*cur));
  2156. cur->var_nest_level = local_lvl;
  2157. cur->next = *cur_pp;
  2158. *cur_pp = cur;
  2159. set_str_and_exp:
  2160. cur->varstr = str;
  2161. exp:
  2162. #if !BB_MMU || ENABLE_HUSH_READONLY
  2163. if (flags & SETFLAG_MAKE_RO) {
  2164. cur->flg_read_only = 1;
  2165. }
  2166. #endif
  2167. if (flags & SETFLAG_EXPORT)
  2168. cur->flg_export = 1;
  2169. if (cur->flg_export) {
  2170. if (flags & SETFLAG_UNEXPORT) {
  2171. cur->flg_export = 0;
  2172. /* unsetenv was already done */
  2173. } else {
  2174. int i;
  2175. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2176. i = putenv(cur->varstr);
  2177. /* only now we can free old exported malloced string */
  2178. free(free_me);
  2179. return i;
  2180. }
  2181. }
  2182. free(free_me);
  2183. handle_changed_special_names(cur->varstr, name_len - 1);
  2184. return 0;
  2185. }
  2186. /* Used at startup and after each cd */
  2187. static void set_pwd_var(unsigned flag)
  2188. {
  2189. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2190. }
  2191. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2192. static int unset_local_var_len(const char *name, int name_len)
  2193. {
  2194. struct variable *cur;
  2195. struct variable **cur_pp;
  2196. cur_pp = &G.top_var;
  2197. while ((cur = *cur_pp) != NULL) {
  2198. if (strncmp(cur->varstr, name, name_len) == 0
  2199. && cur->varstr[name_len] == '='
  2200. ) {
  2201. if (cur->flg_read_only) {
  2202. bb_error_msg("%s: readonly variable", name);
  2203. return EXIT_FAILURE;
  2204. }
  2205. *cur_pp = cur->next;
  2206. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2207. bb_unsetenv(cur->varstr);
  2208. if (!cur->max_len)
  2209. free(cur->varstr);
  2210. free(cur);
  2211. break;
  2212. }
  2213. cur_pp = &cur->next;
  2214. }
  2215. /* Handle "unset PS1" et al even if did not find the variable to unset */
  2216. handle_changed_special_names(name, name_len);
  2217. return EXIT_SUCCESS;
  2218. }
  2219. static int unset_local_var(const char *name)
  2220. {
  2221. return unset_local_var_len(name, strlen(name));
  2222. }
  2223. #endif
  2224. #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
  2225. || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  2226. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2227. {
  2228. char *var = xasprintf("%s=%s", name, val);
  2229. set_local_var(var, /*flag:*/ 0);
  2230. }
  2231. #endif
  2232. /*
  2233. * Helpers for "var1=val1 var2=val2 cmd" feature
  2234. */
  2235. static void add_vars(struct variable *var)
  2236. {
  2237. struct variable *next;
  2238. while (var) {
  2239. next = var->next;
  2240. var->next = G.top_var;
  2241. G.top_var = var;
  2242. if (var->flg_export) {
  2243. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2244. putenv(var->varstr);
  2245. } else {
  2246. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2247. }
  2248. var = next;
  2249. }
  2250. }
  2251. /* We put strings[i] into variable table and possibly putenv them.
  2252. * If variable is read only, we can free the strings[i]
  2253. * which attempts to overwrite it.
  2254. * The strings[] vector itself is freed.
  2255. */
  2256. static void set_vars_and_save_old(char **strings)
  2257. {
  2258. char **s;
  2259. if (!strings)
  2260. return;
  2261. s = strings;
  2262. while (*s) {
  2263. struct variable *var_p;
  2264. struct variable **var_pp;
  2265. char *eq;
  2266. eq = strchr(*s, '=');
  2267. if (eq) {
  2268. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2269. if (var_pp) {
  2270. var_p = *var_pp;
  2271. if (var_p->flg_read_only) {
  2272. char **p;
  2273. bb_error_msg("%s: readonly variable", *s);
  2274. /*
  2275. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2276. * If VAR is readonly, leaving it in the list
  2277. * after asssignment error (msg above)
  2278. * causes doubled error message later, on unset.
  2279. */
  2280. debug_printf_env("removing/freeing '%s' element\n", *s);
  2281. free(*s);
  2282. p = s;
  2283. do { *p = p[1]; p++; } while (*p);
  2284. goto next;
  2285. }
  2286. /* below, set_local_var() with nest level will
  2287. * "shadow" (remove) this variable from
  2288. * global linked list.
  2289. */
  2290. }
  2291. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2292. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2293. } else if (HUSH_DEBUG) {
  2294. bb_error_msg_and_die("BUG in varexp4");
  2295. }
  2296. s++;
  2297. next: ;
  2298. }
  2299. free(strings);
  2300. }
  2301. /*
  2302. * Unicode helper
  2303. */
  2304. static void reinit_unicode_for_hush(void)
  2305. {
  2306. /* Unicode support should be activated even if LANG is set
  2307. * _during_ shell execution, not only if it was set when
  2308. * shell was started. Therefore, re-check LANG every time:
  2309. */
  2310. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2311. || ENABLE_UNICODE_USING_LOCALE
  2312. ) {
  2313. const char *s = get_local_var_value("LC_ALL");
  2314. if (!s) s = get_local_var_value("LC_CTYPE");
  2315. if (!s) s = get_local_var_value("LANG");
  2316. reinit_unicode(s);
  2317. }
  2318. }
  2319. /*
  2320. * in_str support (strings, and "strings" read from files).
  2321. */
  2322. #if ENABLE_HUSH_INTERACTIVE
  2323. /* To test correct lineedit/interactive behavior, type from command line:
  2324. * echo $P\
  2325. * \
  2326. * AT\
  2327. * H\
  2328. * \
  2329. * It exercises a lot of corner cases.
  2330. */
  2331. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2332. static void cmdedit_update_prompt(void)
  2333. {
  2334. G.PS1 = get_local_var_value("PS1");
  2335. if (G.PS1 == NULL)
  2336. G.PS1 = "";
  2337. G.PS2 = get_local_var_value("PS2");
  2338. if (G.PS2 == NULL)
  2339. G.PS2 = "";
  2340. }
  2341. # endif
  2342. static const char *setup_prompt_string(void)
  2343. {
  2344. const char *prompt_str;
  2345. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2346. IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
  2347. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
  2348. if (G.promptmode == 0) { /* PS1 */
  2349. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  2350. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2351. free((char*)G.PS1);
  2352. /* bash uses $PWD value, even if it is set by user.
  2353. * It uses current dir only if PWD is unset.
  2354. * We always use current dir. */
  2355. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2356. }
  2357. prompt_str = G.PS1;
  2358. }
  2359. debug_printf("prompt_str '%s'\n", prompt_str);
  2360. return prompt_str;
  2361. }
  2362. static int get_user_input(struct in_str *i)
  2363. {
  2364. int r;
  2365. const char *prompt_str;
  2366. prompt_str = setup_prompt_string();
  2367. # if ENABLE_FEATURE_EDITING
  2368. for (;;) {
  2369. reinit_unicode_for_hush();
  2370. if (G.flag_SIGINT) {
  2371. /* There was ^C'ed, make it look prettier: */
  2372. bb_putchar('\n');
  2373. G.flag_SIGINT = 0;
  2374. }
  2375. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2376. * only after <Enter>. (^C works immediately) */
  2377. r = read_line_input(G.line_input_state, prompt_str,
  2378. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2379. );
  2380. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2381. if (r == 0)
  2382. raise(SIGINT);
  2383. check_and_run_traps();
  2384. if (r != 0 && !G.flag_SIGINT)
  2385. break;
  2386. /* ^C or SIGINT: repeat */
  2387. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2388. write(STDOUT_FILENO, "^C", 2);
  2389. G.last_exitcode = 128 + SIGINT;
  2390. }
  2391. if (r < 0) {
  2392. /* EOF/error detected */
  2393. i->p = NULL;
  2394. i->peek_buf[0] = r = EOF;
  2395. return r;
  2396. }
  2397. i->p = G.user_input_buf;
  2398. return (unsigned char)*i->p++;
  2399. # else
  2400. for (;;) {
  2401. G.flag_SIGINT = 0;
  2402. if (i->last_char == '\0' || i->last_char == '\n') {
  2403. /* Why check_and_run_traps here? Try this interactively:
  2404. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2405. * $ <[enter], repeatedly...>
  2406. * Without check_and_run_traps, handler never runs.
  2407. */
  2408. check_and_run_traps();
  2409. fputs(prompt_str, stdout);
  2410. }
  2411. fflush_all();
  2412. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2413. r = fgetc(i->file);
  2414. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2415. * no ^C masking happens during fgetc, no special code for ^C:
  2416. * it generates SIGINT as usual.
  2417. */
  2418. check_and_run_traps();
  2419. if (G.flag_SIGINT)
  2420. G.last_exitcode = 128 + SIGINT;
  2421. if (r != '\0')
  2422. break;
  2423. }
  2424. return r;
  2425. # endif
  2426. }
  2427. /* This is the magic location that prints prompts
  2428. * and gets data back from the user */
  2429. static int fgetc_interactive(struct in_str *i)
  2430. {
  2431. int ch;
  2432. /* If it's interactive stdin, get new line. */
  2433. if (G_interactive_fd && i->file == stdin) {
  2434. /* Returns first char (or EOF), the rest is in i->p[] */
  2435. ch = get_user_input(i);
  2436. G.promptmode = 1; /* PS2 */
  2437. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2438. } else {
  2439. /* Not stdin: script file, sourced file, etc */
  2440. do ch = fgetc(i->file); while (ch == '\0');
  2441. }
  2442. return ch;
  2443. }
  2444. #else
  2445. static inline int fgetc_interactive(struct in_str *i)
  2446. {
  2447. int ch;
  2448. do ch = fgetc(i->file); while (ch == '\0');
  2449. return ch;
  2450. }
  2451. #endif /* INTERACTIVE */
  2452. static int i_getch(struct in_str *i)
  2453. {
  2454. int ch;
  2455. if (!i->file) {
  2456. /* string-based in_str */
  2457. ch = (unsigned char)*i->p;
  2458. if (ch != '\0') {
  2459. i->p++;
  2460. i->last_char = ch;
  2461. return ch;
  2462. }
  2463. return EOF;
  2464. }
  2465. /* FILE-based in_str */
  2466. #if ENABLE_FEATURE_EDITING
  2467. /* This can be stdin, check line editing char[] buffer */
  2468. if (i->p && *i->p != '\0') {
  2469. ch = (unsigned char)*i->p++;
  2470. goto out;
  2471. }
  2472. #endif
  2473. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2474. ch = i->peek_buf[0];
  2475. if (ch != 0) {
  2476. int ch2 = i->peek_buf[1];
  2477. i->peek_buf[0] = ch2;
  2478. if (ch2 == 0) /* very likely, avoid redundant write */
  2479. goto out;
  2480. i->peek_buf[1] = 0;
  2481. goto out;
  2482. }
  2483. ch = fgetc_interactive(i);
  2484. out:
  2485. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2486. i->last_char = ch;
  2487. #if ENABLE_HUSH_LINENO_VAR
  2488. if (ch == '\n') {
  2489. G.lineno++;
  2490. debug_printf_parse("G.lineno++ = %u\n", G.lineno);
  2491. }
  2492. #endif
  2493. return ch;
  2494. }
  2495. static int i_peek(struct in_str *i)
  2496. {
  2497. int ch;
  2498. if (!i->file) {
  2499. /* string-based in_str */
  2500. /* Doesn't report EOF on NUL. None of the callers care. */
  2501. return (unsigned char)*i->p;
  2502. }
  2503. /* FILE-based in_str */
  2504. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2505. /* This can be stdin, check line editing char[] buffer */
  2506. if (i->p && *i->p != '\0')
  2507. return (unsigned char)*i->p;
  2508. #endif
  2509. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2510. ch = i->peek_buf[0];
  2511. if (ch != 0)
  2512. return ch;
  2513. /* Need to get a new char */
  2514. ch = fgetc_interactive(i);
  2515. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2516. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2517. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2518. if (i->p) {
  2519. i->p -= 1;
  2520. return ch;
  2521. }
  2522. #endif
  2523. i->peek_buf[0] = ch;
  2524. /*i->peek_buf[1] = 0; - already is */
  2525. return ch;
  2526. }
  2527. /* Only ever called if i_peek() was called, and did not return EOF.
  2528. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2529. * not end-of-line. Therefore we never need to read a new editing line here.
  2530. */
  2531. static int i_peek2(struct in_str *i)
  2532. {
  2533. int ch;
  2534. /* There are two cases when i->p[] buffer exists.
  2535. * (1) it's a string in_str.
  2536. * (2) It's a file, and we have a saved line editing buffer.
  2537. * In both cases, we know that i->p[0] exists and not NUL, and
  2538. * the peek2 result is in i->p[1].
  2539. */
  2540. if (i->p)
  2541. return (unsigned char)i->p[1];
  2542. /* Now we know it is a file-based in_str. */
  2543. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2544. /* Is there 2nd char? */
  2545. ch = i->peek_buf[1];
  2546. if (ch == 0) {
  2547. /* We did not read it yet, get it now */
  2548. do ch = fgetc(i->file); while (ch == '\0');
  2549. i->peek_buf[1] = ch;
  2550. }
  2551. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2552. return ch;
  2553. }
  2554. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2555. {
  2556. for (;;) {
  2557. int ch, ch2;
  2558. ch = i_getch(input);
  2559. if (ch != '\\')
  2560. return ch;
  2561. ch2 = i_peek(input);
  2562. if (ch2 != '\n')
  2563. return ch;
  2564. /* backslash+newline, skip it */
  2565. i_getch(input);
  2566. }
  2567. }
  2568. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2569. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2570. */
  2571. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2572. {
  2573. for (;;) {
  2574. int ch, ch2;
  2575. ch = i_peek(input);
  2576. if (ch != '\\')
  2577. return ch;
  2578. ch2 = i_peek2(input);
  2579. if (ch2 != '\n')
  2580. return ch;
  2581. /* backslash+newline, skip it */
  2582. i_getch(input);
  2583. i_getch(input);
  2584. }
  2585. }
  2586. static void setup_file_in_str(struct in_str *i, FILE *f)
  2587. {
  2588. memset(i, 0, sizeof(*i));
  2589. i->file = f;
  2590. /* i->p = NULL; */
  2591. }
  2592. static void setup_string_in_str(struct in_str *i, const char *s)
  2593. {
  2594. memset(i, 0, sizeof(*i));
  2595. /*i->file = NULL */;
  2596. i->p = s;
  2597. }
  2598. /*
  2599. * o_string support
  2600. */
  2601. #define B_CHUNK (32 * sizeof(char*))
  2602. static void o_reset_to_empty_unquoted(o_string *o)
  2603. {
  2604. o->length = 0;
  2605. o->has_quoted_part = 0;
  2606. if (o->data)
  2607. o->data[0] = '\0';
  2608. }
  2609. static void o_free(o_string *o)
  2610. {
  2611. free(o->data);
  2612. memset(o, 0, sizeof(*o));
  2613. }
  2614. static ALWAYS_INLINE void o_free_unsafe(o_string *o)
  2615. {
  2616. free(o->data);
  2617. }
  2618. static void o_grow_by(o_string *o, int len)
  2619. {
  2620. if (o->length + len > o->maxlen) {
  2621. o->maxlen += (2 * len) | (B_CHUNK-1);
  2622. o->data = xrealloc(o->data, 1 + o->maxlen);
  2623. }
  2624. }
  2625. static void o_addchr(o_string *o, int ch)
  2626. {
  2627. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2628. if (o->length < o->maxlen) {
  2629. /* likely. avoid o_grow_by() call */
  2630. add:
  2631. o->data[o->length] = ch;
  2632. o->length++;
  2633. o->data[o->length] = '\0';
  2634. return;
  2635. }
  2636. o_grow_by(o, 1);
  2637. goto add;
  2638. }
  2639. #if 0
  2640. /* Valid only if we know o_string is not empty */
  2641. static void o_delchr(o_string *o)
  2642. {
  2643. o->length--;
  2644. o->data[o->length] = '\0';
  2645. }
  2646. #endif
  2647. static void o_addblock(o_string *o, const char *str, int len)
  2648. {
  2649. o_grow_by(o, len);
  2650. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2651. o->length += len;
  2652. }
  2653. static void o_addstr(o_string *o, const char *str)
  2654. {
  2655. o_addblock(o, str, strlen(str));
  2656. }
  2657. #if !BB_MMU
  2658. static void nommu_addchr(o_string *o, int ch)
  2659. {
  2660. if (o)
  2661. o_addchr(o, ch);
  2662. }
  2663. #else
  2664. # define nommu_addchr(o, str) ((void)0)
  2665. #endif
  2666. static void o_addstr_with_NUL(o_string *o, const char *str)
  2667. {
  2668. o_addblock(o, str, strlen(str) + 1);
  2669. }
  2670. /*
  2671. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2672. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2673. * Apparently, on unquoted $v bash still does globbing
  2674. * ("v='*.txt'; echo $v" prints all .txt files),
  2675. * but NOT brace expansion! Thus, there should be TWO independent
  2676. * quoting mechanisms on $v expansion side: one protects
  2677. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2678. * We have only second one.
  2679. */
  2680. #if ENABLE_HUSH_BRACE_EXPANSION
  2681. # define MAYBE_BRACES "{}"
  2682. #else
  2683. # define MAYBE_BRACES ""
  2684. #endif
  2685. /* My analysis of quoting semantics tells me that state information
  2686. * is associated with a destination, not a source.
  2687. */
  2688. static void o_addqchr(o_string *o, int ch)
  2689. {
  2690. int sz = 1;
  2691. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2692. if (found)
  2693. sz++;
  2694. o_grow_by(o, sz);
  2695. if (found) {
  2696. o->data[o->length] = '\\';
  2697. o->length++;
  2698. }
  2699. o->data[o->length] = ch;
  2700. o->length++;
  2701. o->data[o->length] = '\0';
  2702. }
  2703. static void o_addQchr(o_string *o, int ch)
  2704. {
  2705. int sz = 1;
  2706. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2707. && strchr("*?[\\" MAYBE_BRACES, ch)
  2708. ) {
  2709. sz++;
  2710. o->data[o->length] = '\\';
  2711. o->length++;
  2712. }
  2713. o_grow_by(o, sz);
  2714. o->data[o->length] = ch;
  2715. o->length++;
  2716. o->data[o->length] = '\0';
  2717. }
  2718. static void o_addqblock(o_string *o, const char *str, int len)
  2719. {
  2720. while (len) {
  2721. char ch;
  2722. int sz;
  2723. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2724. if (ordinary_cnt > len) /* paranoia */
  2725. ordinary_cnt = len;
  2726. o_addblock(o, str, ordinary_cnt);
  2727. if (ordinary_cnt == len)
  2728. return; /* NUL is already added by o_addblock */
  2729. str += ordinary_cnt;
  2730. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2731. ch = *str++;
  2732. sz = 1;
  2733. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2734. sz++;
  2735. o->data[o->length] = '\\';
  2736. o->length++;
  2737. }
  2738. o_grow_by(o, sz);
  2739. o->data[o->length] = ch;
  2740. o->length++;
  2741. }
  2742. o->data[o->length] = '\0';
  2743. }
  2744. static void o_addQblock(o_string *o, const char *str, int len)
  2745. {
  2746. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2747. o_addblock(o, str, len);
  2748. return;
  2749. }
  2750. o_addqblock(o, str, len);
  2751. }
  2752. static void o_addQstr(o_string *o, const char *str)
  2753. {
  2754. o_addQblock(o, str, strlen(str));
  2755. }
  2756. /* A special kind of o_string for $VAR and `cmd` expansion.
  2757. * It contains char* list[] at the beginning, which is grown in 16 element
  2758. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2759. * list[i] contains an INDEX (int!) into this string data.
  2760. * It means that if list[] needs to grow, data needs to be moved higher up
  2761. * but list[i]'s need not be modified.
  2762. * NB: remembering how many list[i]'s you have there is crucial.
  2763. * o_finalize_list() operation post-processes this structure - calculates
  2764. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2765. */
  2766. #if DEBUG_EXPAND || DEBUG_GLOB
  2767. static void debug_print_list(const char *prefix, o_string *o, int n)
  2768. {
  2769. char **list = (char**)o->data;
  2770. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2771. int i = 0;
  2772. indent();
  2773. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2774. prefix, list, n, string_start, o->length, o->maxlen,
  2775. !!(o->o_expflags & EXP_FLAG_GLOB),
  2776. o->has_quoted_part,
  2777. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2778. while (i < n) {
  2779. indent();
  2780. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2781. o->data + (int)(uintptr_t)list[i] + string_start,
  2782. o->data + (int)(uintptr_t)list[i] + string_start);
  2783. i++;
  2784. }
  2785. if (n) {
  2786. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2787. indent();
  2788. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2789. }
  2790. }
  2791. #else
  2792. # define debug_print_list(prefix, o, n) ((void)0)
  2793. #endif
  2794. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2795. * in list[n] so that it points past last stored byte so far.
  2796. * It returns n+1. */
  2797. static int o_save_ptr_helper(o_string *o, int n)
  2798. {
  2799. char **list = (char**)o->data;
  2800. int string_start;
  2801. int string_len;
  2802. if (!o->has_empty_slot) {
  2803. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2804. string_len = o->length - string_start;
  2805. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2806. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2807. /* list[n] points to string_start, make space for 16 more pointers */
  2808. o->maxlen += 0x10 * sizeof(list[0]);
  2809. o->data = xrealloc(o->data, o->maxlen + 1);
  2810. list = (char**)o->data;
  2811. memmove(list + n + 0x10, list + n, string_len);
  2812. o->length += 0x10 * sizeof(list[0]);
  2813. } else {
  2814. debug_printf_list("list[%d]=%d string_start=%d\n",
  2815. n, string_len, string_start);
  2816. }
  2817. } else {
  2818. /* We have empty slot at list[n], reuse without growth */
  2819. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2820. string_len = o->length - string_start;
  2821. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2822. n, string_len, string_start);
  2823. o->has_empty_slot = 0;
  2824. }
  2825. o->has_quoted_part = 0;
  2826. list[n] = (char*)(uintptr_t)string_len;
  2827. return n + 1;
  2828. }
  2829. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2830. static int o_get_last_ptr(o_string *o, int n)
  2831. {
  2832. char **list = (char**)o->data;
  2833. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2834. return ((int)(uintptr_t)list[n-1]) + string_start;
  2835. }
  2836. #if ENABLE_HUSH_BRACE_EXPANSION
  2837. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2838. * first, it processes even {a} (no commas), second,
  2839. * I didn't manage to make it return strings when they don't match
  2840. * existing files. Need to re-implement it.
  2841. */
  2842. /* Helper */
  2843. static int glob_needed(const char *s)
  2844. {
  2845. while (*s) {
  2846. if (*s == '\\') {
  2847. if (!s[1])
  2848. return 0;
  2849. s += 2;
  2850. continue;
  2851. }
  2852. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2853. return 1;
  2854. s++;
  2855. }
  2856. return 0;
  2857. }
  2858. /* Return pointer to next closing brace or to comma */
  2859. static const char *next_brace_sub(const char *cp)
  2860. {
  2861. unsigned depth = 0;
  2862. cp++;
  2863. while (*cp != '\0') {
  2864. if (*cp == '\\') {
  2865. if (*++cp == '\0')
  2866. break;
  2867. cp++;
  2868. continue;
  2869. }
  2870. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  2871. break;
  2872. if (*cp++ == '{')
  2873. depth++;
  2874. }
  2875. return *cp != '\0' ? cp : NULL;
  2876. }
  2877. /* Recursive brace globber. Note: may garble pattern[]. */
  2878. static int glob_brace(char *pattern, o_string *o, int n)
  2879. {
  2880. char *new_pattern_buf;
  2881. const char *begin;
  2882. const char *next;
  2883. const char *rest;
  2884. const char *p;
  2885. size_t rest_len;
  2886. debug_printf_glob("glob_brace('%s')\n", pattern);
  2887. begin = pattern;
  2888. while (1) {
  2889. if (*begin == '\0')
  2890. goto simple_glob;
  2891. if (*begin == '{') {
  2892. /* Find the first sub-pattern and at the same time
  2893. * find the rest after the closing brace */
  2894. next = next_brace_sub(begin);
  2895. if (next == NULL) {
  2896. /* An illegal expression */
  2897. goto simple_glob;
  2898. }
  2899. if (*next == '}') {
  2900. /* "{abc}" with no commas - illegal
  2901. * brace expr, disregard and skip it */
  2902. begin = next + 1;
  2903. continue;
  2904. }
  2905. break;
  2906. }
  2907. if (*begin == '\\' && begin[1] != '\0')
  2908. begin++;
  2909. begin++;
  2910. }
  2911. debug_printf_glob("begin:%s\n", begin);
  2912. debug_printf_glob("next:%s\n", next);
  2913. /* Now find the end of the whole brace expression */
  2914. rest = next;
  2915. while (*rest != '}') {
  2916. rest = next_brace_sub(rest);
  2917. if (rest == NULL) {
  2918. /* An illegal expression */
  2919. goto simple_glob;
  2920. }
  2921. debug_printf_glob("rest:%s\n", rest);
  2922. }
  2923. rest_len = strlen(++rest) + 1;
  2924. /* We are sure the brace expression is well-formed */
  2925. /* Allocate working buffer large enough for our work */
  2926. new_pattern_buf = xmalloc(strlen(pattern));
  2927. /* We have a brace expression. BEGIN points to the opening {,
  2928. * NEXT points past the terminator of the first element, and REST
  2929. * points past the final }. We will accumulate result names from
  2930. * recursive runs for each brace alternative in the buffer using
  2931. * GLOB_APPEND. */
  2932. p = begin + 1;
  2933. while (1) {
  2934. /* Construct the new glob expression */
  2935. memcpy(
  2936. mempcpy(
  2937. mempcpy(new_pattern_buf,
  2938. /* We know the prefix for all sub-patterns */
  2939. pattern, begin - pattern),
  2940. p, next - p),
  2941. rest, rest_len);
  2942. /* Note: glob_brace() may garble new_pattern_buf[].
  2943. * That's why we re-copy prefix every time (1st memcpy above).
  2944. */
  2945. n = glob_brace(new_pattern_buf, o, n);
  2946. if (*next == '}') {
  2947. /* We saw the last entry */
  2948. break;
  2949. }
  2950. p = next + 1;
  2951. next = next_brace_sub(next);
  2952. }
  2953. free(new_pattern_buf);
  2954. return n;
  2955. simple_glob:
  2956. {
  2957. int gr;
  2958. glob_t globdata;
  2959. memset(&globdata, 0, sizeof(globdata));
  2960. gr = glob(pattern, 0, NULL, &globdata);
  2961. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  2962. if (gr != 0) {
  2963. if (gr == GLOB_NOMATCH) {
  2964. globfree(&globdata);
  2965. /* NB: garbles parameter */
  2966. unbackslash(pattern);
  2967. o_addstr_with_NUL(o, pattern);
  2968. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2969. return o_save_ptr_helper(o, n);
  2970. }
  2971. if (gr == GLOB_NOSPACE)
  2972. bb_die_memory_exhausted();
  2973. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  2974. * but we didn't specify it. Paranoia again. */
  2975. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  2976. }
  2977. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  2978. char **argv = globdata.gl_pathv;
  2979. while (1) {
  2980. o_addstr_with_NUL(o, *argv);
  2981. n = o_save_ptr_helper(o, n);
  2982. argv++;
  2983. if (!*argv)
  2984. break;
  2985. }
  2986. }
  2987. globfree(&globdata);
  2988. }
  2989. return n;
  2990. }
  2991. /* Performs globbing on last list[],
  2992. * saving each result as a new list[].
  2993. */
  2994. static int perform_glob(o_string *o, int n)
  2995. {
  2996. char *pattern, *copy;
  2997. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  2998. if (!o->data)
  2999. return o_save_ptr_helper(o, n);
  3000. pattern = o->data + o_get_last_ptr(o, n);
  3001. debug_printf_glob("glob pattern '%s'\n", pattern);
  3002. if (!glob_needed(pattern)) {
  3003. /* unbackslash last string in o in place, fix length */
  3004. o->length = unbackslash(pattern) - o->data;
  3005. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3006. return o_save_ptr_helper(o, n);
  3007. }
  3008. copy = xstrdup(pattern);
  3009. /* "forget" pattern in o */
  3010. o->length = pattern - o->data;
  3011. n = glob_brace(copy, o, n);
  3012. free(copy);
  3013. if (DEBUG_GLOB)
  3014. debug_print_list("perform_glob returning", o, n);
  3015. return n;
  3016. }
  3017. #else /* !HUSH_BRACE_EXPANSION */
  3018. /* Helper */
  3019. static int glob_needed(const char *s)
  3020. {
  3021. while (*s) {
  3022. if (*s == '\\') {
  3023. if (!s[1])
  3024. return 0;
  3025. s += 2;
  3026. continue;
  3027. }
  3028. if (*s == '*' || *s == '[' || *s == '?')
  3029. return 1;
  3030. s++;
  3031. }
  3032. return 0;
  3033. }
  3034. /* Performs globbing on last list[],
  3035. * saving each result as a new list[].
  3036. */
  3037. static int perform_glob(o_string *o, int n)
  3038. {
  3039. glob_t globdata;
  3040. int gr;
  3041. char *pattern;
  3042. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3043. if (!o->data)
  3044. return o_save_ptr_helper(o, n);
  3045. pattern = o->data + o_get_last_ptr(o, n);
  3046. debug_printf_glob("glob pattern '%s'\n", pattern);
  3047. if (!glob_needed(pattern)) {
  3048. literal:
  3049. /* unbackslash last string in o in place, fix length */
  3050. o->length = unbackslash(pattern) - o->data;
  3051. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3052. return o_save_ptr_helper(o, n);
  3053. }
  3054. memset(&globdata, 0, sizeof(globdata));
  3055. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3056. * If we glob "*.\*" and don't find anything, we need
  3057. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3058. * will return "*.\*"!
  3059. */
  3060. gr = glob(pattern, 0, NULL, &globdata);
  3061. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3062. if (gr != 0) {
  3063. if (gr == GLOB_NOMATCH) {
  3064. globfree(&globdata);
  3065. goto literal;
  3066. }
  3067. if (gr == GLOB_NOSPACE)
  3068. bb_die_memory_exhausted();
  3069. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3070. * but we didn't specify it. Paranoia again. */
  3071. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3072. }
  3073. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3074. char **argv = globdata.gl_pathv;
  3075. /* "forget" pattern in o */
  3076. o->length = pattern - o->data;
  3077. while (1) {
  3078. o_addstr_with_NUL(o, *argv);
  3079. n = o_save_ptr_helper(o, n);
  3080. argv++;
  3081. if (!*argv)
  3082. break;
  3083. }
  3084. }
  3085. globfree(&globdata);
  3086. if (DEBUG_GLOB)
  3087. debug_print_list("perform_glob returning", o, n);
  3088. return n;
  3089. }
  3090. #endif /* !HUSH_BRACE_EXPANSION */
  3091. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3092. * Otherwise, just finish current list[] and start new */
  3093. static int o_save_ptr(o_string *o, int n)
  3094. {
  3095. if (o->o_expflags & EXP_FLAG_GLOB) {
  3096. /* If o->has_empty_slot, list[n] was already globbed
  3097. * (if it was requested back then when it was filled)
  3098. * so don't do that again! */
  3099. if (!o->has_empty_slot)
  3100. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3101. }
  3102. return o_save_ptr_helper(o, n);
  3103. }
  3104. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3105. static char **o_finalize_list(o_string *o, int n)
  3106. {
  3107. char **list;
  3108. int string_start;
  3109. n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
  3110. if (DEBUG_EXPAND)
  3111. debug_print_list("finalized", o, n);
  3112. debug_printf_expand("finalized n:%d\n", n);
  3113. list = (char**)o->data;
  3114. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3115. list[--n] = NULL;
  3116. while (n) {
  3117. n--;
  3118. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3119. }
  3120. return list;
  3121. }
  3122. static void free_pipe_list(struct pipe *pi);
  3123. /* Returns pi->next - next pipe in the list */
  3124. static struct pipe *free_pipe(struct pipe *pi)
  3125. {
  3126. struct pipe *next;
  3127. int i;
  3128. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3129. for (i = 0; i < pi->num_cmds; i++) {
  3130. struct command *command;
  3131. struct redir_struct *r, *rnext;
  3132. command = &pi->cmds[i];
  3133. debug_printf_clean(" command %d:\n", i);
  3134. if (command->argv) {
  3135. if (DEBUG_CLEAN) {
  3136. int a;
  3137. char **p;
  3138. for (a = 0, p = command->argv; *p; a++, p++) {
  3139. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3140. }
  3141. }
  3142. free_strings(command->argv);
  3143. //command->argv = NULL;
  3144. }
  3145. /* not "else if": on syntax error, we may have both! */
  3146. if (command->group) {
  3147. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3148. command->cmd_type);
  3149. free_pipe_list(command->group);
  3150. debug_printf_clean(" end group\n");
  3151. //command->group = NULL;
  3152. }
  3153. /* else is crucial here.
  3154. * If group != NULL, child_func is meaningless */
  3155. #if ENABLE_HUSH_FUNCTIONS
  3156. else if (command->child_func) {
  3157. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3158. command->child_func->parent_cmd = NULL;
  3159. }
  3160. #endif
  3161. #if !BB_MMU
  3162. free(command->group_as_string);
  3163. //command->group_as_string = NULL;
  3164. #endif
  3165. for (r = command->redirects; r; r = rnext) {
  3166. debug_printf_clean(" redirect %d%s",
  3167. r->rd_fd, redir_table[r->rd_type].descrip);
  3168. /* guard against the case >$FOO, where foo is unset or blank */
  3169. if (r->rd_filename) {
  3170. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3171. free(r->rd_filename);
  3172. //r->rd_filename = NULL;
  3173. }
  3174. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3175. rnext = r->next;
  3176. free(r);
  3177. }
  3178. //command->redirects = NULL;
  3179. }
  3180. free(pi->cmds); /* children are an array, they get freed all at once */
  3181. //pi->cmds = NULL;
  3182. #if ENABLE_HUSH_JOB
  3183. free(pi->cmdtext);
  3184. //pi->cmdtext = NULL;
  3185. #endif
  3186. next = pi->next;
  3187. free(pi);
  3188. return next;
  3189. }
  3190. static void free_pipe_list(struct pipe *pi)
  3191. {
  3192. while (pi) {
  3193. #if HAS_KEYWORDS
  3194. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3195. #endif
  3196. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3197. pi = free_pipe(pi);
  3198. }
  3199. }
  3200. /*** Parsing routines ***/
  3201. #ifndef debug_print_tree
  3202. static void debug_print_tree(struct pipe *pi, int lvl)
  3203. {
  3204. static const char *const PIPE[] = {
  3205. [PIPE_SEQ] = "SEQ",
  3206. [PIPE_AND] = "AND",
  3207. [PIPE_OR ] = "OR" ,
  3208. [PIPE_BG ] = "BG" ,
  3209. };
  3210. static const char *RES[] = {
  3211. [RES_NONE ] = "NONE" ,
  3212. # if ENABLE_HUSH_IF
  3213. [RES_IF ] = "IF" ,
  3214. [RES_THEN ] = "THEN" ,
  3215. [RES_ELIF ] = "ELIF" ,
  3216. [RES_ELSE ] = "ELSE" ,
  3217. [RES_FI ] = "FI" ,
  3218. # endif
  3219. # if ENABLE_HUSH_LOOPS
  3220. [RES_FOR ] = "FOR" ,
  3221. [RES_WHILE] = "WHILE",
  3222. [RES_UNTIL] = "UNTIL",
  3223. [RES_DO ] = "DO" ,
  3224. [RES_DONE ] = "DONE" ,
  3225. # endif
  3226. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3227. [RES_IN ] = "IN" ,
  3228. # endif
  3229. # if ENABLE_HUSH_CASE
  3230. [RES_CASE ] = "CASE" ,
  3231. [RES_CASE_IN ] = "CASE_IN" ,
  3232. [RES_MATCH] = "MATCH",
  3233. [RES_CASE_BODY] = "CASE_BODY",
  3234. [RES_ESAC ] = "ESAC" ,
  3235. # endif
  3236. [RES_XXXX ] = "XXXX" ,
  3237. [RES_SNTX ] = "SNTX" ,
  3238. };
  3239. static const char *const CMDTYPE[] = {
  3240. "{}",
  3241. "()",
  3242. "[noglob]",
  3243. # if ENABLE_HUSH_FUNCTIONS
  3244. "func()",
  3245. # endif
  3246. };
  3247. int pin, prn;
  3248. pin = 0;
  3249. while (pi) {
  3250. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3251. lvl*2, "",
  3252. pin,
  3253. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3254. RES[pi->res_word],
  3255. pi->followup, PIPE[pi->followup]
  3256. );
  3257. prn = 0;
  3258. while (prn < pi->num_cmds) {
  3259. struct command *command = &pi->cmds[prn];
  3260. char **argv = command->argv;
  3261. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3262. lvl*2, "", prn,
  3263. command->assignment_cnt);
  3264. #if ENABLE_HUSH_LINENO_VAR
  3265. fdprintf(2, " LINENO:%u", command->lineno);
  3266. #endif
  3267. if (command->group) {
  3268. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3269. CMDTYPE[command->cmd_type],
  3270. argv
  3271. # if !BB_MMU
  3272. , " group_as_string:", command->group_as_string
  3273. # else
  3274. , "", ""
  3275. # endif
  3276. );
  3277. debug_print_tree(command->group, lvl+1);
  3278. prn++;
  3279. continue;
  3280. }
  3281. if (argv) while (*argv) {
  3282. fdprintf(2, " '%s'", *argv);
  3283. argv++;
  3284. }
  3285. fdprintf(2, "\n");
  3286. prn++;
  3287. }
  3288. pi = pi->next;
  3289. pin++;
  3290. }
  3291. }
  3292. #endif /* debug_print_tree */
  3293. static struct pipe *new_pipe(void)
  3294. {
  3295. struct pipe *pi;
  3296. pi = xzalloc(sizeof(struct pipe));
  3297. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3298. return pi;
  3299. }
  3300. /* Command (member of a pipe) is complete, or we start a new pipe
  3301. * if ctx->command is NULL.
  3302. * No errors possible here.
  3303. */
  3304. static int done_command(struct parse_context *ctx)
  3305. {
  3306. /* The command is really already in the pipe structure, so
  3307. * advance the pipe counter and make a new, null command. */
  3308. struct pipe *pi = ctx->pipe;
  3309. struct command *command = ctx->command;
  3310. #if 0 /* Instead we emit error message at run time */
  3311. if (ctx->pending_redirect) {
  3312. /* For example, "cmd >" (no filename to redirect to) */
  3313. syntax_error("invalid redirect");
  3314. ctx->pending_redirect = NULL;
  3315. }
  3316. #endif
  3317. if (command) {
  3318. if (IS_NULL_CMD(command)) {
  3319. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3320. goto clear_and_ret;
  3321. }
  3322. pi->num_cmds++;
  3323. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3324. //debug_print_tree(ctx->list_head, 20);
  3325. } else {
  3326. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3327. }
  3328. /* Only real trickiness here is that the uncommitted
  3329. * command structure is not counted in pi->num_cmds. */
  3330. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3331. ctx->command = command = &pi->cmds[pi->num_cmds];
  3332. clear_and_ret:
  3333. memset(command, 0, sizeof(*command));
  3334. #if ENABLE_HUSH_LINENO_VAR
  3335. command->lineno = G.lineno;
  3336. debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
  3337. #endif
  3338. return pi->num_cmds; /* used only for 0/nonzero check */
  3339. }
  3340. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3341. {
  3342. int not_null;
  3343. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3344. /* Close previous command */
  3345. not_null = done_command(ctx);
  3346. #if HAS_KEYWORDS
  3347. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3348. ctx->ctx_inverted = 0;
  3349. ctx->pipe->res_word = ctx->ctx_res_w;
  3350. #endif
  3351. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3352. /* Necessary since && and || have precedence over &:
  3353. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3354. * in a backgrounded subshell.
  3355. */
  3356. struct pipe *pi;
  3357. struct command *command;
  3358. /* Is this actually this construct, all pipes end with && or ||? */
  3359. pi = ctx->list_head;
  3360. while (pi != ctx->pipe) {
  3361. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3362. goto no_conv;
  3363. pi = pi->next;
  3364. }
  3365. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3366. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3367. pi = xzalloc(sizeof(*pi));
  3368. pi->followup = PIPE_BG;
  3369. pi->num_cmds = 1;
  3370. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3371. command = &pi->cmds[0];
  3372. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3373. command->cmd_type = CMD_NORMAL;
  3374. command->group = ctx->list_head;
  3375. #if !BB_MMU
  3376. command->group_as_string = xstrndup(
  3377. ctx->as_string.data,
  3378. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3379. );
  3380. #endif
  3381. /* Replace all pipes in ctx with one newly created */
  3382. ctx->list_head = ctx->pipe = pi;
  3383. } else {
  3384. no_conv:
  3385. ctx->pipe->followup = type;
  3386. }
  3387. /* Without this check, even just <enter> on command line generates
  3388. * tree of three NOPs (!). Which is harmless but annoying.
  3389. * IOW: it is safe to do it unconditionally. */
  3390. if (not_null
  3391. #if ENABLE_HUSH_IF
  3392. || ctx->ctx_res_w == RES_FI
  3393. #endif
  3394. #if ENABLE_HUSH_LOOPS
  3395. || ctx->ctx_res_w == RES_DONE
  3396. || ctx->ctx_res_w == RES_FOR
  3397. || ctx->ctx_res_w == RES_IN
  3398. #endif
  3399. #if ENABLE_HUSH_CASE
  3400. || ctx->ctx_res_w == RES_ESAC
  3401. #endif
  3402. ) {
  3403. struct pipe *new_p;
  3404. debug_printf_parse("done_pipe: adding new pipe: "
  3405. "not_null:%d ctx->ctx_res_w:%d\n",
  3406. not_null, ctx->ctx_res_w);
  3407. new_p = new_pipe();
  3408. ctx->pipe->next = new_p;
  3409. ctx->pipe = new_p;
  3410. /* RES_THEN, RES_DO etc are "sticky" -
  3411. * they remain set for pipes inside if/while.
  3412. * This is used to control execution.
  3413. * RES_FOR and RES_IN are NOT sticky (needed to support
  3414. * cases where variable or value happens to match a keyword):
  3415. */
  3416. #if ENABLE_HUSH_LOOPS
  3417. if (ctx->ctx_res_w == RES_FOR
  3418. || ctx->ctx_res_w == RES_IN)
  3419. ctx->ctx_res_w = RES_NONE;
  3420. #endif
  3421. #if ENABLE_HUSH_CASE
  3422. if (ctx->ctx_res_w == RES_MATCH)
  3423. ctx->ctx_res_w = RES_CASE_BODY;
  3424. if (ctx->ctx_res_w == RES_CASE)
  3425. ctx->ctx_res_w = RES_CASE_IN;
  3426. #endif
  3427. ctx->command = NULL; /* trick done_command below */
  3428. /* Create the memory for command, roughly:
  3429. * ctx->pipe->cmds = new struct command;
  3430. * ctx->command = &ctx->pipe->cmds[0];
  3431. */
  3432. done_command(ctx);
  3433. //debug_print_tree(ctx->list_head, 10);
  3434. }
  3435. debug_printf_parse("done_pipe return\n");
  3436. }
  3437. static void initialize_context(struct parse_context *ctx)
  3438. {
  3439. memset(ctx, 0, sizeof(*ctx));
  3440. if (MAYBE_ASSIGNMENT != 0)
  3441. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3442. ctx->pipe = ctx->list_head = new_pipe();
  3443. /* Create the memory for command, roughly:
  3444. * ctx->pipe->cmds = new struct command;
  3445. * ctx->command = &ctx->pipe->cmds[0];
  3446. */
  3447. done_command(ctx);
  3448. }
  3449. /* If a reserved word is found and processed, parse context is modified
  3450. * and 1 is returned.
  3451. */
  3452. #if HAS_KEYWORDS
  3453. struct reserved_combo {
  3454. char literal[6];
  3455. unsigned char res;
  3456. unsigned char assignment_flag;
  3457. int flag;
  3458. };
  3459. enum {
  3460. FLAG_END = (1 << RES_NONE ),
  3461. # if ENABLE_HUSH_IF
  3462. FLAG_IF = (1 << RES_IF ),
  3463. FLAG_THEN = (1 << RES_THEN ),
  3464. FLAG_ELIF = (1 << RES_ELIF ),
  3465. FLAG_ELSE = (1 << RES_ELSE ),
  3466. FLAG_FI = (1 << RES_FI ),
  3467. # endif
  3468. # if ENABLE_HUSH_LOOPS
  3469. FLAG_FOR = (1 << RES_FOR ),
  3470. FLAG_WHILE = (1 << RES_WHILE),
  3471. FLAG_UNTIL = (1 << RES_UNTIL),
  3472. FLAG_DO = (1 << RES_DO ),
  3473. FLAG_DONE = (1 << RES_DONE ),
  3474. FLAG_IN = (1 << RES_IN ),
  3475. # endif
  3476. # if ENABLE_HUSH_CASE
  3477. FLAG_MATCH = (1 << RES_MATCH),
  3478. FLAG_ESAC = (1 << RES_ESAC ),
  3479. # endif
  3480. FLAG_START = (1 << RES_XXXX ),
  3481. };
  3482. static const struct reserved_combo* match_reserved_word(o_string *word)
  3483. {
  3484. /* Mostly a list of accepted follow-up reserved words.
  3485. * FLAG_END means we are done with the sequence, and are ready
  3486. * to turn the compound list into a command.
  3487. * FLAG_START means the word must start a new compound list.
  3488. */
  3489. static const struct reserved_combo reserved_list[] = {
  3490. # if ENABLE_HUSH_IF
  3491. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3492. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3493. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3494. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3495. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3496. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3497. # endif
  3498. # if ENABLE_HUSH_LOOPS
  3499. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3500. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3501. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3502. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3503. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3504. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3505. # endif
  3506. # if ENABLE_HUSH_CASE
  3507. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3508. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3509. # endif
  3510. };
  3511. const struct reserved_combo *r;
  3512. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3513. if (strcmp(word->data, r->literal) == 0)
  3514. return r;
  3515. }
  3516. return NULL;
  3517. }
  3518. /* Return NULL: not a keyword, else: keyword
  3519. */
  3520. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3521. {
  3522. # if ENABLE_HUSH_CASE
  3523. static const struct reserved_combo reserved_match = {
  3524. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3525. };
  3526. # endif
  3527. const struct reserved_combo *r;
  3528. if (ctx->word.has_quoted_part)
  3529. return 0;
  3530. r = match_reserved_word(&ctx->word);
  3531. if (!r)
  3532. return r; /* NULL */
  3533. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3534. # if ENABLE_HUSH_CASE
  3535. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3536. /* "case word IN ..." - IN part starts first MATCH part */
  3537. r = &reserved_match;
  3538. } else
  3539. # endif
  3540. if (r->flag == 0) { /* '!' */
  3541. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3542. syntax_error("! ! command");
  3543. ctx->ctx_res_w = RES_SNTX;
  3544. }
  3545. ctx->ctx_inverted = 1;
  3546. return r;
  3547. }
  3548. if (r->flag & FLAG_START) {
  3549. struct parse_context *old;
  3550. old = xmemdup(ctx, sizeof(*ctx));
  3551. debug_printf_parse("push stack %p\n", old);
  3552. initialize_context(ctx);
  3553. ctx->stack = old;
  3554. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3555. syntax_error_at(ctx->word.data);
  3556. ctx->ctx_res_w = RES_SNTX;
  3557. return r;
  3558. } else {
  3559. /* "{...} fi" is ok. "{...} if" is not
  3560. * Example:
  3561. * if { echo foo; } then { echo bar; } fi */
  3562. if (ctx->command->group)
  3563. done_pipe(ctx, PIPE_SEQ);
  3564. }
  3565. ctx->ctx_res_w = r->res;
  3566. ctx->old_flag = r->flag;
  3567. ctx->is_assignment = r->assignment_flag;
  3568. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3569. if (ctx->old_flag & FLAG_END) {
  3570. struct parse_context *old;
  3571. done_pipe(ctx, PIPE_SEQ);
  3572. debug_printf_parse("pop stack %p\n", ctx->stack);
  3573. old = ctx->stack;
  3574. old->command->group = ctx->list_head;
  3575. old->command->cmd_type = CMD_NORMAL;
  3576. # if !BB_MMU
  3577. /* At this point, the compound command's string is in
  3578. * ctx->as_string... except for the leading keyword!
  3579. * Consider this example: "echo a | if true; then echo a; fi"
  3580. * ctx->as_string will contain "true; then echo a; fi",
  3581. * with "if " remaining in old->as_string!
  3582. */
  3583. {
  3584. char *str;
  3585. int len = old->as_string.length;
  3586. /* Concatenate halves */
  3587. o_addstr(&old->as_string, ctx->as_string.data);
  3588. o_free_unsafe(&ctx->as_string);
  3589. /* Find where leading keyword starts in first half */
  3590. str = old->as_string.data + len;
  3591. if (str > old->as_string.data)
  3592. str--; /* skip whitespace after keyword */
  3593. while (str > old->as_string.data && isalpha(str[-1]))
  3594. str--;
  3595. /* Ugh, we're done with this horrid hack */
  3596. old->command->group_as_string = xstrdup(str);
  3597. debug_printf_parse("pop, remembering as:'%s'\n",
  3598. old->command->group_as_string);
  3599. }
  3600. # endif
  3601. *ctx = *old; /* physical copy */
  3602. free(old);
  3603. }
  3604. return r;
  3605. }
  3606. #endif /* HAS_KEYWORDS */
  3607. /* Word is complete, look at it and update parsing context.
  3608. * Normal return is 0. Syntax errors return 1.
  3609. * Note: on return, word is reset, but not o_free'd!
  3610. */
  3611. static int done_word(struct parse_context *ctx)
  3612. {
  3613. struct command *command = ctx->command;
  3614. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3615. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3616. debug_printf_parse("done_word return 0: true null, ignored\n");
  3617. return 0;
  3618. }
  3619. if (ctx->pending_redirect) {
  3620. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3621. * only if run as "bash", not "sh" */
  3622. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3623. * "2.7 Redirection
  3624. * If the redirection operator is "<<" or "<<-", the word
  3625. * that follows the redirection operator shall be
  3626. * subjected to quote removal; it is unspecified whether
  3627. * any of the other expansions occur. For the other
  3628. * redirection operators, the word that follows the
  3629. * redirection operator shall be subjected to tilde
  3630. * expansion, parameter expansion, command substitution,
  3631. * arithmetic expansion, and quote removal.
  3632. * Pathname expansion shall not be performed
  3633. * on the word by a non-interactive shell; an interactive
  3634. * shell may perform it, but shall do so only when
  3635. * the expansion would result in one word."
  3636. */
  3637. //bash does not do parameter/command substitution or arithmetic expansion
  3638. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3639. // as written:
  3640. // <<EOF$t
  3641. // <<EOF$((1))
  3642. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3643. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3644. /* Cater for >\file case:
  3645. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3646. * Same with heredocs:
  3647. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3648. */
  3649. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3650. unbackslash(ctx->pending_redirect->rd_filename);
  3651. /* Is it <<"HEREDOC"? */
  3652. if (ctx->word.has_quoted_part) {
  3653. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3654. }
  3655. }
  3656. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3657. ctx->pending_redirect = NULL;
  3658. } else {
  3659. #if HAS_KEYWORDS
  3660. # if ENABLE_HUSH_CASE
  3661. if (ctx->ctx_dsemicolon
  3662. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3663. ) {
  3664. /* already done when ctx_dsemicolon was set to 1: */
  3665. /* ctx->ctx_res_w = RES_MATCH; */
  3666. ctx->ctx_dsemicolon = 0;
  3667. } else
  3668. # endif
  3669. if (!command->argv /* if it's the first word... */
  3670. # if ENABLE_HUSH_LOOPS
  3671. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3672. && ctx->ctx_res_w != RES_IN
  3673. # endif
  3674. # if ENABLE_HUSH_CASE
  3675. && ctx->ctx_res_w != RES_CASE
  3676. # endif
  3677. ) {
  3678. const struct reserved_combo *reserved;
  3679. reserved = reserved_word(ctx);
  3680. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3681. if (reserved) {
  3682. # if ENABLE_HUSH_LINENO_VAR
  3683. /* Case:
  3684. * "while ...; do
  3685. * cmd ..."
  3686. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3687. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3688. */
  3689. if (0
  3690. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3691. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3692. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3693. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3694. ) {
  3695. done_pipe(ctx, PIPE_SEQ);
  3696. }
  3697. # endif
  3698. o_reset_to_empty_unquoted(&ctx->word);
  3699. debug_printf_parse("done_word return %d\n",
  3700. (ctx->ctx_res_w == RES_SNTX));
  3701. return (ctx->ctx_res_w == RES_SNTX);
  3702. }
  3703. # if defined(CMD_SINGLEWORD_NOGLOB)
  3704. if (0
  3705. # if BASH_TEST2
  3706. || strcmp(ctx->word.data, "[[") == 0
  3707. # endif
  3708. /* In bash, local/export/readonly are special, args
  3709. * are assignments and therefore expansion of them
  3710. * should be "one-word" expansion:
  3711. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3712. * compare with:
  3713. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3714. * ls: cannot access i=a: No such file or directory
  3715. * ls: cannot access b: No such file or directory
  3716. * Note: bash 3.2.33(1) does this only if export word
  3717. * itself is not quoted:
  3718. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3719. * aaa bbb
  3720. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3721. * aaa
  3722. */
  3723. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3724. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3725. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3726. ) {
  3727. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3728. }
  3729. /* fall through */
  3730. # endif
  3731. }
  3732. #endif /* HAS_KEYWORDS */
  3733. if (command->group) {
  3734. /* "{ echo foo; } echo bar" - bad */
  3735. syntax_error_at(ctx->word.data);
  3736. debug_printf_parse("done_word return 1: syntax error, "
  3737. "groups and arglists don't mix\n");
  3738. return 1;
  3739. }
  3740. /* If this word wasn't an assignment, next ones definitely
  3741. * can't be assignments. Even if they look like ones. */
  3742. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3743. && ctx->is_assignment != WORD_IS_KEYWORD
  3744. ) {
  3745. ctx->is_assignment = NOT_ASSIGNMENT;
  3746. } else {
  3747. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3748. command->assignment_cnt++;
  3749. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3750. }
  3751. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3752. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3753. }
  3754. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3755. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3756. debug_print_strings("word appended to argv", command->argv);
  3757. }
  3758. #if ENABLE_HUSH_LOOPS
  3759. if (ctx->ctx_res_w == RES_FOR) {
  3760. if (ctx->word.has_quoted_part
  3761. || !is_well_formed_var_name(command->argv[0], '\0')
  3762. ) {
  3763. /* bash says just "not a valid identifier" */
  3764. syntax_error("not a valid identifier in for");
  3765. return 1;
  3766. }
  3767. /* Force FOR to have just one word (variable name) */
  3768. /* NB: basically, this makes hush see "for v in ..."
  3769. * syntax as if it is "for v; in ...". FOR and IN become
  3770. * two pipe structs in parse tree. */
  3771. done_pipe(ctx, PIPE_SEQ);
  3772. }
  3773. #endif
  3774. #if ENABLE_HUSH_CASE
  3775. /* Force CASE to have just one word */
  3776. if (ctx->ctx_res_w == RES_CASE) {
  3777. done_pipe(ctx, PIPE_SEQ);
  3778. }
  3779. #endif
  3780. o_reset_to_empty_unquoted(&ctx->word);
  3781. debug_printf_parse("done_word return 0\n");
  3782. return 0;
  3783. }
  3784. /* Peek ahead in the input to find out if we have a "&n" construct,
  3785. * as in "2>&1", that represents duplicating a file descriptor.
  3786. * Return:
  3787. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3788. * REDIRFD_SYNTAX_ERR if syntax error,
  3789. * REDIRFD_TO_FILE if no & was seen,
  3790. * or the number found.
  3791. */
  3792. #if BB_MMU
  3793. #define parse_redir_right_fd(as_string, input) \
  3794. parse_redir_right_fd(input)
  3795. #endif
  3796. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3797. {
  3798. int ch, d, ok;
  3799. ch = i_peek(input);
  3800. if (ch != '&')
  3801. return REDIRFD_TO_FILE;
  3802. ch = i_getch(input); /* get the & */
  3803. nommu_addchr(as_string, ch);
  3804. ch = i_peek(input);
  3805. if (ch == '-') {
  3806. ch = i_getch(input);
  3807. nommu_addchr(as_string, ch);
  3808. return REDIRFD_CLOSE;
  3809. }
  3810. d = 0;
  3811. ok = 0;
  3812. while (ch != EOF && isdigit(ch)) {
  3813. d = d*10 + (ch-'0');
  3814. ok = 1;
  3815. ch = i_getch(input);
  3816. nommu_addchr(as_string, ch);
  3817. ch = i_peek(input);
  3818. }
  3819. if (ok) return d;
  3820. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3821. bb_error_msg("ambiguous redirect");
  3822. return REDIRFD_SYNTAX_ERR;
  3823. }
  3824. /* Return code is 0 normal, 1 if a syntax error is detected
  3825. */
  3826. static int parse_redirect(struct parse_context *ctx,
  3827. int fd,
  3828. redir_type style,
  3829. struct in_str *input)
  3830. {
  3831. struct command *command = ctx->command;
  3832. struct redir_struct *redir;
  3833. struct redir_struct **redirp;
  3834. int dup_num;
  3835. dup_num = REDIRFD_TO_FILE;
  3836. if (style != REDIRECT_HEREDOC) {
  3837. /* Check for a '>&1' type redirect */
  3838. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3839. if (dup_num == REDIRFD_SYNTAX_ERR)
  3840. return 1;
  3841. } else {
  3842. int ch = i_peek_and_eat_bkslash_nl(input);
  3843. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3844. if (dup_num) { /* <<-... */
  3845. ch = i_getch(input);
  3846. nommu_addchr(&ctx->as_string, ch);
  3847. ch = i_peek(input);
  3848. }
  3849. }
  3850. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3851. int ch = i_peek_and_eat_bkslash_nl(input);
  3852. if (ch == '|') {
  3853. /* >|FILE redirect ("clobbering" >).
  3854. * Since we do not support "set -o noclobber" yet,
  3855. * >| and > are the same for now. Just eat |.
  3856. */
  3857. ch = i_getch(input);
  3858. nommu_addchr(&ctx->as_string, ch);
  3859. }
  3860. }
  3861. /* Create a new redir_struct and append it to the linked list */
  3862. redirp = &command->redirects;
  3863. while ((redir = *redirp) != NULL) {
  3864. redirp = &(redir->next);
  3865. }
  3866. *redirp = redir = xzalloc(sizeof(*redir));
  3867. /* redir->next = NULL; */
  3868. /* redir->rd_filename = NULL; */
  3869. redir->rd_type = style;
  3870. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  3871. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  3872. redir_table[style].descrip);
  3873. redir->rd_dup = dup_num;
  3874. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  3875. /* Erik had a check here that the file descriptor in question
  3876. * is legit; I postpone that to "run time"
  3877. * A "-" representation of "close me" shows up as a -3 here */
  3878. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  3879. redir->rd_fd, redir->rd_dup);
  3880. } else {
  3881. #if 0 /* Instead we emit error message at run time */
  3882. if (ctx->pending_redirect) {
  3883. /* For example, "cmd > <file" */
  3884. syntax_error("invalid redirect");
  3885. }
  3886. #endif
  3887. /* Set ctx->pending_redirect, so we know what to do at the
  3888. * end of the next parsed word. */
  3889. ctx->pending_redirect = redir;
  3890. }
  3891. return 0;
  3892. }
  3893. /* If a redirect is immediately preceded by a number, that number is
  3894. * supposed to tell which file descriptor to redirect. This routine
  3895. * looks for such preceding numbers. In an ideal world this routine
  3896. * needs to handle all the following classes of redirects...
  3897. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  3898. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  3899. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  3900. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  3901. *
  3902. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  3903. * "2.7 Redirection
  3904. * ... If n is quoted, the number shall not be recognized as part of
  3905. * the redirection expression. For example:
  3906. * echo \2>a
  3907. * writes the character 2 into file a"
  3908. * We are getting it right by setting ->has_quoted_part on any \<char>
  3909. *
  3910. * A -1 return means no valid number was found,
  3911. * the caller should use the appropriate default for this redirection.
  3912. */
  3913. static int redirect_opt_num(o_string *o)
  3914. {
  3915. int num;
  3916. if (o->data == NULL)
  3917. return -1;
  3918. num = bb_strtou(o->data, NULL, 10);
  3919. if (errno || num < 0)
  3920. return -1;
  3921. o_reset_to_empty_unquoted(o);
  3922. return num;
  3923. }
  3924. #if BB_MMU
  3925. #define fetch_till_str(as_string, input, word, skip_tabs) \
  3926. fetch_till_str(input, word, skip_tabs)
  3927. #endif
  3928. static char *fetch_till_str(o_string *as_string,
  3929. struct in_str *input,
  3930. const char *word,
  3931. int heredoc_flags)
  3932. {
  3933. o_string heredoc = NULL_O_STRING;
  3934. unsigned past_EOL;
  3935. int prev = 0; /* not \ */
  3936. int ch;
  3937. goto jump_in;
  3938. while (1) {
  3939. ch = i_getch(input);
  3940. if (ch != EOF)
  3941. nommu_addchr(as_string, ch);
  3942. if (ch == '\n' || ch == EOF) {
  3943. check_heredoc_end:
  3944. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  3945. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  3946. heredoc.data[past_EOL] = '\0';
  3947. debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
  3948. return heredoc.data;
  3949. }
  3950. if (ch == '\n') {
  3951. /* This is a new line.
  3952. * Remember position and backslash-escaping status.
  3953. */
  3954. o_addchr(&heredoc, ch);
  3955. prev = ch;
  3956. jump_in:
  3957. past_EOL = heredoc.length;
  3958. /* Get 1st char of next line, possibly skipping leading tabs */
  3959. do {
  3960. ch = i_getch(input);
  3961. if (ch != EOF)
  3962. nommu_addchr(as_string, ch);
  3963. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  3964. /* If this immediately ended the line,
  3965. * go back to end-of-line checks.
  3966. */
  3967. if (ch == '\n')
  3968. goto check_heredoc_end;
  3969. }
  3970. }
  3971. }
  3972. if (ch == EOF) {
  3973. o_free_unsafe(&heredoc);
  3974. return NULL;
  3975. }
  3976. o_addchr(&heredoc, ch);
  3977. nommu_addchr(as_string, ch);
  3978. if (prev == '\\' && ch == '\\')
  3979. /* Correctly handle foo\\<eol> (not a line cont.) */
  3980. prev = 0; /* not \ */
  3981. else
  3982. prev = ch;
  3983. }
  3984. }
  3985. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  3986. * and load them all. There should be exactly heredoc_cnt of them.
  3987. */
  3988. static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
  3989. {
  3990. struct pipe *pi = ctx->list_head;
  3991. while (pi && heredoc_cnt) {
  3992. int i;
  3993. struct command *cmd = pi->cmds;
  3994. debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  3995. pi->num_cmds,
  3996. cmd->argv ? cmd->argv[0] : "NONE");
  3997. for (i = 0; i < pi->num_cmds; i++) {
  3998. struct redir_struct *redir = cmd->redirects;
  3999. debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
  4000. i, cmd->argv ? cmd->argv[0] : "NONE");
  4001. while (redir) {
  4002. if (redir->rd_type == REDIRECT_HEREDOC) {
  4003. char *p;
  4004. redir->rd_type = REDIRECT_HEREDOC2;
  4005. /* redir->rd_dup is (ab)used to indicate <<- */
  4006. p = fetch_till_str(&ctx->as_string, input,
  4007. redir->rd_filename, redir->rd_dup);
  4008. if (!p) {
  4009. syntax_error("unexpected EOF in here document");
  4010. return 1;
  4011. }
  4012. free(redir->rd_filename);
  4013. redir->rd_filename = p;
  4014. heredoc_cnt--;
  4015. }
  4016. redir = redir->next;
  4017. }
  4018. cmd++;
  4019. }
  4020. pi = pi->next;
  4021. }
  4022. #if 0
  4023. /* Should be 0. If it isn't, it's a parse error */
  4024. if (heredoc_cnt)
  4025. bb_error_msg_and_die("heredoc BUG 2");
  4026. #endif
  4027. return 0;
  4028. }
  4029. static int run_list(struct pipe *pi);
  4030. #if BB_MMU
  4031. #define parse_stream(pstring, input, end_trigger) \
  4032. parse_stream(input, end_trigger)
  4033. #endif
  4034. static struct pipe *parse_stream(char **pstring,
  4035. struct in_str *input,
  4036. int end_trigger);
  4037. static int parse_group(struct parse_context *ctx,
  4038. struct in_str *input, int ch)
  4039. {
  4040. /* ctx->word contains characters seen prior to ( or {.
  4041. * Typically it's empty, but for function defs,
  4042. * it contains function name (without '()'). */
  4043. #if BB_MMU
  4044. # define as_string NULL
  4045. #else
  4046. char *as_string = NULL;
  4047. #endif
  4048. struct pipe *pipe_list;
  4049. int endch;
  4050. struct command *command = ctx->command;
  4051. debug_printf_parse("parse_group entered\n");
  4052. #if ENABLE_HUSH_FUNCTIONS
  4053. if (ch == '(' && !ctx->word.has_quoted_part) {
  4054. if (ctx->word.length)
  4055. if (done_word(ctx))
  4056. return 1;
  4057. if (!command->argv)
  4058. goto skip; /* (... */
  4059. if (command->argv[1]) { /* word word ... (... */
  4060. syntax_error_unexpected_ch('(');
  4061. return 1;
  4062. }
  4063. /* it is "word(..." or "word (..." */
  4064. do
  4065. ch = i_getch(input);
  4066. while (ch == ' ' || ch == '\t');
  4067. if (ch != ')') {
  4068. syntax_error_unexpected_ch(ch);
  4069. return 1;
  4070. }
  4071. nommu_addchr(&ctx->as_string, ch);
  4072. do
  4073. ch = i_getch(input);
  4074. while (ch == ' ' || ch == '\t' || ch == '\n');
  4075. if (ch != '{' && ch != '(') {
  4076. syntax_error_unexpected_ch(ch);
  4077. return 1;
  4078. }
  4079. nommu_addchr(&ctx->as_string, ch);
  4080. command->cmd_type = CMD_FUNCDEF;
  4081. goto skip;
  4082. }
  4083. #endif
  4084. #if 0 /* Prevented by caller */
  4085. if (command->argv /* word [word]{... */
  4086. || ctx->word.length /* word{... */
  4087. || ctx->word.has_quoted_part /* ""{... */
  4088. ) {
  4089. syntax_error(NULL);
  4090. debug_printf_parse("parse_group return 1: "
  4091. "syntax error, groups and arglists don't mix\n");
  4092. return 1;
  4093. }
  4094. #endif
  4095. IF_HUSH_FUNCTIONS(skip:)
  4096. endch = '}';
  4097. if (ch == '(') {
  4098. endch = ')';
  4099. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4100. command->cmd_type = CMD_SUBSHELL;
  4101. } else {
  4102. /* bash does not allow "{echo...", requires whitespace */
  4103. ch = i_peek(input);
  4104. if (ch != ' ' && ch != '\t' && ch != '\n'
  4105. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4106. ) {
  4107. syntax_error_unexpected_ch(ch);
  4108. return 1;
  4109. }
  4110. if (ch != '(') {
  4111. ch = i_getch(input);
  4112. nommu_addchr(&ctx->as_string, ch);
  4113. }
  4114. }
  4115. pipe_list = parse_stream(&as_string, input, endch);
  4116. #if !BB_MMU
  4117. if (as_string)
  4118. o_addstr(&ctx->as_string, as_string);
  4119. #endif
  4120. /* empty ()/{} or parse error? */
  4121. if (!pipe_list || pipe_list == ERR_PTR) {
  4122. /* parse_stream already emitted error msg */
  4123. if (!BB_MMU)
  4124. free(as_string);
  4125. debug_printf_parse("parse_group return 1: "
  4126. "parse_stream returned %p\n", pipe_list);
  4127. return 1;
  4128. }
  4129. #if !BB_MMU
  4130. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4131. command->group_as_string = as_string;
  4132. debug_printf_parse("end of group, remembering as:'%s'\n",
  4133. command->group_as_string);
  4134. #endif
  4135. #if ENABLE_HUSH_FUNCTIONS
  4136. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4137. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4138. struct command *cmd2;
  4139. cmd2 = xzalloc(sizeof(*cmd2));
  4140. cmd2->cmd_type = CMD_SUBSHELL;
  4141. cmd2->group = pipe_list;
  4142. # if !BB_MMU
  4143. //UNTESTED!
  4144. cmd2->group_as_string = command->group_as_string;
  4145. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4146. # endif
  4147. pipe_list = new_pipe();
  4148. pipe_list->cmds = cmd2;
  4149. pipe_list->num_cmds = 1;
  4150. }
  4151. #endif
  4152. command->group = pipe_list;
  4153. debug_printf_parse("parse_group return 0\n");
  4154. return 0;
  4155. /* command remains "open", available for possible redirects */
  4156. #undef as_string
  4157. }
  4158. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4159. /* Subroutines for copying $(...) and `...` things */
  4160. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4161. /* '...' */
  4162. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4163. {
  4164. while (1) {
  4165. int ch = i_getch(input);
  4166. if (ch == EOF) {
  4167. syntax_error_unterm_ch('\'');
  4168. return 0;
  4169. }
  4170. if (ch == '\'')
  4171. return 1;
  4172. o_addchr(dest, ch);
  4173. }
  4174. }
  4175. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4176. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4177. {
  4178. while (1) {
  4179. int ch = i_getch(input);
  4180. if (ch == EOF) {
  4181. syntax_error_unterm_ch('"');
  4182. return 0;
  4183. }
  4184. if (ch == '"')
  4185. return 1;
  4186. if (ch == '\\') { /* \x. Copy both chars. */
  4187. o_addchr(dest, ch);
  4188. ch = i_getch(input);
  4189. }
  4190. o_addchr(dest, ch);
  4191. if (ch == '`') {
  4192. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4193. return 0;
  4194. o_addchr(dest, ch);
  4195. continue;
  4196. }
  4197. //if (ch == '$') ...
  4198. }
  4199. }
  4200. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4201. * \` quoting.
  4202. * "Within the backquoted style of command substitution, backslash
  4203. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4204. * The search for the matching backquote shall be satisfied by the first
  4205. * backquote found without a preceding backslash; during this search,
  4206. * if a non-escaped backquote is encountered within a shell comment,
  4207. * a here-document, an embedded command substitution of the $(command)
  4208. * form, or a quoted string, undefined results occur. A single-quoted
  4209. * or double-quoted string that begins, but does not end, within the
  4210. * "`...`" sequence produces undefined results."
  4211. * Example Output
  4212. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4213. */
  4214. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4215. {
  4216. while (1) {
  4217. int ch = i_getch(input);
  4218. if (ch == '`')
  4219. return 1;
  4220. if (ch == '\\') {
  4221. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4222. ch = i_getch(input);
  4223. if (ch != '`'
  4224. && ch != '$'
  4225. && ch != '\\'
  4226. && (!in_dquote || ch != '"')
  4227. ) {
  4228. o_addchr(dest, '\\');
  4229. }
  4230. }
  4231. if (ch == EOF) {
  4232. syntax_error_unterm_ch('`');
  4233. return 0;
  4234. }
  4235. o_addchr(dest, ch);
  4236. }
  4237. }
  4238. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4239. * quoting and nested ()s.
  4240. * "With the $(command) style of command substitution, all characters
  4241. * following the open parenthesis to the matching closing parenthesis
  4242. * constitute the command. Any valid shell script can be used for command,
  4243. * except a script consisting solely of redirections which produces
  4244. * unspecified results."
  4245. * Example Output
  4246. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4247. * echo $(echo 'TEST)' BEST) TEST) BEST
  4248. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4249. *
  4250. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4251. * can contain arbitrary constructs, just like $(cmd).
  4252. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4253. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4254. */
  4255. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4256. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4257. {
  4258. int ch;
  4259. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4260. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4261. char end_char2 = end_ch >> 8;
  4262. # endif
  4263. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4264. #if ENABLE_HUSH_INTERACTIVE
  4265. G.promptmode = 1; /* PS2 */
  4266. #endif
  4267. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4268. while (1) {
  4269. ch = i_getch(input);
  4270. if (ch == EOF) {
  4271. syntax_error_unterm_ch(end_ch);
  4272. return 0;
  4273. }
  4274. if (ch == end_ch
  4275. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4276. || ch == end_char2
  4277. # endif
  4278. ) {
  4279. if (!dbl)
  4280. break;
  4281. /* we look for closing )) of $((EXPR)) */
  4282. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4283. i_getch(input); /* eat second ')' */
  4284. break;
  4285. }
  4286. }
  4287. o_addchr(dest, ch);
  4288. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4289. if (ch == '(' || ch == '{') {
  4290. ch = (ch == '(' ? ')' : '}');
  4291. if (!add_till_closing_bracket(dest, input, ch))
  4292. return 0;
  4293. o_addchr(dest, ch);
  4294. continue;
  4295. }
  4296. if (ch == '\'') {
  4297. if (!add_till_single_quote(dest, input))
  4298. return 0;
  4299. o_addchr(dest, ch);
  4300. continue;
  4301. }
  4302. if (ch == '"') {
  4303. if (!add_till_double_quote(dest, input))
  4304. return 0;
  4305. o_addchr(dest, ch);
  4306. continue;
  4307. }
  4308. if (ch == '`') {
  4309. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4310. return 0;
  4311. o_addchr(dest, ch);
  4312. continue;
  4313. }
  4314. if (ch == '\\') {
  4315. /* \x. Copy verbatim. Important for \(, \) */
  4316. ch = i_getch(input);
  4317. if (ch == EOF) {
  4318. syntax_error_unterm_ch(end_ch);
  4319. return 0;
  4320. }
  4321. #if 0
  4322. if (ch == '\n') {
  4323. /* "backslash+newline", ignore both */
  4324. o_delchr(dest); /* undo insertion of '\' */
  4325. continue;
  4326. }
  4327. #endif
  4328. o_addchr(dest, ch);
  4329. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4330. continue;
  4331. }
  4332. }
  4333. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4334. return ch;
  4335. }
  4336. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4337. /* Return code: 0 for OK, 1 for syntax error */
  4338. #if BB_MMU
  4339. #define parse_dollar(as_string, dest, input, quote_mask) \
  4340. parse_dollar(dest, input, quote_mask)
  4341. #define as_string NULL
  4342. #endif
  4343. static int parse_dollar(o_string *as_string,
  4344. o_string *dest,
  4345. struct in_str *input, unsigned char quote_mask)
  4346. {
  4347. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4348. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4349. if (isalpha(ch)) {
  4350. make_var:
  4351. ch = i_getch(input);
  4352. nommu_addchr(as_string, ch);
  4353. /*make_var1:*/
  4354. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4355. while (1) {
  4356. debug_printf_parse(": '%c'\n", ch);
  4357. o_addchr(dest, ch | quote_mask);
  4358. quote_mask = 0;
  4359. ch = i_peek_and_eat_bkslash_nl(input);
  4360. if (!isalnum(ch) && ch != '_') {
  4361. /* End of variable name reached */
  4362. break;
  4363. }
  4364. ch = i_getch(input);
  4365. nommu_addchr(as_string, ch);
  4366. }
  4367. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4368. } else if (isdigit(ch)) {
  4369. make_one_char_var:
  4370. ch = i_getch(input);
  4371. nommu_addchr(as_string, ch);
  4372. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4373. debug_printf_parse(": '%c'\n", ch);
  4374. o_addchr(dest, ch | quote_mask);
  4375. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4376. } else switch (ch) {
  4377. case '$': /* pid */
  4378. case '!': /* last bg pid */
  4379. case '?': /* last exit code */
  4380. case '#': /* number of args */
  4381. case '*': /* args */
  4382. case '@': /* args */
  4383. goto make_one_char_var;
  4384. case '{': {
  4385. char len_single_ch;
  4386. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4387. ch = i_getch(input); /* eat '{' */
  4388. nommu_addchr(as_string, ch);
  4389. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4390. /* It should be ${?}, or ${#var},
  4391. * or even ${?+subst} - operator acting on a special variable,
  4392. * or the beginning of variable name.
  4393. */
  4394. if (ch == EOF
  4395. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4396. ) {
  4397. bad_dollar_syntax:
  4398. syntax_error_unterm_str("${name}");
  4399. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4400. return 0;
  4401. }
  4402. nommu_addchr(as_string, ch);
  4403. len_single_ch = ch;
  4404. ch |= quote_mask;
  4405. /* It's possible to just call add_till_closing_bracket() at this point.
  4406. * However, this regresses some of our testsuite cases
  4407. * which check invalid constructs like ${%}.
  4408. * Oh well... let's check that the var name part is fine... */
  4409. while (1) {
  4410. unsigned pos;
  4411. o_addchr(dest, ch);
  4412. debug_printf_parse(": '%c'\n", ch);
  4413. ch = i_getch(input);
  4414. nommu_addchr(as_string, ch);
  4415. if (ch == '}')
  4416. break;
  4417. if (!isalnum(ch) && ch != '_') {
  4418. unsigned end_ch;
  4419. unsigned char last_ch;
  4420. /* handle parameter expansions
  4421. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4422. */
  4423. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4424. if (len_single_ch != '#'
  4425. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4426. || i_peek(input) != '}'
  4427. ) {
  4428. goto bad_dollar_syntax;
  4429. }
  4430. /* else: it's "length of C" ${#C} op,
  4431. * where C is a single char
  4432. * special var name, e.g. ${#!}.
  4433. */
  4434. }
  4435. /* Eat everything until closing '}' (or ':') */
  4436. end_ch = '}';
  4437. if (BASH_SUBSTR
  4438. && ch == ':'
  4439. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4440. ) {
  4441. /* It's ${var:N[:M]} thing */
  4442. end_ch = '}' * 0x100 + ':';
  4443. }
  4444. if (BASH_PATTERN_SUBST
  4445. && ch == '/'
  4446. ) {
  4447. /* It's ${var/[/]pattern[/repl]} thing */
  4448. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4449. i_getch(input);
  4450. nommu_addchr(as_string, '/');
  4451. ch = '\\';
  4452. }
  4453. end_ch = '}' * 0x100 + '/';
  4454. }
  4455. o_addchr(dest, ch);
  4456. again:
  4457. if (!BB_MMU)
  4458. pos = dest->length;
  4459. #if ENABLE_HUSH_DOLLAR_OPS
  4460. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4461. if (last_ch == 0) /* error? */
  4462. return 0;
  4463. #else
  4464. #error Simple code to only allow ${var} is not implemented
  4465. #endif
  4466. if (as_string) {
  4467. o_addstr(as_string, dest->data + pos);
  4468. o_addchr(as_string, last_ch);
  4469. }
  4470. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4471. && (end_ch & 0xff00)
  4472. ) {
  4473. /* close the first block: */
  4474. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4475. /* while parsing N from ${var:N[:M]}
  4476. * or pattern from ${var/[/]pattern[/repl]} */
  4477. if ((end_ch & 0xff) == last_ch) {
  4478. /* got ':' or '/'- parse the rest */
  4479. end_ch = '}';
  4480. goto again;
  4481. }
  4482. /* got '}' */
  4483. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4484. /* it's ${var:N} - emulate :999999999 */
  4485. o_addstr(dest, "999999999");
  4486. } /* else: it's ${var/[/]pattern} */
  4487. }
  4488. break;
  4489. }
  4490. len_single_ch = 0; /* it can't be ${#C} op */
  4491. }
  4492. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4493. break;
  4494. }
  4495. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4496. case '(': {
  4497. unsigned pos;
  4498. ch = i_getch(input);
  4499. nommu_addchr(as_string, ch);
  4500. # if ENABLE_FEATURE_SH_MATH
  4501. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4502. ch = i_getch(input);
  4503. nommu_addchr(as_string, ch);
  4504. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4505. o_addchr(dest, /*quote_mask |*/ '+');
  4506. if (!BB_MMU)
  4507. pos = dest->length;
  4508. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4509. return 0; /* error */
  4510. if (as_string) {
  4511. o_addstr(as_string, dest->data + pos);
  4512. o_addchr(as_string, ')');
  4513. o_addchr(as_string, ')');
  4514. }
  4515. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4516. break;
  4517. }
  4518. # endif
  4519. # if ENABLE_HUSH_TICK
  4520. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4521. o_addchr(dest, quote_mask | '`');
  4522. if (!BB_MMU)
  4523. pos = dest->length;
  4524. if (!add_till_closing_bracket(dest, input, ')'))
  4525. return 0; /* error */
  4526. if (as_string) {
  4527. o_addstr(as_string, dest->data + pos);
  4528. o_addchr(as_string, ')');
  4529. }
  4530. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4531. # endif
  4532. break;
  4533. }
  4534. #endif
  4535. case '_':
  4536. goto make_var;
  4537. #if 0
  4538. /* TODO: $_ and $-: */
  4539. /* $_ Shell or shell script name; or last argument of last command
  4540. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4541. * but in command's env, set to full pathname used to invoke it */
  4542. /* $- Option flags set by set builtin or shell options (-i etc) */
  4543. ch = i_getch(input);
  4544. nommu_addchr(as_string, ch);
  4545. ch = i_peek_and_eat_bkslash_nl(input);
  4546. if (isalnum(ch)) { /* it's $_name or $_123 */
  4547. ch = '_';
  4548. goto make_var1;
  4549. }
  4550. /* else: it's $_ */
  4551. #endif
  4552. default:
  4553. o_addQchr(dest, '$');
  4554. }
  4555. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4556. return 1;
  4557. #undef as_string
  4558. }
  4559. #if BB_MMU
  4560. # if BASH_PATTERN_SUBST
  4561. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  4562. encode_string(dest, input, dquote_end, process_bkslash)
  4563. # else
  4564. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  4565. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  4566. encode_string(dest, input, dquote_end)
  4567. # endif
  4568. #define as_string NULL
  4569. #else /* !MMU */
  4570. # if BASH_PATTERN_SUBST
  4571. /* all parameters are needed, no macro tricks */
  4572. # else
  4573. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  4574. encode_string(as_string, dest, input, dquote_end)
  4575. # endif
  4576. #endif
  4577. static int encode_string(o_string *as_string,
  4578. o_string *dest,
  4579. struct in_str *input,
  4580. int dquote_end,
  4581. int process_bkslash)
  4582. {
  4583. #if !BASH_PATTERN_SUBST
  4584. const int process_bkslash = 1;
  4585. #endif
  4586. int ch;
  4587. int next;
  4588. again:
  4589. ch = i_getch(input);
  4590. if (ch != EOF)
  4591. nommu_addchr(as_string, ch);
  4592. if (ch == dquote_end) { /* may be only '"' or EOF */
  4593. debug_printf_parse("encode_string return 1 (ok)\n");
  4594. return 1;
  4595. }
  4596. /* note: can't move it above ch == dquote_end check! */
  4597. if (ch == EOF) {
  4598. syntax_error_unterm_ch('"');
  4599. return 0; /* error */
  4600. }
  4601. next = '\0';
  4602. if (ch != '\n') {
  4603. next = i_peek(input);
  4604. }
  4605. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4606. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4607. if (process_bkslash && ch == '\\') {
  4608. if (next == EOF) {
  4609. /* Testcase: in interactive shell a file with
  4610. * echo "unterminated string\<eof>
  4611. * is sourced.
  4612. */
  4613. syntax_error_unterm_ch('"');
  4614. return 0; /* error */
  4615. }
  4616. /* bash:
  4617. * "The backslash retains its special meaning [in "..."]
  4618. * only when followed by one of the following characters:
  4619. * $, `, ", \, or <newline>. A double quote may be quoted
  4620. * within double quotes by preceding it with a backslash."
  4621. * NB: in (unquoted) heredoc, above does not apply to ",
  4622. * therefore we check for it by "next == dquote_end" cond.
  4623. */
  4624. if (next == dquote_end || strchr("$`\\\n", next)) {
  4625. ch = i_getch(input); /* eat next */
  4626. if (ch == '\n')
  4627. goto again; /* skip \<newline> */
  4628. } /* else: ch remains == '\\', and we double it below: */
  4629. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4630. nommu_addchr(as_string, ch);
  4631. goto again;
  4632. }
  4633. if (ch == '$') {
  4634. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4635. debug_printf_parse("encode_string return 0: "
  4636. "parse_dollar returned 0 (error)\n");
  4637. return 0;
  4638. }
  4639. goto again;
  4640. }
  4641. #if ENABLE_HUSH_TICK
  4642. if (ch == '`') {
  4643. //unsigned pos = dest->length;
  4644. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4645. o_addchr(dest, 0x80 | '`');
  4646. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4647. return 0; /* error */
  4648. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4649. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4650. goto again;
  4651. }
  4652. #endif
  4653. o_addQchr(dest, ch);
  4654. goto again;
  4655. #undef as_string
  4656. }
  4657. /*
  4658. * Scan input until EOF or end_trigger char.
  4659. * Return a list of pipes to execute, or NULL on EOF
  4660. * or if end_trigger character is met.
  4661. * On syntax error, exit if shell is not interactive,
  4662. * reset parsing machinery and start parsing anew,
  4663. * or return ERR_PTR.
  4664. */
  4665. static struct pipe *parse_stream(char **pstring,
  4666. struct in_str *input,
  4667. int end_trigger)
  4668. {
  4669. struct parse_context ctx;
  4670. int heredoc_cnt;
  4671. /* Single-quote triggers a bypass of the main loop until its mate is
  4672. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4673. */
  4674. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4675. end_trigger ? end_trigger : 'X');
  4676. debug_enter();
  4677. initialize_context(&ctx);
  4678. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4679. * Preventing this:
  4680. */
  4681. o_addchr(&ctx.word, '\0');
  4682. ctx.word.length = 0;
  4683. /* We used to separate words on $IFS here. This was wrong.
  4684. * $IFS is used only for word splitting when $var is expanded,
  4685. * here we should use blank chars as separators, not $IFS
  4686. */
  4687. heredoc_cnt = 0;
  4688. while (1) {
  4689. const char *is_blank;
  4690. const char *is_special;
  4691. int ch;
  4692. int next;
  4693. int redir_fd;
  4694. redir_type redir_style;
  4695. ch = i_getch(input);
  4696. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4697. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4698. if (ch == EOF) {
  4699. struct pipe *pi;
  4700. if (heredoc_cnt) {
  4701. syntax_error_unterm_str("here document");
  4702. goto parse_error;
  4703. }
  4704. if (end_trigger == ')') {
  4705. syntax_error_unterm_ch('(');
  4706. goto parse_error;
  4707. }
  4708. if (end_trigger == '}') {
  4709. syntax_error_unterm_ch('{');
  4710. goto parse_error;
  4711. }
  4712. if (done_word(&ctx)) {
  4713. goto parse_error;
  4714. }
  4715. o_free(&ctx.word);
  4716. done_pipe(&ctx, PIPE_SEQ);
  4717. pi = ctx.list_head;
  4718. /* If we got nothing... */
  4719. /* (this makes bare "&" cmd a no-op.
  4720. * bash says: "syntax error near unexpected token '&'") */
  4721. if (pi->num_cmds == 0
  4722. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4723. ) {
  4724. free_pipe_list(pi);
  4725. pi = NULL;
  4726. }
  4727. #if !BB_MMU
  4728. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4729. if (pstring)
  4730. *pstring = ctx.as_string.data;
  4731. else
  4732. o_free_unsafe(&ctx.as_string);
  4733. #endif
  4734. debug_leave();
  4735. debug_printf_parse("parse_stream return %p\n", pi);
  4736. return pi;
  4737. }
  4738. /* Handle "'" and "\" first, as they won't play nice with
  4739. * i_peek_and_eat_bkslash_nl() anyway:
  4740. * echo z\\
  4741. * and
  4742. * echo '\
  4743. * '
  4744. * would break.
  4745. */
  4746. if (ch == '\\') {
  4747. ch = i_getch(input);
  4748. if (ch == '\n')
  4749. continue; /* drop \<newline>, get next char */
  4750. nommu_addchr(&ctx.as_string, '\\');
  4751. o_addchr(&ctx.word, '\\');
  4752. if (ch == EOF) {
  4753. /* Testcase: eval 'echo Ok\' */
  4754. /* bash-4.3.43 was removing backslash,
  4755. * but 4.4.19 retains it, most other shells too
  4756. */
  4757. continue; /* get next char */
  4758. }
  4759. /* Example: echo Hello \2>file
  4760. * we need to know that word 2 is quoted
  4761. */
  4762. ctx.word.has_quoted_part = 1;
  4763. nommu_addchr(&ctx.as_string, ch);
  4764. o_addchr(&ctx.word, ch);
  4765. continue; /* get next char */
  4766. }
  4767. nommu_addchr(&ctx.as_string, ch);
  4768. if (ch == '\'') {
  4769. ctx.word.has_quoted_part = 1;
  4770. next = i_getch(input);
  4771. if (next == '\'' && !ctx.pending_redirect)
  4772. goto insert_empty_quoted_str_marker;
  4773. ch = next;
  4774. while (1) {
  4775. if (ch == EOF) {
  4776. syntax_error_unterm_ch('\'');
  4777. goto parse_error;
  4778. }
  4779. nommu_addchr(&ctx.as_string, ch);
  4780. if (ch == '\'')
  4781. break;
  4782. if (ch == SPECIAL_VAR_SYMBOL) {
  4783. /* Convert raw ^C to corresponding special variable reference */
  4784. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4785. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4786. }
  4787. o_addqchr(&ctx.word, ch);
  4788. ch = i_getch(input);
  4789. }
  4790. continue; /* get next char */
  4791. }
  4792. next = '\0';
  4793. if (ch != '\n')
  4794. next = i_peek_and_eat_bkslash_nl(input);
  4795. is_special = "{}<>;&|()#" /* special outside of "str" */
  4796. "$\"" IF_HUSH_TICK("`") /* always special */
  4797. SPECIAL_VAR_SYMBOL_STR;
  4798. /* Are { and } special here? */
  4799. if (ctx.command->argv /* word [word]{... - non-special */
  4800. || ctx.word.length /* word{... - non-special */
  4801. || ctx.word.has_quoted_part /* ""{... - non-special */
  4802. || (next != ';' /* }; - special */
  4803. && next != ')' /* }) - special */
  4804. && next != '(' /* {( - special */
  4805. && next != '&' /* }& and }&& ... - special */
  4806. && next != '|' /* }|| ... - special */
  4807. && !strchr(defifs, next) /* {word - non-special */
  4808. )
  4809. ) {
  4810. /* They are not special, skip "{}" */
  4811. is_special += 2;
  4812. }
  4813. is_special = strchr(is_special, ch);
  4814. is_blank = strchr(defifs, ch);
  4815. if (!is_special && !is_blank) { /* ordinary char */
  4816. ordinary_char:
  4817. o_addQchr(&ctx.word, ch);
  4818. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  4819. || ctx.is_assignment == WORD_IS_KEYWORD)
  4820. && ch == '='
  4821. && is_well_formed_var_name(ctx.word.data, '=')
  4822. ) {
  4823. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  4824. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  4825. }
  4826. continue;
  4827. }
  4828. if (is_blank) {
  4829. #if ENABLE_HUSH_LINENO_VAR
  4830. /* Case:
  4831. * "while ...; do<whitespace><newline>
  4832. * cmd ..."
  4833. * would think that "cmd" starts in <whitespace> -
  4834. * i.e., at the previous line.
  4835. * We need to skip all whitespace before newlines.
  4836. */
  4837. while (ch != '\n') {
  4838. next = i_peek(input);
  4839. if (next != ' ' && next != '\t' && next != '\n')
  4840. break; /* next char is not ws */
  4841. ch = i_getch(input);
  4842. }
  4843. /* ch == last eaten whitespace char */
  4844. #endif
  4845. if (done_word(&ctx)) {
  4846. goto parse_error;
  4847. }
  4848. if (ch == '\n') {
  4849. /* Is this a case when newline is simply ignored?
  4850. * Some examples:
  4851. * "cmd | <newline> cmd ..."
  4852. * "case ... in <newline> word) ..."
  4853. */
  4854. if (IS_NULL_CMD(ctx.command)
  4855. && ctx.word.length == 0 && !ctx.word.has_quoted_part
  4856. ) {
  4857. /* This newline can be ignored. But...
  4858. * Without check #1, interactive shell
  4859. * ignores even bare <newline>,
  4860. * and shows the continuation prompt:
  4861. * ps1_prompt$ <enter>
  4862. * ps2> _ <=== wrong, should be ps1
  4863. * Without check #2, "cmd & <newline>"
  4864. * is similarly mistreated.
  4865. * (BTW, this makes "cmd & cmd"
  4866. * and "cmd && cmd" non-orthogonal.
  4867. * Really, ask yourself, why
  4868. * "cmd && <newline>" doesn't start
  4869. * cmd but waits for more input?
  4870. * The only reason is that it might be
  4871. * a "cmd1 && <nl> cmd2 &" construct,
  4872. * cmd1 may need to run in BG).
  4873. */
  4874. struct pipe *pi = ctx.list_head;
  4875. if (pi->num_cmds != 0 /* check #1 */
  4876. && pi->followup != PIPE_BG /* check #2 */
  4877. ) {
  4878. continue;
  4879. }
  4880. }
  4881. /* Treat newline as a command separator. */
  4882. done_pipe(&ctx, PIPE_SEQ);
  4883. debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
  4884. if (heredoc_cnt) {
  4885. if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
  4886. goto parse_error;
  4887. }
  4888. heredoc_cnt = 0;
  4889. }
  4890. ctx.is_assignment = MAYBE_ASSIGNMENT;
  4891. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  4892. ch = ';';
  4893. /* note: if (is_blank) continue;
  4894. * will still trigger for us */
  4895. }
  4896. }
  4897. /* "cmd}" or "cmd }..." without semicolon or &:
  4898. * } is an ordinary char in this case, even inside { cmd; }
  4899. * Pathological example: { ""}; } should exec "}" cmd
  4900. */
  4901. if (ch == '}') {
  4902. if (ctx.word.length != 0 /* word} */
  4903. || ctx.word.has_quoted_part /* ""} */
  4904. ) {
  4905. goto ordinary_char;
  4906. }
  4907. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  4908. /* Generally, there should be semicolon: "cmd; }"
  4909. * However, bash allows to omit it if "cmd" is
  4910. * a group. Examples:
  4911. * { { echo 1; } }
  4912. * {(echo 1)}
  4913. * { echo 0 >&2 | { echo 1; } }
  4914. * { while false; do :; done }
  4915. * { case a in b) ;; esac }
  4916. */
  4917. if (ctx.command->group)
  4918. goto term_group;
  4919. goto ordinary_char;
  4920. }
  4921. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  4922. /* Can't be an end of {cmd}, skip the check */
  4923. goto skip_end_trigger;
  4924. /* else: } does terminate a group */
  4925. }
  4926. term_group:
  4927. if (end_trigger && end_trigger == ch
  4928. && (ch != ';' || heredoc_cnt == 0)
  4929. #if ENABLE_HUSH_CASE
  4930. && (ch != ')'
  4931. || ctx.ctx_res_w != RES_MATCH
  4932. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  4933. )
  4934. #endif
  4935. ) {
  4936. if (heredoc_cnt) {
  4937. /* This is technically valid:
  4938. * { cat <<HERE; }; echo Ok
  4939. * heredoc
  4940. * heredoc
  4941. * HERE
  4942. * but we don't support this.
  4943. * We require heredoc to be in enclosing {}/(),
  4944. * if any.
  4945. */
  4946. syntax_error_unterm_str("here document");
  4947. goto parse_error;
  4948. }
  4949. if (done_word(&ctx)) {
  4950. goto parse_error;
  4951. }
  4952. done_pipe(&ctx, PIPE_SEQ);
  4953. ctx.is_assignment = MAYBE_ASSIGNMENT;
  4954. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  4955. /* Do we sit outside of any if's, loops or case's? */
  4956. if (!HAS_KEYWORDS
  4957. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  4958. ) {
  4959. o_free(&ctx.word);
  4960. #if !BB_MMU
  4961. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  4962. if (pstring)
  4963. *pstring = ctx.as_string.data;
  4964. else
  4965. o_free_unsafe(&ctx.as_string);
  4966. #endif
  4967. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  4968. /* Example: bare "{ }", "()" */
  4969. G.last_exitcode = 2; /* bash compat */
  4970. syntax_error_unexpected_ch(ch);
  4971. goto parse_error2;
  4972. }
  4973. debug_printf_parse("parse_stream return %p: "
  4974. "end_trigger char found\n",
  4975. ctx.list_head);
  4976. debug_leave();
  4977. return ctx.list_head;
  4978. }
  4979. }
  4980. if (is_blank)
  4981. continue;
  4982. /* Catch <, > before deciding whether this word is
  4983. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  4984. switch (ch) {
  4985. case '>':
  4986. redir_fd = redirect_opt_num(&ctx.word);
  4987. if (done_word(&ctx)) {
  4988. goto parse_error;
  4989. }
  4990. redir_style = REDIRECT_OVERWRITE;
  4991. if (next == '>') {
  4992. redir_style = REDIRECT_APPEND;
  4993. ch = i_getch(input);
  4994. nommu_addchr(&ctx.as_string, ch);
  4995. }
  4996. #if 0
  4997. else if (next == '(') {
  4998. syntax_error(">(process) not supported");
  4999. goto parse_error;
  5000. }
  5001. #endif
  5002. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5003. goto parse_error;
  5004. continue; /* get next char */
  5005. case '<':
  5006. redir_fd = redirect_opt_num(&ctx.word);
  5007. if (done_word(&ctx)) {
  5008. goto parse_error;
  5009. }
  5010. redir_style = REDIRECT_INPUT;
  5011. if (next == '<') {
  5012. redir_style = REDIRECT_HEREDOC;
  5013. heredoc_cnt++;
  5014. debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
  5015. ch = i_getch(input);
  5016. nommu_addchr(&ctx.as_string, ch);
  5017. } else if (next == '>') {
  5018. redir_style = REDIRECT_IO;
  5019. ch = i_getch(input);
  5020. nommu_addchr(&ctx.as_string, ch);
  5021. }
  5022. #if 0
  5023. else if (next == '(') {
  5024. syntax_error("<(process) not supported");
  5025. goto parse_error;
  5026. }
  5027. #endif
  5028. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5029. goto parse_error;
  5030. continue; /* get next char */
  5031. case '#':
  5032. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5033. /* skip "#comment" */
  5034. /* note: we do not add it to &ctx.as_string */
  5035. /* TODO: in bash:
  5036. * comment inside $() goes to the next \n, even inside quoted string (!):
  5037. * cmd "$(cmd2 #comment)" - syntax error
  5038. * cmd "`cmd2 #comment`" - ok
  5039. * We accept both (comment ends where command subst ends, in both cases).
  5040. */
  5041. while (1) {
  5042. ch = i_peek(input);
  5043. if (ch == '\n') {
  5044. nommu_addchr(&ctx.as_string, '\n');
  5045. break;
  5046. }
  5047. ch = i_getch(input);
  5048. if (ch == EOF)
  5049. break;
  5050. }
  5051. continue; /* get next char */
  5052. }
  5053. break;
  5054. }
  5055. skip_end_trigger:
  5056. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5057. /* check that we are not in word in "a=1 2>word b=1": */
  5058. && !ctx.pending_redirect
  5059. ) {
  5060. /* ch is a special char and thus this word
  5061. * cannot be an assignment */
  5062. ctx.is_assignment = NOT_ASSIGNMENT;
  5063. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5064. }
  5065. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5066. switch (ch) {
  5067. case SPECIAL_VAR_SYMBOL:
  5068. /* Convert raw ^C to corresponding special variable reference */
  5069. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5070. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5071. /* fall through */
  5072. case '#':
  5073. /* non-comment #: "echo a#b" etc */
  5074. o_addchr(&ctx.word, ch);
  5075. continue; /* get next char */
  5076. case '$':
  5077. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5078. debug_printf_parse("parse_stream parse error: "
  5079. "parse_dollar returned 0 (error)\n");
  5080. goto parse_error;
  5081. }
  5082. continue; /* get next char */
  5083. case '"':
  5084. ctx.word.has_quoted_part = 1;
  5085. if (next == '"' && !ctx.pending_redirect) {
  5086. i_getch(input); /* eat second " */
  5087. insert_empty_quoted_str_marker:
  5088. nommu_addchr(&ctx.as_string, next);
  5089. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5090. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5091. continue; /* get next char */
  5092. }
  5093. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5094. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5095. if (!encode_string(&ctx.as_string, &ctx.word, input, '"', /*process_bkslash:*/ 1))
  5096. goto parse_error;
  5097. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5098. continue; /* get next char */
  5099. #if ENABLE_HUSH_TICK
  5100. case '`': {
  5101. USE_FOR_NOMMU(unsigned pos;)
  5102. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5103. o_addchr(&ctx.word, '`');
  5104. USE_FOR_NOMMU(pos = ctx.word.length;)
  5105. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5106. goto parse_error;
  5107. # if !BB_MMU
  5108. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5109. o_addchr(&ctx.as_string, '`');
  5110. # endif
  5111. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5112. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5113. continue; /* get next char */
  5114. }
  5115. #endif
  5116. case ';':
  5117. #if ENABLE_HUSH_CASE
  5118. case_semi:
  5119. #endif
  5120. if (done_word(&ctx)) {
  5121. goto parse_error;
  5122. }
  5123. done_pipe(&ctx, PIPE_SEQ);
  5124. #if ENABLE_HUSH_CASE
  5125. /* Eat multiple semicolons, detect
  5126. * whether it means something special */
  5127. while (1) {
  5128. ch = i_peek_and_eat_bkslash_nl(input);
  5129. if (ch != ';')
  5130. break;
  5131. ch = i_getch(input);
  5132. nommu_addchr(&ctx.as_string, ch);
  5133. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5134. ctx.ctx_dsemicolon = 1;
  5135. ctx.ctx_res_w = RES_MATCH;
  5136. break;
  5137. }
  5138. }
  5139. #endif
  5140. new_cmd:
  5141. /* We just finished a cmd. New one may start
  5142. * with an assignment */
  5143. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5144. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5145. continue; /* get next char */
  5146. case '&':
  5147. if (done_word(&ctx)) {
  5148. goto parse_error;
  5149. }
  5150. if (next == '&') {
  5151. ch = i_getch(input);
  5152. nommu_addchr(&ctx.as_string, ch);
  5153. done_pipe(&ctx, PIPE_AND);
  5154. } else {
  5155. done_pipe(&ctx, PIPE_BG);
  5156. }
  5157. goto new_cmd;
  5158. case '|':
  5159. if (done_word(&ctx)) {
  5160. goto parse_error;
  5161. }
  5162. #if ENABLE_HUSH_CASE
  5163. if (ctx.ctx_res_w == RES_MATCH)
  5164. break; /* we are in case's "word | word)" */
  5165. #endif
  5166. if (next == '|') { /* || */
  5167. ch = i_getch(input);
  5168. nommu_addchr(&ctx.as_string, ch);
  5169. done_pipe(&ctx, PIPE_OR);
  5170. } else {
  5171. /* we could pick up a file descriptor choice here
  5172. * with redirect_opt_num(), but bash doesn't do it.
  5173. * "echo foo 2| cat" yields "foo 2". */
  5174. done_command(&ctx);
  5175. }
  5176. goto new_cmd;
  5177. case '(':
  5178. #if ENABLE_HUSH_CASE
  5179. /* "case... in [(]word)..." - skip '(' */
  5180. if (ctx.ctx_res_w == RES_MATCH
  5181. && ctx.command->argv == NULL /* not (word|(... */
  5182. && ctx.word.length == 0 /* not word(... */
  5183. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5184. ) {
  5185. continue; /* get next char */
  5186. }
  5187. #endif
  5188. case '{':
  5189. if (parse_group(&ctx, input, ch) != 0) {
  5190. goto parse_error;
  5191. }
  5192. goto new_cmd;
  5193. case ')':
  5194. #if ENABLE_HUSH_CASE
  5195. if (ctx.ctx_res_w == RES_MATCH)
  5196. goto case_semi;
  5197. #endif
  5198. case '}':
  5199. /* proper use of this character is caught by end_trigger:
  5200. * if we see {, we call parse_group(..., end_trigger='}')
  5201. * and it will match } earlier (not here). */
  5202. G.last_exitcode = 2;
  5203. syntax_error_unexpected_ch(ch);
  5204. goto parse_error2;
  5205. default:
  5206. if (HUSH_DEBUG)
  5207. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5208. }
  5209. } /* while (1) */
  5210. parse_error:
  5211. G.last_exitcode = 1;
  5212. parse_error2:
  5213. {
  5214. struct parse_context *pctx;
  5215. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5216. /* Clean up allocated tree.
  5217. * Sample for finding leaks on syntax error recovery path.
  5218. * Run it from interactive shell, watch pmap `pidof hush`.
  5219. * while if false; then false; fi; do break; fi
  5220. * Samples to catch leaks at execution:
  5221. * while if (true | { true;}); then echo ok; fi; do break; done
  5222. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5223. */
  5224. pctx = &ctx;
  5225. do {
  5226. /* Update pipe/command counts,
  5227. * otherwise freeing may miss some */
  5228. done_pipe(pctx, PIPE_SEQ);
  5229. debug_printf_clean("freeing list %p from ctx %p\n",
  5230. pctx->list_head, pctx);
  5231. debug_print_tree(pctx->list_head, 0);
  5232. free_pipe_list(pctx->list_head);
  5233. debug_printf_clean("freed list %p\n", pctx->list_head);
  5234. #if !BB_MMU
  5235. o_free_unsafe(&pctx->as_string);
  5236. #endif
  5237. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5238. if (pctx != &ctx) {
  5239. free(pctx);
  5240. }
  5241. IF_HAS_KEYWORDS(pctx = p2;)
  5242. } while (HAS_KEYWORDS && pctx);
  5243. o_free(&ctx.word);
  5244. #if !BB_MMU
  5245. if (pstring)
  5246. *pstring = NULL;
  5247. #endif
  5248. debug_leave();
  5249. return ERR_PTR;
  5250. }
  5251. }
  5252. /*** Execution routines ***/
  5253. /* Expansion can recurse, need forward decls: */
  5254. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5255. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5256. expand_string_to_string(str)
  5257. #endif
  5258. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5259. #if ENABLE_HUSH_TICK
  5260. static int process_command_subs(o_string *dest, const char *s);
  5261. #endif
  5262. /* expand_strvec_to_strvec() takes a list of strings, expands
  5263. * all variable references within and returns a pointer to
  5264. * a list of expanded strings, possibly with larger number
  5265. * of strings. (Think VAR="a b"; echo $VAR).
  5266. * This new list is allocated as a single malloc block.
  5267. * NULL-terminated list of char* pointers is at the beginning of it,
  5268. * followed by strings themselves.
  5269. * Caller can deallocate entire list by single free(list). */
  5270. /* A horde of its helpers come first: */
  5271. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5272. {
  5273. while (--len >= 0) {
  5274. char c = *str++;
  5275. #if ENABLE_HUSH_BRACE_EXPANSION
  5276. if (c == '{' || c == '}') {
  5277. /* { -> \{, } -> \} */
  5278. o_addchr(o, '\\');
  5279. /* And now we want to add { or } and continue:
  5280. * o_addchr(o, c);
  5281. * continue;
  5282. * luckily, just falling through achieves this.
  5283. */
  5284. }
  5285. #endif
  5286. o_addchr(o, c);
  5287. if (c == '\\') {
  5288. /* \z -> \\\z; \<eol> -> \\<eol> */
  5289. o_addchr(o, '\\');
  5290. if (len) {
  5291. len--;
  5292. o_addchr(o, '\\');
  5293. o_addchr(o, *str++);
  5294. }
  5295. }
  5296. }
  5297. }
  5298. /* Store given string, finalizing the word and starting new one whenever
  5299. * we encounter IFS char(s). This is used for expanding variable values.
  5300. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5301. * Return in *ended_with_ifs:
  5302. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5303. */
  5304. static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
  5305. {
  5306. int last_is_ifs = 0;
  5307. while (1) {
  5308. int word_len;
  5309. if (!*str) /* EOL - do not finalize word */
  5310. break;
  5311. word_len = strcspn(str, G.ifs);
  5312. if (word_len) {
  5313. /* We have WORD_LEN leading non-IFS chars */
  5314. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5315. o_addblock(output, str, word_len);
  5316. } else {
  5317. /* Protect backslashes against globbing up :)
  5318. * Example: "v='\*'; echo b$v" prints "b\*"
  5319. * (and does not try to glob on "*")
  5320. */
  5321. o_addblock_duplicate_backslash(output, str, word_len);
  5322. /*/ Why can't we do it easier? */
  5323. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5324. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5325. }
  5326. last_is_ifs = 0;
  5327. str += word_len;
  5328. if (!*str) /* EOL - do not finalize word */
  5329. break;
  5330. }
  5331. /* We know str here points to at least one IFS char */
  5332. last_is_ifs = 1;
  5333. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5334. if (!*str) /* EOL - do not finalize word */
  5335. break;
  5336. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5337. && strchr(G.ifs, *str) /* the second check would fail */
  5338. ) {
  5339. /* This is a non-whitespace $IFS char */
  5340. /* Skip it and IFS whitespace chars, start new word */
  5341. str++;
  5342. str += strspn(str, G.ifs_whitespace);
  5343. goto new_word;
  5344. }
  5345. /* Start new word... but not always! */
  5346. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5347. if (output->has_quoted_part
  5348. /* Case "v=' a'; echo $v":
  5349. * here nothing precedes the space in $v expansion,
  5350. * therefore we should not finish the word
  5351. * (IOW: if there *is* word to finalize, only then do it):
  5352. */
  5353. || (n > 0 && output->data[output->length - 1])
  5354. ) {
  5355. new_word:
  5356. o_addchr(output, '\0');
  5357. debug_print_list("expand_on_ifs", output, n);
  5358. n = o_save_ptr(output, n);
  5359. }
  5360. }
  5361. if (ended_with_ifs)
  5362. *ended_with_ifs = last_is_ifs;
  5363. debug_print_list("expand_on_ifs[1]", output, n);
  5364. return n;
  5365. }
  5366. /* Helper to expand $((...)) and heredoc body. These act as if
  5367. * they are in double quotes, with the exception that they are not :).
  5368. * Just the rules are similar: "expand only $var and `cmd`"
  5369. *
  5370. * Returns malloced string.
  5371. * As an optimization, we return NULL if expansion is not needed.
  5372. */
  5373. #if !BASH_PATTERN_SUBST
  5374. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  5375. #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
  5376. encode_then_expand_string(str)
  5377. #endif
  5378. static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
  5379. {
  5380. #if !BASH_PATTERN_SUBST
  5381. enum { do_unbackslash = 1 };
  5382. #endif
  5383. char *exp_str;
  5384. struct in_str input;
  5385. o_string dest = NULL_O_STRING;
  5386. if (!strchr(str, '$')
  5387. && !strchr(str, '\\')
  5388. #if ENABLE_HUSH_TICK
  5389. && !strchr(str, '`')
  5390. #endif
  5391. ) {
  5392. return NULL;
  5393. }
  5394. /* We need to expand. Example:
  5395. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5396. */
  5397. setup_string_in_str(&input, str);
  5398. encode_string(NULL, &dest, &input, EOF, process_bkslash);
  5399. //TODO: error check (encode_string returns 0 on error)?
  5400. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5401. exp_str = expand_string_to_string(dest.data,
  5402. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5403. do_unbackslash
  5404. );
  5405. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5406. o_free_unsafe(&dest);
  5407. return exp_str;
  5408. }
  5409. #if ENABLE_FEATURE_SH_MATH
  5410. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5411. {
  5412. arith_state_t math_state;
  5413. arith_t res;
  5414. char *exp_str;
  5415. math_state.lookupvar = get_local_var_value;
  5416. math_state.setvar = set_local_var_from_halves;
  5417. //math_state.endofname = endofname;
  5418. exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  5419. res = arith(&math_state, exp_str ? exp_str : arg);
  5420. free(exp_str);
  5421. if (errmsg_p)
  5422. *errmsg_p = math_state.errmsg;
  5423. if (math_state.errmsg)
  5424. msg_and_die_if_script(math_state.errmsg);
  5425. return res;
  5426. }
  5427. #endif
  5428. #if BASH_PATTERN_SUBST
  5429. /* ${var/[/]pattern[/repl]} helpers */
  5430. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5431. {
  5432. while (1) {
  5433. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5434. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5435. if (end) {
  5436. *size = end - val;
  5437. return val;
  5438. }
  5439. if (*val == '\0')
  5440. return NULL;
  5441. /* Optimization: if "*pat" did not match the start of "string",
  5442. * we know that "tring", "ring" etc will not match too:
  5443. */
  5444. if (pattern[0] == '*')
  5445. return NULL;
  5446. val++;
  5447. }
  5448. }
  5449. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5450. {
  5451. char *result = NULL;
  5452. unsigned res_len = 0;
  5453. unsigned repl_len = strlen(repl);
  5454. /* Null pattern never matches, including if "var" is empty */
  5455. if (!pattern[0])
  5456. return result; /* NULL, no replaces happened */
  5457. while (1) {
  5458. int size;
  5459. char *s = strstr_pattern(val, pattern, &size);
  5460. if (!s)
  5461. break;
  5462. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5463. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5464. res_len += (s - val) + repl_len;
  5465. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5466. val = s + size;
  5467. if (exp_op == '/')
  5468. break;
  5469. }
  5470. if (*val && result) {
  5471. result = xrealloc(result, res_len + strlen(val) + 1);
  5472. strcpy(result + res_len, val);
  5473. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5474. }
  5475. debug_printf_varexp("result:'%s'\n", result);
  5476. return result;
  5477. }
  5478. #endif /* BASH_PATTERN_SUBST */
  5479. /* Helper:
  5480. * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5481. */
  5482. static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
  5483. {
  5484. const char *val;
  5485. char *to_be_freed;
  5486. char *p;
  5487. char *var;
  5488. char first_char;
  5489. char exp_op;
  5490. char exp_save = exp_save; /* for compiler */
  5491. char *exp_saveptr; /* points to expansion operator */
  5492. char *exp_word = exp_word; /* for compiler */
  5493. char arg0;
  5494. val = NULL;
  5495. to_be_freed = NULL;
  5496. p = *pp;
  5497. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5498. var = arg;
  5499. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5500. arg0 = arg[0];
  5501. first_char = arg[0] = arg0 & 0x7f;
  5502. exp_op = 0;
  5503. if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
  5504. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5505. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5506. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5507. ) {
  5508. /* It must be length operator: ${#var} */
  5509. var++;
  5510. exp_op = 'L';
  5511. } else {
  5512. /* Maybe handle parameter expansion */
  5513. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5514. && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
  5515. ) {
  5516. /* ${?:0}, ${#[:]%0} etc */
  5517. exp_saveptr = var + 1;
  5518. } else {
  5519. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5520. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5521. }
  5522. exp_op = exp_save = *exp_saveptr;
  5523. if (exp_op) {
  5524. exp_word = exp_saveptr + 1;
  5525. if (exp_op == ':') {
  5526. exp_op = *exp_word++;
  5527. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5528. if (BASH_SUBSTR
  5529. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5530. ) {
  5531. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5532. exp_op = ':';
  5533. exp_word--;
  5534. }
  5535. }
  5536. *exp_saveptr = '\0';
  5537. } /* else: it's not an expansion op, but bare ${var} */
  5538. }
  5539. /* Look up the variable in question */
  5540. if (isdigit(var[0])) {
  5541. /* parse_dollar should have vetted var for us */
  5542. int n = xatoi_positive(var);
  5543. if (n < G.global_argc)
  5544. val = G.global_argv[n];
  5545. /* else val remains NULL: $N with too big N */
  5546. } else {
  5547. switch (var[0]) {
  5548. case '$': /* pid */
  5549. val = utoa(G.root_pid);
  5550. break;
  5551. case '!': /* bg pid */
  5552. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  5553. break;
  5554. case '?': /* exitcode */
  5555. val = utoa(G.last_exitcode);
  5556. break;
  5557. case '#': /* argc */
  5558. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  5559. break;
  5560. default:
  5561. val = get_local_var_value(var);
  5562. }
  5563. }
  5564. /* Handle any expansions */
  5565. if (exp_op == 'L') {
  5566. reinit_unicode_for_hush();
  5567. debug_printf_expand("expand: length(%s)=", val);
  5568. val = utoa(val ? unicode_strlen(val) : 0);
  5569. debug_printf_expand("%s\n", val);
  5570. } else if (exp_op) {
  5571. if (exp_op == '%' || exp_op == '#') {
  5572. /* Standard-mandated substring removal ops:
  5573. * ${parameter%word} - remove smallest suffix pattern
  5574. * ${parameter%%word} - remove largest suffix pattern
  5575. * ${parameter#word} - remove smallest prefix pattern
  5576. * ${parameter##word} - remove largest prefix pattern
  5577. *
  5578. * Word is expanded to produce a glob pattern.
  5579. * Then var's value is matched to it and matching part removed.
  5580. */
  5581. if (val && val[0]) {
  5582. char *t;
  5583. char *exp_exp_word;
  5584. char *loc;
  5585. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  5586. if (exp_op == *exp_word) /* ## or %% */
  5587. exp_word++;
  5588. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  5589. /*
  5590. * process_bkslash:1 unbackslash:1 breaks this:
  5591. * a='a\\'; echo ${a%\\\\} # correct output is: a
  5592. * process_bkslash:1 unbackslash:0 breaks this:
  5593. * a='a}'; echo ${a%\}} # correct output is: a
  5594. */
  5595. exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
  5596. if (exp_exp_word)
  5597. exp_word = exp_exp_word;
  5598. debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
  5599. /* HACK ALERT. We depend here on the fact that
  5600. * G.global_argv and results of utoa and get_local_var_value
  5601. * are actually in writable memory:
  5602. * scan_and_match momentarily stores NULs there. */
  5603. t = (char*)val;
  5604. loc = scan_and_match(t, exp_word, scan_flags);
  5605. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  5606. free(exp_exp_word);
  5607. if (loc) { /* match was found */
  5608. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  5609. val = loc; /* take right part */
  5610. else /* %[%] */
  5611. val = to_be_freed = xstrndup(val, loc - val); /* left */
  5612. }
  5613. }
  5614. }
  5615. #if BASH_PATTERN_SUBST
  5616. else if (exp_op == '/' || exp_op == '\\') {
  5617. /* It's ${var/[/]pattern[/repl]} thing.
  5618. * Note that in encoded form it has TWO parts:
  5619. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  5620. * and if // is used, it is encoded as \:
  5621. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  5622. */
  5623. if (val && val[0]) {
  5624. /* pattern uses non-standard expansion.
  5625. * repl should be unbackslashed and globbed
  5626. * by the usual expansion rules:
  5627. * >az >bz
  5628. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  5629. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  5630. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  5631. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  5632. * (note that a*z _pattern_ is never globbed!)
  5633. */
  5634. char *pattern, *repl, *t;
  5635. pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
  5636. if (!pattern)
  5637. pattern = xstrdup(exp_word);
  5638. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  5639. *p++ = SPECIAL_VAR_SYMBOL;
  5640. exp_word = p;
  5641. p = strchr(p, SPECIAL_VAR_SYMBOL);
  5642. *p = '\0';
  5643. repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 1);
  5644. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  5645. /* HACK ALERT. We depend here on the fact that
  5646. * G.global_argv and results of utoa and get_local_var_value
  5647. * are actually in writable memory:
  5648. * replace_pattern momentarily stores NULs there. */
  5649. t = (char*)val;
  5650. to_be_freed = replace_pattern(t,
  5651. pattern,
  5652. (repl ? repl : exp_word),
  5653. exp_op);
  5654. if (to_be_freed) /* at least one replace happened */
  5655. val = to_be_freed;
  5656. free(pattern);
  5657. free(repl);
  5658. } else {
  5659. /* Empty variable always gives nothing */
  5660. // "v=''; echo ${v/*/w}" prints "", not "w"
  5661. /* Just skip "replace" part */
  5662. *p++ = SPECIAL_VAR_SYMBOL;
  5663. p = strchr(p, SPECIAL_VAR_SYMBOL);
  5664. *p = '\0';
  5665. }
  5666. }
  5667. #endif /* BASH_PATTERN_SUBST */
  5668. else if (exp_op == ':') {
  5669. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  5670. /* It's ${var:N[:M]} bashism.
  5671. * Note that in encoded form it has TWO parts:
  5672. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  5673. */
  5674. arith_t beg, len;
  5675. const char *errmsg;
  5676. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  5677. if (errmsg)
  5678. goto arith_err;
  5679. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  5680. *p++ = SPECIAL_VAR_SYMBOL;
  5681. exp_word = p;
  5682. p = strchr(p, SPECIAL_VAR_SYMBOL);
  5683. *p = '\0';
  5684. len = expand_and_evaluate_arith(exp_word, &errmsg);
  5685. if (errmsg)
  5686. goto arith_err;
  5687. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  5688. if (beg < 0) {
  5689. /* negative beg counts from the end */
  5690. beg = (arith_t)strlen(val) + beg;
  5691. if (beg < 0) /* ${v: -999999} is "" */
  5692. beg = len = 0;
  5693. }
  5694. debug_printf_varexp("from val:'%s'\n", val);
  5695. if (len < 0) {
  5696. /* in bash, len=-n means strlen()-n */
  5697. len = (arith_t)strlen(val) - beg + len;
  5698. if (len < 0) /* bash compat */
  5699. msg_and_die_if_script("%s: substring expression < 0", var);
  5700. }
  5701. if (len <= 0 || !val || beg >= strlen(val)) {
  5702. arith_err:
  5703. val = NULL;
  5704. } else {
  5705. /* Paranoia. What if user entered 9999999999999
  5706. * which fits in arith_t but not int? */
  5707. if (len >= INT_MAX)
  5708. len = INT_MAX;
  5709. val = to_be_freed = xstrndup(val + beg, len);
  5710. }
  5711. debug_printf_varexp("val:'%s'\n", val);
  5712. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  5713. msg_and_die_if_script("malformed ${%s:...}", var);
  5714. val = NULL;
  5715. #endif
  5716. } else { /* one of "-=+?" */
  5717. /* Standard-mandated substitution ops:
  5718. * ${var?word} - indicate error if unset
  5719. * If var is unset, word (or a message indicating it is unset
  5720. * if word is null) is written to standard error
  5721. * and the shell exits with a non-zero exit status.
  5722. * Otherwise, the value of var is substituted.
  5723. * ${var-word} - use default value
  5724. * If var is unset, word is substituted.
  5725. * ${var=word} - assign and use default value
  5726. * If var is unset, word is assigned to var.
  5727. * In all cases, final value of var is substituted.
  5728. * ${var+word} - use alternative value
  5729. * If var is unset, null is substituted.
  5730. * Otherwise, word is substituted.
  5731. *
  5732. * Word is subjected to tilde expansion, parameter expansion,
  5733. * command substitution, and arithmetic expansion.
  5734. * If word is not needed, it is not expanded.
  5735. *
  5736. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  5737. * but also treat null var as if it is unset.
  5738. */
  5739. int use_word = (!val || ((exp_save == ':') && !val[0]));
  5740. if (exp_op == '+')
  5741. use_word = !use_word;
  5742. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  5743. (exp_save == ':') ? "true" : "false", use_word);
  5744. if (use_word) {
  5745. to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  5746. if (to_be_freed)
  5747. exp_word = to_be_freed;
  5748. if (exp_op == '?') {
  5749. /* mimic bash message */
  5750. msg_and_die_if_script("%s: %s",
  5751. var,
  5752. exp_word[0]
  5753. ? exp_word
  5754. : "parameter null or not set"
  5755. /* ash has more specific messages, a-la: */
  5756. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  5757. );
  5758. //TODO: how interactive bash aborts expansion mid-command?
  5759. } else {
  5760. val = exp_word;
  5761. }
  5762. if (exp_op == '=') {
  5763. /* ${var=[word]} or ${var:=[word]} */
  5764. if (isdigit(var[0]) || var[0] == '#') {
  5765. /* mimic bash message */
  5766. msg_and_die_if_script("$%s: cannot assign in this way", var);
  5767. val = NULL;
  5768. } else {
  5769. char *new_var = xasprintf("%s=%s", var, val);
  5770. set_local_var(new_var, /*flag:*/ 0);
  5771. }
  5772. }
  5773. }
  5774. } /* one of "-=+?" */
  5775. *exp_saveptr = exp_save;
  5776. } /* if (exp_op) */
  5777. arg[0] = arg0;
  5778. *pp = p;
  5779. *to_be_freed_pp = to_be_freed;
  5780. return val;
  5781. }
  5782. /* Expand all variable references in given string, adding words to list[]
  5783. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  5784. * to be filled). This routine is extremely tricky: has to deal with
  5785. * variables/parameters with whitespace, $* and $@, and constructs like
  5786. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  5787. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  5788. {
  5789. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  5790. * expansion of right-hand side of assignment == 1-element expand.
  5791. */
  5792. char cant_be_null = 0; /* only bit 0x80 matters */
  5793. int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
  5794. char *p;
  5795. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  5796. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  5797. debug_print_list("expand_vars_to_list", output, n);
  5798. n = o_save_ptr(output, n);
  5799. debug_print_list("expand_vars_to_list[0]", output, n);
  5800. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  5801. char first_ch;
  5802. char *to_be_freed = NULL;
  5803. const char *val = NULL;
  5804. #if ENABLE_HUSH_TICK
  5805. o_string subst_result = NULL_O_STRING;
  5806. #endif
  5807. #if ENABLE_FEATURE_SH_MATH
  5808. char arith_buf[sizeof(arith_t)*3 + 2];
  5809. #endif
  5810. if (ended_in_ifs) {
  5811. o_addchr(output, '\0');
  5812. n = o_save_ptr(output, n);
  5813. ended_in_ifs = 0;
  5814. }
  5815. o_addblock(output, arg, p - arg);
  5816. debug_print_list("expand_vars_to_list[1]", output, n);
  5817. arg = ++p;
  5818. p = strchr(p, SPECIAL_VAR_SYMBOL);
  5819. /* Fetch special var name (if it is indeed one of them)
  5820. * and quote bit, force the bit on if singleword expansion -
  5821. * important for not getting v=$@ expand to many words. */
  5822. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  5823. /* Is this variable quoted and thus expansion can't be null?
  5824. * "$@" is special. Even if quoted, it can still
  5825. * expand to nothing (not even an empty string),
  5826. * thus it is excluded. */
  5827. if ((first_ch & 0x7f) != '@')
  5828. cant_be_null |= first_ch;
  5829. switch (first_ch & 0x7f) {
  5830. /* Highest bit in first_ch indicates that var is double-quoted */
  5831. case '*':
  5832. case '@': {
  5833. int i;
  5834. if (!G.global_argv[1])
  5835. break;
  5836. i = 1;
  5837. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  5838. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  5839. while (G.global_argv[i]) {
  5840. n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
  5841. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  5842. if (G.global_argv[i++][0] && G.global_argv[i]) {
  5843. /* this argv[] is not empty and not last:
  5844. * put terminating NUL, start new word */
  5845. o_addchr(output, '\0');
  5846. debug_print_list("expand_vars_to_list[2]", output, n);
  5847. n = o_save_ptr(output, n);
  5848. debug_print_list("expand_vars_to_list[3]", output, n);
  5849. }
  5850. }
  5851. } else
  5852. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  5853. * and in this case should treat it like '$*' - see 'else...' below */
  5854. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  5855. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  5856. ) {
  5857. while (1) {
  5858. o_addQstr(output, G.global_argv[i]);
  5859. if (++i >= G.global_argc)
  5860. break;
  5861. o_addchr(output, '\0');
  5862. debug_print_list("expand_vars_to_list[4]", output, n);
  5863. n = o_save_ptr(output, n);
  5864. }
  5865. } else { /* quoted $* (or v="$@" case): add as one word */
  5866. while (1) {
  5867. o_addQstr(output, G.global_argv[i]);
  5868. if (!G.global_argv[++i])
  5869. break;
  5870. if (G.ifs[0])
  5871. o_addchr(output, G.ifs[0]);
  5872. }
  5873. output->has_quoted_part = 1;
  5874. }
  5875. break;
  5876. }
  5877. case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  5878. /* "Empty variable", used to make "" etc to not disappear */
  5879. output->has_quoted_part = 1;
  5880. arg++;
  5881. cant_be_null = 0x80;
  5882. break;
  5883. case SPECIAL_VAR_QUOTED_SVS:
  5884. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  5885. arg++;
  5886. val = SPECIAL_VAR_SYMBOL_STR;
  5887. break;
  5888. #if ENABLE_HUSH_TICK
  5889. case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  5890. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5891. arg++;
  5892. /* Can't just stuff it into output o_string,
  5893. * expanded result may need to be globbed
  5894. * and $IFS-split */
  5895. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  5896. G.last_exitcode = process_command_subs(&subst_result, arg);
  5897. G.expand_exitcode = G.last_exitcode;
  5898. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  5899. val = subst_result.data;
  5900. goto store_val;
  5901. #endif
  5902. #if ENABLE_FEATURE_SH_MATH
  5903. case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
  5904. arith_t res;
  5905. arg++; /* skip '+' */
  5906. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5907. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  5908. res = expand_and_evaluate_arith(arg, NULL);
  5909. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  5910. sprintf(arith_buf, ARITH_FMT, res);
  5911. val = arith_buf;
  5912. break;
  5913. }
  5914. #endif
  5915. default:
  5916. val = expand_one_var(&to_be_freed, arg, &p);
  5917. IF_HUSH_TICK(store_val:)
  5918. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5919. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5920. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5921. if (val && val[0]) {
  5922. n = expand_on_ifs(&ended_in_ifs, output, n, val);
  5923. val = NULL;
  5924. }
  5925. } else { /* quoted $VAR, val will be appended below */
  5926. output->has_quoted_part = 1;
  5927. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5928. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5929. }
  5930. break;
  5931. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  5932. if (val && val[0]) {
  5933. o_addQstr(output, val);
  5934. }
  5935. free(to_be_freed);
  5936. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  5937. * Do the check to avoid writing to a const string. */
  5938. if (*p != SPECIAL_VAR_SYMBOL)
  5939. *p = SPECIAL_VAR_SYMBOL;
  5940. #if ENABLE_HUSH_TICK
  5941. o_free(&subst_result);
  5942. #endif
  5943. arg = ++p;
  5944. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  5945. if (arg[0]) {
  5946. if (ended_in_ifs) {
  5947. o_addchr(output, '\0');
  5948. n = o_save_ptr(output, n);
  5949. }
  5950. debug_print_list("expand_vars_to_list[a]", output, n);
  5951. /* this part is literal, and it was already pre-quoted
  5952. * if needed (much earlier), do not use o_addQstr here! */
  5953. o_addstr_with_NUL(output, arg);
  5954. debug_print_list("expand_vars_to_list[b]", output, n);
  5955. } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  5956. && !(cant_be_null & 0x80) /* and all vars were not quoted. */
  5957. ) {
  5958. n--;
  5959. /* allow to reuse list[n] later without re-growth */
  5960. output->has_empty_slot = 1;
  5961. } else {
  5962. o_addchr(output, '\0');
  5963. }
  5964. return n;
  5965. }
  5966. static char **expand_variables(char **argv, unsigned expflags)
  5967. {
  5968. int n;
  5969. char **list;
  5970. o_string output = NULL_O_STRING;
  5971. output.o_expflags = expflags;
  5972. n = 0;
  5973. while (*argv) {
  5974. n = expand_vars_to_list(&output, n, *argv);
  5975. argv++;
  5976. }
  5977. debug_print_list("expand_variables", &output, n);
  5978. /* output.data (malloced in one block) gets returned in "list" */
  5979. list = o_finalize_list(&output, n);
  5980. debug_print_strings("expand_variables[1]", list);
  5981. return list;
  5982. }
  5983. static char **expand_strvec_to_strvec(char **argv)
  5984. {
  5985. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  5986. }
  5987. #if defined(CMD_SINGLEWORD_NOGLOB)
  5988. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  5989. {
  5990. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  5991. }
  5992. #endif
  5993. /* Used for expansion of right hand of assignments,
  5994. * $((...)), heredocs, variable expansion parts.
  5995. *
  5996. * NB: should NOT do globbing!
  5997. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  5998. */
  5999. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6000. {
  6001. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6002. const int do_unbackslash = 1;
  6003. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6004. #endif
  6005. char *argv[2], **list;
  6006. debug_printf_expand("string_to_string<='%s'\n", str);
  6007. /* This is generally an optimization, but it also
  6008. * handles "", which otherwise trips over !list[0] check below.
  6009. * (is this ever happens that we actually get str="" here?)
  6010. */
  6011. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6012. //TODO: Can use on strings with \ too, just unbackslash() them?
  6013. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6014. return xstrdup(str);
  6015. }
  6016. argv[0] = (char*)str;
  6017. argv[1] = NULL;
  6018. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6019. if (HUSH_DEBUG)
  6020. if (!list[0] || list[1])
  6021. bb_error_msg_and_die("BUG in varexp2");
  6022. /* actually, just move string 2*sizeof(char*) bytes back */
  6023. overlapping_strcpy((char*)list, list[0]);
  6024. if (do_unbackslash)
  6025. unbackslash((char*)list);
  6026. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6027. return (char*)list;
  6028. }
  6029. #if 0
  6030. static char* expand_strvec_to_string(char **argv)
  6031. {
  6032. char **list;
  6033. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6034. /* Convert all NULs to spaces */
  6035. if (list[0]) {
  6036. int n = 1;
  6037. while (list[n]) {
  6038. if (HUSH_DEBUG)
  6039. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6040. bb_error_msg_and_die("BUG in varexp3");
  6041. /* bash uses ' ' regardless of $IFS contents */
  6042. list[n][-1] = ' ';
  6043. n++;
  6044. }
  6045. }
  6046. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6047. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6048. return (char*)list;
  6049. }
  6050. #endif
  6051. static char **expand_assignments(char **argv, int count)
  6052. {
  6053. int i;
  6054. char **p;
  6055. G.expanded_assignments = p = NULL;
  6056. /* Expand assignments into one string each */
  6057. for (i = 0; i < count; i++) {
  6058. p = add_string_to_strings(p,
  6059. expand_string_to_string(argv[i],
  6060. EXP_FLAG_ESC_GLOB_CHARS,
  6061. /*unbackslash:*/ 1
  6062. )
  6063. );
  6064. G.expanded_assignments = p;
  6065. }
  6066. G.expanded_assignments = NULL;
  6067. return p;
  6068. }
  6069. static void switch_off_special_sigs(unsigned mask)
  6070. {
  6071. unsigned sig = 0;
  6072. while ((mask >>= 1) != 0) {
  6073. sig++;
  6074. if (!(mask & 1))
  6075. continue;
  6076. #if ENABLE_HUSH_TRAP
  6077. if (G_traps) {
  6078. if (G_traps[sig] && !G_traps[sig][0])
  6079. /* trap is '', has to remain SIG_IGN */
  6080. continue;
  6081. free(G_traps[sig]);
  6082. G_traps[sig] = NULL;
  6083. }
  6084. #endif
  6085. /* We are here only if no trap or trap was not '' */
  6086. install_sighandler(sig, SIG_DFL);
  6087. }
  6088. }
  6089. #if BB_MMU
  6090. /* never called */
  6091. void re_execute_shell(char ***to_free, const char *s,
  6092. char *g_argv0, char **g_argv,
  6093. char **builtin_argv) NORETURN;
  6094. static void reset_traps_to_defaults(void)
  6095. {
  6096. /* This function is always called in a child shell
  6097. * after fork (not vfork, NOMMU doesn't use this function).
  6098. */
  6099. IF_HUSH_TRAP(unsigned sig;)
  6100. unsigned mask;
  6101. /* Child shells are not interactive.
  6102. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6103. * Testcase: (while :; do :; done) + ^Z should background.
  6104. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6105. */
  6106. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6107. if (!G_traps && !mask)
  6108. return; /* already no traps and no special sigs */
  6109. /* Switch off special sigs */
  6110. switch_off_special_sigs(mask);
  6111. # if ENABLE_HUSH_JOB
  6112. G_fatal_sig_mask = 0;
  6113. # endif
  6114. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6115. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6116. * remain set in G.special_sig_mask */
  6117. # if ENABLE_HUSH_TRAP
  6118. if (!G_traps)
  6119. return;
  6120. /* Reset all sigs to default except ones with empty traps */
  6121. for (sig = 0; sig < NSIG; sig++) {
  6122. if (!G_traps[sig])
  6123. continue; /* no trap: nothing to do */
  6124. if (!G_traps[sig][0])
  6125. continue; /* empty trap: has to remain SIG_IGN */
  6126. /* sig has non-empty trap, reset it: */
  6127. free(G_traps[sig]);
  6128. G_traps[sig] = NULL;
  6129. /* There is no signal for trap 0 (EXIT) */
  6130. if (sig == 0)
  6131. continue;
  6132. install_sighandler(sig, pick_sighandler(sig));
  6133. }
  6134. # endif
  6135. }
  6136. #else /* !BB_MMU */
  6137. static void re_execute_shell(char ***to_free, const char *s,
  6138. char *g_argv0, char **g_argv,
  6139. char **builtin_argv) NORETURN;
  6140. static void re_execute_shell(char ***to_free, const char *s,
  6141. char *g_argv0, char **g_argv,
  6142. char **builtin_argv)
  6143. {
  6144. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6145. /* delims + 2 * (number of bytes in printed hex numbers) */
  6146. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6147. char *heredoc_argv[4];
  6148. struct variable *cur;
  6149. # if ENABLE_HUSH_FUNCTIONS
  6150. struct function *funcp;
  6151. # endif
  6152. char **argv, **pp;
  6153. unsigned cnt;
  6154. unsigned long long empty_trap_mask;
  6155. if (!g_argv0) { /* heredoc */
  6156. argv = heredoc_argv;
  6157. argv[0] = (char *) G.argv0_for_re_execing;
  6158. argv[1] = (char *) "-<";
  6159. argv[2] = (char *) s;
  6160. argv[3] = NULL;
  6161. pp = &argv[3]; /* used as pointer to empty environment */
  6162. goto do_exec;
  6163. }
  6164. cnt = 0;
  6165. pp = builtin_argv;
  6166. if (pp) while (*pp++)
  6167. cnt++;
  6168. empty_trap_mask = 0;
  6169. if (G_traps) {
  6170. int sig;
  6171. for (sig = 1; sig < NSIG; sig++) {
  6172. if (G_traps[sig] && !G_traps[sig][0])
  6173. empty_trap_mask |= 1LL << sig;
  6174. }
  6175. }
  6176. sprintf(param_buf, NOMMU_HACK_FMT
  6177. , (unsigned) G.root_pid
  6178. , (unsigned) G.root_ppid
  6179. , (unsigned) G.last_bg_pid
  6180. , (unsigned) G.last_exitcode
  6181. , cnt
  6182. , empty_trap_mask
  6183. IF_HUSH_LOOPS(, G.depth_of_loop)
  6184. );
  6185. # undef NOMMU_HACK_FMT
  6186. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6187. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6188. */
  6189. cnt += 6;
  6190. for (cur = G.top_var; cur; cur = cur->next) {
  6191. if (!cur->flg_export || cur->flg_read_only)
  6192. cnt += 2;
  6193. }
  6194. # if ENABLE_HUSH_FUNCTIONS
  6195. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6196. cnt += 3;
  6197. # endif
  6198. pp = g_argv;
  6199. while (*pp++)
  6200. cnt++;
  6201. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6202. *pp++ = (char *) G.argv0_for_re_execing;
  6203. *pp++ = param_buf;
  6204. for (cur = G.top_var; cur; cur = cur->next) {
  6205. if (strcmp(cur->varstr, hush_version_str) == 0)
  6206. continue;
  6207. if (cur->flg_read_only) {
  6208. *pp++ = (char *) "-R";
  6209. *pp++ = cur->varstr;
  6210. } else if (!cur->flg_export) {
  6211. *pp++ = (char *) "-V";
  6212. *pp++ = cur->varstr;
  6213. }
  6214. }
  6215. # if ENABLE_HUSH_FUNCTIONS
  6216. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6217. *pp++ = (char *) "-F";
  6218. *pp++ = funcp->name;
  6219. *pp++ = funcp->body_as_string;
  6220. }
  6221. # endif
  6222. /* We can pass activated traps here. Say, -Tnn:trap_string
  6223. *
  6224. * However, POSIX says that subshells reset signals with traps
  6225. * to SIG_DFL.
  6226. * I tested bash-3.2 and it not only does that with true subshells
  6227. * of the form ( list ), but with any forked children shells.
  6228. * I set trap "echo W" WINCH; and then tried:
  6229. *
  6230. * { echo 1; sleep 20; echo 2; } &
  6231. * while true; do echo 1; sleep 20; echo 2; break; done &
  6232. * true | { echo 1; sleep 20; echo 2; } | cat
  6233. *
  6234. * In all these cases sending SIGWINCH to the child shell
  6235. * did not run the trap. If I add trap "echo V" WINCH;
  6236. * _inside_ group (just before echo 1), it works.
  6237. *
  6238. * I conclude it means we don't need to pass active traps here.
  6239. */
  6240. *pp++ = (char *) "-c";
  6241. *pp++ = (char *) s;
  6242. if (builtin_argv) {
  6243. while (*++builtin_argv)
  6244. *pp++ = *builtin_argv;
  6245. *pp++ = (char *) "";
  6246. }
  6247. *pp++ = g_argv0;
  6248. while (*g_argv)
  6249. *pp++ = *g_argv++;
  6250. /* *pp = NULL; - is already there */
  6251. pp = environ;
  6252. do_exec:
  6253. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6254. /* Don't propagate SIG_IGN to the child */
  6255. if (SPECIAL_JOBSTOP_SIGS != 0)
  6256. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6257. execve(bb_busybox_exec_path, argv, pp);
  6258. /* Fallback. Useful for init=/bin/hush usage etc */
  6259. if (argv[0][0] == '/')
  6260. execve(argv[0], argv, pp);
  6261. xfunc_error_retval = 127;
  6262. bb_error_msg_and_die("can't re-execute the shell");
  6263. }
  6264. #endif /* !BB_MMU */
  6265. static int run_and_free_list(struct pipe *pi);
  6266. /* Executing from string: eval, sh -c '...'
  6267. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6268. * end_trigger controls how often we stop parsing
  6269. * NUL: parse all, execute, return
  6270. * ';': parse till ';' or newline, execute, repeat till EOF
  6271. */
  6272. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6273. {
  6274. /* Why we need empty flag?
  6275. * An obscure corner case "false; ``; echo $?":
  6276. * empty command in `` should still set $? to 0.
  6277. * But we can't just set $? to 0 at the start,
  6278. * this breaks "false; echo `echo $?`" case.
  6279. */
  6280. bool empty = 1;
  6281. while (1) {
  6282. struct pipe *pipe_list;
  6283. #if ENABLE_HUSH_INTERACTIVE
  6284. if (end_trigger == ';') {
  6285. G.promptmode = 0; /* PS1 */
  6286. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6287. }
  6288. #endif
  6289. pipe_list = parse_stream(NULL, inp, end_trigger);
  6290. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6291. /* If we are in "big" script
  6292. * (not in `cmd` or something similar)...
  6293. */
  6294. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6295. /* Discard cached input (rest of line) */
  6296. int ch = inp->last_char;
  6297. while (ch != EOF && ch != '\n') {
  6298. //bb_error_msg("Discarded:'%c'", ch);
  6299. ch = i_getch(inp);
  6300. }
  6301. /* Force prompt */
  6302. inp->p = NULL;
  6303. /* This stream isn't empty */
  6304. empty = 0;
  6305. continue;
  6306. }
  6307. if (!pipe_list && empty)
  6308. G.last_exitcode = 0;
  6309. break;
  6310. }
  6311. debug_print_tree(pipe_list, 0);
  6312. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6313. run_and_free_list(pipe_list);
  6314. empty = 0;
  6315. if (G_flag_return_in_progress == 1)
  6316. break;
  6317. }
  6318. }
  6319. static void parse_and_run_string(const char *s)
  6320. {
  6321. struct in_str input;
  6322. //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6323. setup_string_in_str(&input, s);
  6324. parse_and_run_stream(&input, '\0');
  6325. //IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6326. }
  6327. static void parse_and_run_file(FILE *f)
  6328. {
  6329. struct in_str input;
  6330. IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6331. IF_HUSH_LINENO_VAR(G.lineno = 1;)
  6332. setup_file_in_str(&input, f);
  6333. parse_and_run_stream(&input, ';');
  6334. IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6335. }
  6336. #if ENABLE_HUSH_TICK
  6337. static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
  6338. {
  6339. pid_t pid;
  6340. int channel[2];
  6341. # if !BB_MMU
  6342. char **to_free = NULL;
  6343. # endif
  6344. xpipe(channel);
  6345. pid = BB_MMU ? xfork() : xvfork();
  6346. if (pid == 0) { /* child */
  6347. disable_restore_tty_pgrp_on_exit();
  6348. /* Process substitution is not considered to be usual
  6349. * 'command execution'.
  6350. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6351. */
  6352. bb_signals(0
  6353. + (1 << SIGTSTP)
  6354. + (1 << SIGTTIN)
  6355. + (1 << SIGTTOU)
  6356. , SIG_IGN);
  6357. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6358. close(channel[0]); /* NB: close _first_, then move fd! */
  6359. xmove_fd(channel[1], 1);
  6360. /* Prevent it from trying to handle ctrl-z etc */
  6361. IF_HUSH_JOB(G.run_list_level = 1;)
  6362. # if ENABLE_HUSH_TRAP
  6363. /* Awful hack for `trap` or $(trap).
  6364. *
  6365. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6366. * contains an example where "trap" is executed in a subshell:
  6367. *
  6368. * save_traps=$(trap)
  6369. * ...
  6370. * eval "$save_traps"
  6371. *
  6372. * Standard does not say that "trap" in subshell shall print
  6373. * parent shell's traps. It only says that its output
  6374. * must have suitable form, but then, in the above example
  6375. * (which is not supposed to be normative), it implies that.
  6376. *
  6377. * bash (and probably other shell) does implement it
  6378. * (traps are reset to defaults, but "trap" still shows them),
  6379. * but as a result, "trap" logic is hopelessly messed up:
  6380. *
  6381. * # trap
  6382. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6383. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6384. * # true | trap <--- trap is in subshell - no output (ditto)
  6385. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6386. * trap -- 'echo Ho' SIGWINCH
  6387. * # echo `(trap)` <--- in subshell in subshell - output
  6388. * trap -- 'echo Ho' SIGWINCH
  6389. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6390. * trap -- 'echo Ho' SIGWINCH
  6391. *
  6392. * The rules when to forget and when to not forget traps
  6393. * get really complex and nonsensical.
  6394. *
  6395. * Our solution: ONLY bare $(trap) or `trap` is special.
  6396. */
  6397. s = skip_whitespace(s);
  6398. if (is_prefixed_with(s, "trap")
  6399. && skip_whitespace(s + 4)[0] == '\0'
  6400. ) {
  6401. static const char *const argv[] = { NULL, NULL };
  6402. builtin_trap((char**)argv);
  6403. fflush_all(); /* important */
  6404. _exit(0);
  6405. }
  6406. # endif
  6407. # if BB_MMU
  6408. reset_traps_to_defaults();
  6409. parse_and_run_string(s);
  6410. _exit(G.last_exitcode);
  6411. # else
  6412. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6413. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6414. * huge=`cat BIG` # was blocking here forever
  6415. * echo OK
  6416. */
  6417. re_execute_shell(&to_free,
  6418. s,
  6419. G.global_argv[0],
  6420. G.global_argv + 1,
  6421. NULL);
  6422. # endif
  6423. }
  6424. /* parent */
  6425. *pid_p = pid;
  6426. # if ENABLE_HUSH_FAST
  6427. G.count_SIGCHLD++;
  6428. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6429. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6430. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6431. # endif
  6432. enable_restore_tty_pgrp_on_exit();
  6433. # if !BB_MMU
  6434. free(to_free);
  6435. # endif
  6436. close(channel[1]);
  6437. return remember_FILE(xfdopen_for_read(channel[0]));
  6438. }
  6439. /* Return code is exit status of the process that is run. */
  6440. static int process_command_subs(o_string *dest, const char *s)
  6441. {
  6442. FILE *fp;
  6443. pid_t pid;
  6444. int status, ch, eol_cnt;
  6445. fp = generate_stream_from_string(s, &pid);
  6446. /* Now send results of command back into original context */
  6447. eol_cnt = 0;
  6448. while ((ch = getc(fp)) != EOF) {
  6449. if (ch == '\0')
  6450. continue;
  6451. if (ch == '\n') {
  6452. eol_cnt++;
  6453. continue;
  6454. }
  6455. while (eol_cnt) {
  6456. o_addchr(dest, '\n');
  6457. eol_cnt--;
  6458. }
  6459. o_addQchr(dest, ch);
  6460. }
  6461. debug_printf("done reading from `cmd` pipe, closing it\n");
  6462. fclose_and_forget(fp);
  6463. /* We need to extract exitcode. Test case
  6464. * "true; echo `sleep 1; false` $?"
  6465. * should print 1 */
  6466. safe_waitpid(pid, &status, 0);
  6467. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6468. return WEXITSTATUS(status);
  6469. }
  6470. #endif /* ENABLE_HUSH_TICK */
  6471. static void setup_heredoc(struct redir_struct *redir)
  6472. {
  6473. struct fd_pair pair;
  6474. pid_t pid;
  6475. int len, written;
  6476. /* the _body_ of heredoc (misleading field name) */
  6477. const char *heredoc = redir->rd_filename;
  6478. char *expanded;
  6479. #if !BB_MMU
  6480. char **to_free;
  6481. #endif
  6482. expanded = NULL;
  6483. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6484. expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  6485. if (expanded)
  6486. heredoc = expanded;
  6487. }
  6488. len = strlen(heredoc);
  6489. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  6490. xpiped_pair(pair);
  6491. xmove_fd(pair.rd, redir->rd_fd);
  6492. /* Try writing without forking. Newer kernels have
  6493. * dynamically growing pipes. Must use non-blocking write! */
  6494. ndelay_on(pair.wr);
  6495. while (1) {
  6496. written = write(pair.wr, heredoc, len);
  6497. if (written <= 0)
  6498. break;
  6499. len -= written;
  6500. if (len == 0) {
  6501. close(pair.wr);
  6502. free(expanded);
  6503. return;
  6504. }
  6505. heredoc += written;
  6506. }
  6507. ndelay_off(pair.wr);
  6508. /* Okay, pipe buffer was not big enough */
  6509. /* Note: we must not create a stray child (bastard? :)
  6510. * for the unsuspecting parent process. Child creates a grandchild
  6511. * and exits before parent execs the process which consumes heredoc
  6512. * (that exec happens after we return from this function) */
  6513. #if !BB_MMU
  6514. to_free = NULL;
  6515. #endif
  6516. pid = xvfork();
  6517. if (pid == 0) {
  6518. /* child */
  6519. disable_restore_tty_pgrp_on_exit();
  6520. pid = BB_MMU ? xfork() : xvfork();
  6521. if (pid != 0)
  6522. _exit(0);
  6523. /* grandchild */
  6524. close(redir->rd_fd); /* read side of the pipe */
  6525. #if BB_MMU
  6526. full_write(pair.wr, heredoc, len); /* may loop or block */
  6527. _exit(0);
  6528. #else
  6529. /* Delegate blocking writes to another process */
  6530. xmove_fd(pair.wr, STDOUT_FILENO);
  6531. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  6532. #endif
  6533. }
  6534. /* parent */
  6535. #if ENABLE_HUSH_FAST
  6536. G.count_SIGCHLD++;
  6537. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6538. #endif
  6539. enable_restore_tty_pgrp_on_exit();
  6540. #if !BB_MMU
  6541. free(to_free);
  6542. #endif
  6543. close(pair.wr);
  6544. free(expanded);
  6545. wait(NULL); /* wait till child has died */
  6546. }
  6547. struct squirrel {
  6548. int orig_fd;
  6549. int moved_to;
  6550. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  6551. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  6552. };
  6553. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  6554. {
  6555. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  6556. sq[i].orig_fd = orig;
  6557. sq[i].moved_to = moved;
  6558. sq[i+1].orig_fd = -1; /* end marker */
  6559. return sq;
  6560. }
  6561. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  6562. {
  6563. int moved_to;
  6564. int i;
  6565. i = 0;
  6566. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  6567. /* If we collide with an already moved fd... */
  6568. if (fd == sq[i].moved_to) {
  6569. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  6570. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  6571. if (sq[i].moved_to < 0) /* what? */
  6572. xfunc_die();
  6573. return sq;
  6574. }
  6575. if (fd == sq[i].orig_fd) {
  6576. /* Example: echo Hello >/dev/null 1>&2 */
  6577. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  6578. return sq;
  6579. }
  6580. }
  6581. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  6582. moved_to = dup_CLOEXEC(fd, avoid_fd);
  6583. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  6584. if (moved_to < 0 && errno != EBADF)
  6585. xfunc_die();
  6586. return append_squirrel(sq, i, fd, moved_to);
  6587. }
  6588. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  6589. {
  6590. int i;
  6591. i = 0;
  6592. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  6593. /* If we collide with an already moved fd... */
  6594. if (fd == sq[i].orig_fd) {
  6595. /* Examples:
  6596. * "echo 3>FILE 3>&- 3>FILE"
  6597. * "echo 3>&- 3>FILE"
  6598. * No need for last redirect to insert
  6599. * another "need to close 3" indicator.
  6600. */
  6601. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  6602. return sq;
  6603. }
  6604. }
  6605. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  6606. return append_squirrel(sq, i, fd, -1);
  6607. }
  6608. /* fd: redirect wants this fd to be used (e.g. 3>file).
  6609. * Move all conflicting internally used fds,
  6610. * and remember them so that we can restore them later.
  6611. */
  6612. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  6613. {
  6614. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  6615. avoid_fd = 9;
  6616. #if ENABLE_HUSH_INTERACTIVE
  6617. if (fd == G.interactive_fd) {
  6618. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  6619. G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
  6620. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
  6621. return 1; /* "we closed fd" */
  6622. }
  6623. #endif
  6624. /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
  6625. * (1) Redirect in a forked child. No need to save FILEs' fds,
  6626. * we aren't going to use them anymore, ok to trash.
  6627. * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
  6628. * but how are we doing to restore them?
  6629. * "fileno(fd) = new_fd" can't be done.
  6630. */
  6631. if (!sqp)
  6632. return 0;
  6633. /* If this one of script's fds? */
  6634. if (save_FILEs_on_redirect(fd, avoid_fd))
  6635. return 1; /* yes. "we closed fd" */
  6636. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  6637. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  6638. return 0; /* "we did not close fd" */
  6639. }
  6640. static void restore_redirects(struct squirrel *sq)
  6641. {
  6642. if (sq) {
  6643. int i;
  6644. for (i = 0; sq[i].orig_fd >= 0; i++) {
  6645. if (sq[i].moved_to >= 0) {
  6646. /* We simply die on error */
  6647. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  6648. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  6649. } else {
  6650. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  6651. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  6652. close(sq[i].orig_fd);
  6653. }
  6654. }
  6655. free(sq);
  6656. }
  6657. /* If moved, G.interactive_fd stays on new fd, not restoring it */
  6658. restore_redirected_FILEs();
  6659. }
  6660. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  6661. static void close_saved_fds_and_FILE_fds(void)
  6662. {
  6663. if (G_interactive_fd)
  6664. close(G_interactive_fd);
  6665. close_all_FILE_list();
  6666. }
  6667. #endif
  6668. static int internally_opened_fd(int fd, struct squirrel *sq)
  6669. {
  6670. int i;
  6671. #if ENABLE_HUSH_INTERACTIVE
  6672. if (fd == G.interactive_fd)
  6673. return 1;
  6674. #endif
  6675. /* If this one of script's fds? */
  6676. if (fd_in_FILEs(fd))
  6677. return 1;
  6678. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  6679. if (fd == sq[i].moved_to)
  6680. return 1;
  6681. }
  6682. return 0;
  6683. }
  6684. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  6685. * and stderr if they are redirected. */
  6686. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  6687. {
  6688. struct redir_struct *redir;
  6689. for (redir = prog->redirects; redir; redir = redir->next) {
  6690. int newfd;
  6691. int closed;
  6692. if (redir->rd_type == REDIRECT_HEREDOC2) {
  6693. /* "rd_fd<<HERE" case */
  6694. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  6695. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  6696. * of the heredoc */
  6697. debug_printf_parse("set heredoc '%s'\n",
  6698. redir->rd_filename);
  6699. setup_heredoc(redir);
  6700. continue;
  6701. }
  6702. if (redir->rd_dup == REDIRFD_TO_FILE) {
  6703. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  6704. char *p;
  6705. int mode;
  6706. if (redir->rd_filename == NULL) {
  6707. /*
  6708. * Examples:
  6709. * "cmd >" (no filename)
  6710. * "cmd > <file" (2nd redirect starts too early)
  6711. */
  6712. syntax_error("invalid redirect");
  6713. continue;
  6714. }
  6715. mode = redir_table[redir->rd_type].mode;
  6716. p = expand_string_to_string(redir->rd_filename,
  6717. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  6718. newfd = open_or_warn(p, mode);
  6719. free(p);
  6720. if (newfd < 0) {
  6721. /* Error message from open_or_warn can be lost
  6722. * if stderr has been redirected, but bash
  6723. * and ash both lose it as well
  6724. * (though zsh doesn't!)
  6725. */
  6726. return 1;
  6727. }
  6728. if (newfd == redir->rd_fd && sqp) {
  6729. /* open() gave us precisely the fd we wanted.
  6730. * This means that this fd was not busy
  6731. * (not opened to anywhere).
  6732. * Remember to close it on restore:
  6733. */
  6734. *sqp = add_squirrel_closed(*sqp, newfd);
  6735. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  6736. }
  6737. } else {
  6738. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  6739. newfd = redir->rd_dup;
  6740. }
  6741. if (newfd == redir->rd_fd)
  6742. continue;
  6743. /* if "N>FILE": move newfd to redir->rd_fd */
  6744. /* if "N>&M": dup newfd to redir->rd_fd */
  6745. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  6746. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  6747. if (newfd == REDIRFD_CLOSE) {
  6748. /* "N>&-" means "close me" */
  6749. if (!closed) {
  6750. /* ^^^ optimization: saving may already
  6751. * have closed it. If not... */
  6752. close(redir->rd_fd);
  6753. }
  6754. /* Sometimes we do another close on restore, getting EBADF.
  6755. * Consider "echo 3>FILE 3>&-"
  6756. * first redirect remembers "need to close 3",
  6757. * and second redirect closes 3! Restore code then closes 3 again.
  6758. */
  6759. } else {
  6760. /* if newfd is a script fd or saved fd, simulate EBADF */
  6761. if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
  6762. //errno = EBADF;
  6763. //bb_perror_msg_and_die("can't duplicate file descriptor");
  6764. newfd = -1; /* same effect as code above */
  6765. }
  6766. xdup2(newfd, redir->rd_fd);
  6767. if (redir->rd_dup == REDIRFD_TO_FILE)
  6768. /* "rd_fd > FILE" */
  6769. close(newfd);
  6770. /* else: "rd_fd > rd_dup" */
  6771. }
  6772. }
  6773. return 0;
  6774. }
  6775. static char *find_in_path(const char *arg)
  6776. {
  6777. char *ret = NULL;
  6778. const char *PATH = get_local_var_value("PATH");
  6779. if (!PATH)
  6780. return NULL;
  6781. while (1) {
  6782. const char *end = strchrnul(PATH, ':');
  6783. int sz = end - PATH; /* must be int! */
  6784. free(ret);
  6785. if (sz != 0) {
  6786. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  6787. } else {
  6788. /* We have xxx::yyyy in $PATH,
  6789. * it means "use current dir" */
  6790. ret = xstrdup(arg);
  6791. }
  6792. if (access(ret, F_OK) == 0)
  6793. break;
  6794. if (*end == '\0') {
  6795. free(ret);
  6796. return NULL;
  6797. }
  6798. PATH = end + 1;
  6799. }
  6800. return ret;
  6801. }
  6802. static const struct built_in_command *find_builtin_helper(const char *name,
  6803. const struct built_in_command *x,
  6804. const struct built_in_command *end)
  6805. {
  6806. while (x != end) {
  6807. if (strcmp(name, x->b_cmd) != 0) {
  6808. x++;
  6809. continue;
  6810. }
  6811. debug_printf_exec("found builtin '%s'\n", name);
  6812. return x;
  6813. }
  6814. return NULL;
  6815. }
  6816. static const struct built_in_command *find_builtin1(const char *name)
  6817. {
  6818. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  6819. }
  6820. static const struct built_in_command *find_builtin(const char *name)
  6821. {
  6822. const struct built_in_command *x = find_builtin1(name);
  6823. if (x)
  6824. return x;
  6825. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  6826. }
  6827. static void remove_nested_vars(void)
  6828. {
  6829. struct variable *cur;
  6830. struct variable **cur_pp;
  6831. cur_pp = &G.top_var;
  6832. while ((cur = *cur_pp) != NULL) {
  6833. if (cur->var_nest_level <= G.var_nest_level) {
  6834. cur_pp = &cur->next;
  6835. continue;
  6836. }
  6837. /* Unexport */
  6838. if (cur->flg_export) {
  6839. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  6840. bb_unsetenv(cur->varstr);
  6841. }
  6842. /* Remove from global list */
  6843. *cur_pp = cur->next;
  6844. /* Free */
  6845. if (!cur->max_len) {
  6846. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  6847. free(cur->varstr);
  6848. }
  6849. free(cur);
  6850. }
  6851. }
  6852. static void enter_var_nest_level(void)
  6853. {
  6854. G.var_nest_level++;
  6855. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  6856. /* Try: f() { echo -n .; f; }; f
  6857. * struct variable::var_nest_level is uint16_t,
  6858. * thus limiting recursion to < 2^16.
  6859. * In any case, with 8 Mbyte stack SEGV happens
  6860. * not too long after 2^16 recursions anyway.
  6861. */
  6862. if (G.var_nest_level > 0xff00)
  6863. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  6864. }
  6865. static void leave_var_nest_level(void)
  6866. {
  6867. G.var_nest_level--;
  6868. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  6869. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  6870. bb_error_msg_and_die("BUG: nesting underflow");
  6871. remove_nested_vars();
  6872. }
  6873. #if ENABLE_HUSH_FUNCTIONS
  6874. static struct function **find_function_slot(const char *name)
  6875. {
  6876. struct function *funcp;
  6877. struct function **funcpp = &G.top_func;
  6878. while ((funcp = *funcpp) != NULL) {
  6879. if (strcmp(name, funcp->name) == 0) {
  6880. debug_printf_exec("found function '%s'\n", name);
  6881. break;
  6882. }
  6883. funcpp = &funcp->next;
  6884. }
  6885. return funcpp;
  6886. }
  6887. static ALWAYS_INLINE const struct function *find_function(const char *name)
  6888. {
  6889. const struct function *funcp = *find_function_slot(name);
  6890. return funcp;
  6891. }
  6892. /* Note: takes ownership on name ptr */
  6893. static struct function *new_function(char *name)
  6894. {
  6895. struct function **funcpp = find_function_slot(name);
  6896. struct function *funcp = *funcpp;
  6897. if (funcp != NULL) {
  6898. struct command *cmd = funcp->parent_cmd;
  6899. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  6900. if (!cmd) {
  6901. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  6902. free(funcp->name);
  6903. /* Note: if !funcp->body, do not free body_as_string!
  6904. * This is a special case of "-F name body" function:
  6905. * body_as_string was not malloced! */
  6906. if (funcp->body) {
  6907. free_pipe_list(funcp->body);
  6908. # if !BB_MMU
  6909. free(funcp->body_as_string);
  6910. # endif
  6911. }
  6912. } else {
  6913. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  6914. cmd->argv[0] = funcp->name;
  6915. cmd->group = funcp->body;
  6916. # if !BB_MMU
  6917. cmd->group_as_string = funcp->body_as_string;
  6918. # endif
  6919. }
  6920. } else {
  6921. debug_printf_exec("remembering new function '%s'\n", name);
  6922. funcp = *funcpp = xzalloc(sizeof(*funcp));
  6923. /*funcp->next = NULL;*/
  6924. }
  6925. funcp->name = name;
  6926. return funcp;
  6927. }
  6928. # if ENABLE_HUSH_UNSET
  6929. static void unset_func(const char *name)
  6930. {
  6931. struct function **funcpp = find_function_slot(name);
  6932. struct function *funcp = *funcpp;
  6933. if (funcp != NULL) {
  6934. debug_printf_exec("freeing function '%s'\n", funcp->name);
  6935. *funcpp = funcp->next;
  6936. /* funcp is unlinked now, deleting it.
  6937. * Note: if !funcp->body, the function was created by
  6938. * "-F name body", do not free ->body_as_string
  6939. * and ->name as they were not malloced. */
  6940. if (funcp->body) {
  6941. free_pipe_list(funcp->body);
  6942. free(funcp->name);
  6943. # if !BB_MMU
  6944. free(funcp->body_as_string);
  6945. # endif
  6946. }
  6947. free(funcp);
  6948. }
  6949. }
  6950. # endif
  6951. # if BB_MMU
  6952. #define exec_function(to_free, funcp, argv) \
  6953. exec_function(funcp, argv)
  6954. # endif
  6955. static void exec_function(char ***to_free,
  6956. const struct function *funcp,
  6957. char **argv) NORETURN;
  6958. static void exec_function(char ***to_free,
  6959. const struct function *funcp,
  6960. char **argv)
  6961. {
  6962. # if BB_MMU
  6963. int n;
  6964. argv[0] = G.global_argv[0];
  6965. G.global_argv = argv;
  6966. G.global_argc = n = 1 + string_array_len(argv + 1);
  6967. // Example when we are here: "cmd | func"
  6968. // func will run with saved-redirect fds open.
  6969. // $ f() { echo /proc/self/fd/*; }
  6970. // $ true | f
  6971. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  6972. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  6973. // Same in script:
  6974. // $ . ./SCRIPT
  6975. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  6976. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  6977. // They are CLOEXEC so external programs won't see them, but
  6978. // for "more correctness" we might want to close those extra fds here:
  6979. //? close_saved_fds_and_FILE_fds();
  6980. /* "we are in a function, ok to use return" */
  6981. G_flag_return_in_progress = -1;
  6982. enter_var_nest_level();
  6983. IF_HUSH_LOCAL(G.func_nest_level++;)
  6984. /* On MMU, funcp->body is always non-NULL */
  6985. n = run_list(funcp->body);
  6986. fflush_all();
  6987. _exit(n);
  6988. # else
  6989. //? close_saved_fds_and_FILE_fds();
  6990. //TODO: check whether "true | func_with_return" works
  6991. re_execute_shell(to_free,
  6992. funcp->body_as_string,
  6993. G.global_argv[0],
  6994. argv + 1,
  6995. NULL);
  6996. # endif
  6997. }
  6998. static int run_function(const struct function *funcp, char **argv)
  6999. {
  7000. int rc;
  7001. save_arg_t sv;
  7002. smallint sv_flg;
  7003. save_and_replace_G_args(&sv, argv);
  7004. /* "We are in function, ok to use return" */
  7005. sv_flg = G_flag_return_in_progress;
  7006. G_flag_return_in_progress = -1;
  7007. /* Make "local" variables properly shadow previous ones */
  7008. IF_HUSH_LOCAL(enter_var_nest_level();)
  7009. IF_HUSH_LOCAL(G.func_nest_level++;)
  7010. /* On MMU, funcp->body is always non-NULL */
  7011. # if !BB_MMU
  7012. if (!funcp->body) {
  7013. /* Function defined by -F */
  7014. parse_and_run_string(funcp->body_as_string);
  7015. rc = G.last_exitcode;
  7016. } else
  7017. # endif
  7018. {
  7019. rc = run_list(funcp->body);
  7020. }
  7021. IF_HUSH_LOCAL(G.func_nest_level--;)
  7022. IF_HUSH_LOCAL(leave_var_nest_level();)
  7023. G_flag_return_in_progress = sv_flg;
  7024. restore_G_args(&sv, argv);
  7025. return rc;
  7026. }
  7027. #endif /* ENABLE_HUSH_FUNCTIONS */
  7028. #if BB_MMU
  7029. #define exec_builtin(to_free, x, argv) \
  7030. exec_builtin(x, argv)
  7031. #else
  7032. #define exec_builtin(to_free, x, argv) \
  7033. exec_builtin(to_free, argv)
  7034. #endif
  7035. static void exec_builtin(char ***to_free,
  7036. const struct built_in_command *x,
  7037. char **argv) NORETURN;
  7038. static void exec_builtin(char ***to_free,
  7039. const struct built_in_command *x,
  7040. char **argv)
  7041. {
  7042. #if BB_MMU
  7043. int rcode;
  7044. fflush_all();
  7045. //? close_saved_fds_and_FILE_fds();
  7046. rcode = x->b_function(argv);
  7047. fflush_all();
  7048. _exit(rcode);
  7049. #else
  7050. fflush_all();
  7051. /* On NOMMU, we must never block!
  7052. * Example: { sleep 99 | read line; } & echo Ok
  7053. */
  7054. re_execute_shell(to_free,
  7055. argv[0],
  7056. G.global_argv[0],
  7057. G.global_argv + 1,
  7058. argv);
  7059. #endif
  7060. }
  7061. static void execvp_or_die(char **argv) NORETURN;
  7062. static void execvp_or_die(char **argv)
  7063. {
  7064. int e;
  7065. debug_printf_exec("execing '%s'\n", argv[0]);
  7066. /* Don't propagate SIG_IGN to the child */
  7067. if (SPECIAL_JOBSTOP_SIGS != 0)
  7068. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7069. execvp(argv[0], argv);
  7070. e = 2;
  7071. if (errno == EACCES) e = 126;
  7072. if (errno == ENOENT) e = 127;
  7073. bb_perror_msg("can't execute '%s'", argv[0]);
  7074. _exit(e);
  7075. }
  7076. #if ENABLE_HUSH_MODE_X
  7077. static void dump_cmd_in_x_mode(char **argv)
  7078. {
  7079. if (G_x_mode && argv) {
  7080. /* We want to output the line in one write op */
  7081. char *buf, *p;
  7082. int len;
  7083. int n;
  7084. len = 3;
  7085. n = 0;
  7086. while (argv[n])
  7087. len += strlen(argv[n++]) + 1;
  7088. buf = xmalloc(len);
  7089. buf[0] = '+';
  7090. p = buf + 1;
  7091. n = 0;
  7092. while (argv[n])
  7093. p += sprintf(p, " %s", argv[n++]);
  7094. *p++ = '\n';
  7095. *p = '\0';
  7096. fputs(buf, stderr);
  7097. free(buf);
  7098. }
  7099. }
  7100. #else
  7101. # define dump_cmd_in_x_mode(argv) ((void)0)
  7102. #endif
  7103. #if ENABLE_HUSH_COMMAND
  7104. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7105. {
  7106. char *to_free;
  7107. if (!opt_vV)
  7108. return;
  7109. to_free = NULL;
  7110. if (!explanation) {
  7111. char *path = getenv("PATH");
  7112. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7113. if (!explanation)
  7114. _exit(1); /* PROG was not found */
  7115. if (opt_vV != 'V')
  7116. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7117. }
  7118. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7119. free(to_free);
  7120. fflush_all();
  7121. _exit(0);
  7122. }
  7123. #else
  7124. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7125. #endif
  7126. #if BB_MMU
  7127. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7128. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7129. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7130. pseudo_exec(command, argv_expanded)
  7131. #endif
  7132. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7133. * Never returns.
  7134. * Don't exit() here. If you don't exec, use _exit instead.
  7135. * The at_exit handlers apparently confuse the calling process,
  7136. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7137. */
  7138. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7139. char **argv, int assignment_cnt,
  7140. char **argv_expanded) NORETURN;
  7141. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7142. char **argv, int assignment_cnt,
  7143. char **argv_expanded)
  7144. {
  7145. const struct built_in_command *x;
  7146. struct variable **sv_shadowed;
  7147. char **new_env;
  7148. IF_HUSH_COMMAND(char opt_vV = 0;)
  7149. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7150. new_env = expand_assignments(argv, assignment_cnt);
  7151. dump_cmd_in_x_mode(new_env);
  7152. if (!argv[assignment_cnt]) {
  7153. /* Case when we are here: ... | var=val | ...
  7154. * (note that we do not exit early, i.e., do not optimize out
  7155. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7156. */
  7157. free_strings(new_env);
  7158. _exit(EXIT_SUCCESS);
  7159. }
  7160. sv_shadowed = G.shadowed_vars_pp;
  7161. #if BB_MMU
  7162. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7163. #else
  7164. G.shadowed_vars_pp = &nommu_save->old_vars;
  7165. G.var_nest_level++;
  7166. #endif
  7167. set_vars_and_save_old(new_env);
  7168. G.shadowed_vars_pp = sv_shadowed;
  7169. if (argv_expanded) {
  7170. argv = argv_expanded;
  7171. } else {
  7172. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7173. #if !BB_MMU
  7174. nommu_save->argv = argv;
  7175. #endif
  7176. }
  7177. dump_cmd_in_x_mode(argv);
  7178. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7179. if (strchr(argv[0], '/') != NULL)
  7180. goto skip;
  7181. #endif
  7182. #if ENABLE_HUSH_FUNCTIONS
  7183. /* Check if the command matches any functions (this goes before bltins) */
  7184. funcp = find_function(argv[0]);
  7185. if (funcp)
  7186. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7187. #endif
  7188. #if ENABLE_HUSH_COMMAND
  7189. /* "command BAR": run BAR without looking it up among functions
  7190. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7191. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7192. */
  7193. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7194. char *p;
  7195. argv++;
  7196. p = *argv;
  7197. if (p[0] != '-' || !p[1])
  7198. continue; /* bash allows "command command command [-OPT] BAR" */
  7199. for (;;) {
  7200. p++;
  7201. switch (*p) {
  7202. case '\0':
  7203. argv++;
  7204. p = *argv;
  7205. if (p[0] != '-' || !p[1])
  7206. goto after_opts;
  7207. continue; /* next arg is also -opts, process it too */
  7208. case 'v':
  7209. case 'V':
  7210. opt_vV = *p;
  7211. continue;
  7212. default:
  7213. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7214. }
  7215. }
  7216. }
  7217. after_opts:
  7218. # if ENABLE_HUSH_FUNCTIONS
  7219. if (opt_vV && find_function(argv[0]))
  7220. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7221. # endif
  7222. #endif
  7223. /* Check if the command matches any of the builtins.
  7224. * Depending on context, this might be redundant. But it's
  7225. * easier to waste a few CPU cycles than it is to figure out
  7226. * if this is one of those cases.
  7227. */
  7228. /* Why "BB_MMU ? :" difference in logic? -
  7229. * On NOMMU, it is more expensive to re-execute shell
  7230. * just in order to run echo or test builtin.
  7231. * It's better to skip it here and run corresponding
  7232. * non-builtin later. */
  7233. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7234. if (x) {
  7235. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7236. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7237. }
  7238. #if ENABLE_FEATURE_SH_STANDALONE
  7239. /* Check if the command matches any busybox applets */
  7240. {
  7241. int a = find_applet_by_name(argv[0]);
  7242. if (a >= 0) {
  7243. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7244. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7245. if (APPLET_IS_NOEXEC(a)) {
  7246. /* Do not leak open fds from opened script files etc.
  7247. * Testcase: interactive "ls -l /proc/self/fd"
  7248. * should not show tty fd open.
  7249. */
  7250. close_saved_fds_and_FILE_fds();
  7251. //FIXME: should also close saved redir fds
  7252. //This casuses test failures in
  7253. //redir_children_should_not_see_saved_fd_2.tests
  7254. //redir_children_should_not_see_saved_fd_3.tests
  7255. //if you replace "busybox find" with just "find" in them
  7256. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7257. switch_off_special_sigs(G.special_sig_mask);
  7258. debug_printf_exec("running applet '%s'\n", argv[0]);
  7259. run_noexec_applet_and_exit(a, argv[0], argv);
  7260. }
  7261. # endif
  7262. /* Re-exec ourselves */
  7263. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7264. /* Don't propagate SIG_IGN to the child */
  7265. if (SPECIAL_JOBSTOP_SIGS != 0)
  7266. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7267. execv(bb_busybox_exec_path, argv);
  7268. /* If they called chroot or otherwise made the binary no longer
  7269. * executable, fall through */
  7270. }
  7271. }
  7272. #endif
  7273. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7274. skip:
  7275. #endif
  7276. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7277. execvp_or_die(argv);
  7278. }
  7279. /* Called after [v]fork() in run_pipe
  7280. */
  7281. static void pseudo_exec(nommu_save_t *nommu_save,
  7282. struct command *command,
  7283. char **argv_expanded) NORETURN;
  7284. static void pseudo_exec(nommu_save_t *nommu_save,
  7285. struct command *command,
  7286. char **argv_expanded)
  7287. {
  7288. #if ENABLE_HUSH_FUNCTIONS
  7289. if (command->cmd_type == CMD_FUNCDEF) {
  7290. /* Ignore funcdefs in pipes:
  7291. * true | f() { cmd }
  7292. */
  7293. _exit(0);
  7294. }
  7295. #endif
  7296. if (command->argv) {
  7297. pseudo_exec_argv(nommu_save, command->argv,
  7298. command->assignment_cnt, argv_expanded);
  7299. }
  7300. if (command->group) {
  7301. /* Cases when we are here:
  7302. * ( list )
  7303. * { list } &
  7304. * ... | ( list ) | ...
  7305. * ... | { list } | ...
  7306. */
  7307. #if BB_MMU
  7308. int rcode;
  7309. debug_printf_exec("pseudo_exec: run_list\n");
  7310. reset_traps_to_defaults();
  7311. rcode = run_list(command->group);
  7312. /* OK to leak memory by not calling free_pipe_list,
  7313. * since this process is about to exit */
  7314. _exit(rcode);
  7315. #else
  7316. re_execute_shell(&nommu_save->argv_from_re_execing,
  7317. command->group_as_string,
  7318. G.global_argv[0],
  7319. G.global_argv + 1,
  7320. NULL);
  7321. #endif
  7322. }
  7323. /* Case when we are here: ... | >file */
  7324. debug_printf_exec("pseudo_exec'ed null command\n");
  7325. _exit(EXIT_SUCCESS);
  7326. }
  7327. #if ENABLE_HUSH_JOB
  7328. static const char *get_cmdtext(struct pipe *pi)
  7329. {
  7330. char **argv;
  7331. char *p;
  7332. int len;
  7333. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7334. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7335. * On subsequent bg argv is trashed, but we won't use it */
  7336. if (pi->cmdtext)
  7337. return pi->cmdtext;
  7338. argv = pi->cmds[0].argv;
  7339. if (!argv) {
  7340. pi->cmdtext = xzalloc(1);
  7341. return pi->cmdtext;
  7342. }
  7343. len = 0;
  7344. do {
  7345. len += strlen(*argv) + 1;
  7346. } while (*++argv);
  7347. p = xmalloc(len);
  7348. pi->cmdtext = p;
  7349. argv = pi->cmds[0].argv;
  7350. do {
  7351. p = stpcpy(p, *argv);
  7352. *p++ = ' ';
  7353. } while (*++argv);
  7354. p[-1] = '\0';
  7355. return pi->cmdtext;
  7356. }
  7357. static void remove_job_from_table(struct pipe *pi)
  7358. {
  7359. struct pipe *prev_pipe;
  7360. if (pi == G.job_list) {
  7361. G.job_list = pi->next;
  7362. } else {
  7363. prev_pipe = G.job_list;
  7364. while (prev_pipe->next != pi)
  7365. prev_pipe = prev_pipe->next;
  7366. prev_pipe->next = pi->next;
  7367. }
  7368. G.last_jobid = 0;
  7369. if (G.job_list)
  7370. G.last_jobid = G.job_list->jobid;
  7371. }
  7372. static void delete_finished_job(struct pipe *pi)
  7373. {
  7374. remove_job_from_table(pi);
  7375. free_pipe(pi);
  7376. }
  7377. static void clean_up_last_dead_job(void)
  7378. {
  7379. if (G.job_list && !G.job_list->alive_cmds)
  7380. delete_finished_job(G.job_list);
  7381. }
  7382. static void insert_job_into_table(struct pipe *pi)
  7383. {
  7384. struct pipe *job, **jobp;
  7385. int i;
  7386. clean_up_last_dead_job();
  7387. /* Find the end of the list, and find next job ID to use */
  7388. i = 0;
  7389. jobp = &G.job_list;
  7390. while ((job = *jobp) != NULL) {
  7391. if (job->jobid > i)
  7392. i = job->jobid;
  7393. jobp = &job->next;
  7394. }
  7395. pi->jobid = i + 1;
  7396. /* Create a new job struct at the end */
  7397. job = *jobp = xmemdup(pi, sizeof(*pi));
  7398. job->next = NULL;
  7399. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7400. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7401. for (i = 0; i < pi->num_cmds; i++) {
  7402. job->cmds[i].pid = pi->cmds[i].pid;
  7403. /* all other fields are not used and stay zero */
  7404. }
  7405. job->cmdtext = xstrdup(get_cmdtext(pi));
  7406. if (G_interactive_fd)
  7407. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  7408. G.last_jobid = job->jobid;
  7409. }
  7410. #endif /* JOB */
  7411. static int job_exited_or_stopped(struct pipe *pi)
  7412. {
  7413. int rcode, i;
  7414. if (pi->alive_cmds != pi->stopped_cmds)
  7415. return -1;
  7416. /* All processes in fg pipe have exited or stopped */
  7417. rcode = 0;
  7418. i = pi->num_cmds;
  7419. while (--i >= 0) {
  7420. rcode = pi->cmds[i].cmd_exitcode;
  7421. /* usually last process gives overall exitstatus,
  7422. * but with "set -o pipefail", last *failed* process does */
  7423. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  7424. break;
  7425. }
  7426. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7427. return rcode;
  7428. }
  7429. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  7430. {
  7431. #if ENABLE_HUSH_JOB
  7432. struct pipe *pi;
  7433. #endif
  7434. int i, dead;
  7435. dead = WIFEXITED(status) || WIFSIGNALED(status);
  7436. #if DEBUG_JOBS
  7437. if (WIFSTOPPED(status))
  7438. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  7439. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  7440. if (WIFSIGNALED(status))
  7441. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  7442. childpid, WTERMSIG(status), WEXITSTATUS(status));
  7443. if (WIFEXITED(status))
  7444. debug_printf_jobs("pid %d exited, exitcode %d\n",
  7445. childpid, WEXITSTATUS(status));
  7446. #endif
  7447. /* Were we asked to wait for a fg pipe? */
  7448. if (fg_pipe) {
  7449. i = fg_pipe->num_cmds;
  7450. while (--i >= 0) {
  7451. int rcode;
  7452. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  7453. if (fg_pipe->cmds[i].pid != childpid)
  7454. continue;
  7455. if (dead) {
  7456. int ex;
  7457. fg_pipe->cmds[i].pid = 0;
  7458. fg_pipe->alive_cmds--;
  7459. ex = WEXITSTATUS(status);
  7460. /* bash prints killer signal's name for *last*
  7461. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  7462. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  7463. */
  7464. if (WIFSIGNALED(status)) {
  7465. int sig = WTERMSIG(status);
  7466. if (i == fg_pipe->num_cmds-1)
  7467. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  7468. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  7469. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  7470. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  7471. * Maybe we need to use sig | 128? */
  7472. ex = sig + 128;
  7473. }
  7474. fg_pipe->cmds[i].cmd_exitcode = ex;
  7475. } else {
  7476. fg_pipe->stopped_cmds++;
  7477. }
  7478. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  7479. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  7480. rcode = job_exited_or_stopped(fg_pipe);
  7481. if (rcode >= 0) {
  7482. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  7483. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  7484. * and "killall -STOP cat" */
  7485. if (G_interactive_fd) {
  7486. #if ENABLE_HUSH_JOB
  7487. if (fg_pipe->alive_cmds != 0)
  7488. insert_job_into_table(fg_pipe);
  7489. #endif
  7490. return rcode;
  7491. }
  7492. if (fg_pipe->alive_cmds == 0)
  7493. return rcode;
  7494. }
  7495. /* There are still running processes in the fg_pipe */
  7496. return -1;
  7497. }
  7498. /* It wasn't in fg_pipe, look for process in bg pipes */
  7499. }
  7500. #if ENABLE_HUSH_JOB
  7501. /* We were asked to wait for bg or orphaned children */
  7502. /* No need to remember exitcode in this case */
  7503. for (pi = G.job_list; pi; pi = pi->next) {
  7504. for (i = 0; i < pi->num_cmds; i++) {
  7505. if (pi->cmds[i].pid == childpid)
  7506. goto found_pi_and_prognum;
  7507. }
  7508. }
  7509. /* Happens when shell is used as init process (init=/bin/sh) */
  7510. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  7511. return -1; /* this wasn't a process from fg_pipe */
  7512. found_pi_and_prognum:
  7513. if (dead) {
  7514. /* child exited */
  7515. int rcode = WEXITSTATUS(status);
  7516. if (WIFSIGNALED(status))
  7517. rcode = 128 + WTERMSIG(status);
  7518. pi->cmds[i].cmd_exitcode = rcode;
  7519. if (G.last_bg_pid == pi->cmds[i].pid)
  7520. G.last_bg_pid_exitcode = rcode;
  7521. pi->cmds[i].pid = 0;
  7522. pi->alive_cmds--;
  7523. if (!pi->alive_cmds) {
  7524. if (G_interactive_fd) {
  7525. printf(JOB_STATUS_FORMAT, pi->jobid,
  7526. "Done", pi->cmdtext);
  7527. delete_finished_job(pi);
  7528. } else {
  7529. /*
  7530. * bash deletes finished jobs from job table only in interactive mode,
  7531. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  7532. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  7533. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  7534. * We only retain one "dead" job, if it's the single job on the list.
  7535. * This covers most of real-world scenarios where this is useful.
  7536. */
  7537. if (pi != G.job_list)
  7538. delete_finished_job(pi);
  7539. }
  7540. }
  7541. } else {
  7542. /* child stopped */
  7543. pi->stopped_cmds++;
  7544. }
  7545. #endif
  7546. return -1; /* this wasn't a process from fg_pipe */
  7547. }
  7548. /* Check to see if any processes have exited -- if they have,
  7549. * figure out why and see if a job has completed.
  7550. *
  7551. * If non-NULL fg_pipe: wait for its completion or stop.
  7552. * Return its exitcode or zero if stopped.
  7553. *
  7554. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  7555. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  7556. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  7557. * or 0 if no children changed status.
  7558. *
  7559. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  7560. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  7561. * or 0 if no children changed status.
  7562. */
  7563. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  7564. {
  7565. int attributes;
  7566. int status;
  7567. int rcode = 0;
  7568. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  7569. attributes = WUNTRACED;
  7570. if (fg_pipe == NULL)
  7571. attributes |= WNOHANG;
  7572. errno = 0;
  7573. #if ENABLE_HUSH_FAST
  7574. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  7575. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  7576. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  7577. /* There was neither fork nor SIGCHLD since last waitpid */
  7578. /* Avoid doing waitpid syscall if possible */
  7579. if (!G.we_have_children) {
  7580. errno = ECHILD;
  7581. return -1;
  7582. }
  7583. if (fg_pipe == NULL) { /* is WNOHANG set? */
  7584. /* We have children, but they did not exit
  7585. * or stop yet (we saw no SIGCHLD) */
  7586. return 0;
  7587. }
  7588. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  7589. }
  7590. #endif
  7591. /* Do we do this right?
  7592. * bash-3.00# sleep 20 | false
  7593. * <ctrl-Z pressed>
  7594. * [3]+ Stopped sleep 20 | false
  7595. * bash-3.00# echo $?
  7596. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  7597. * [hush 1.14.0: yes we do it right]
  7598. */
  7599. while (1) {
  7600. pid_t childpid;
  7601. #if ENABLE_HUSH_FAST
  7602. int i;
  7603. i = G.count_SIGCHLD;
  7604. #endif
  7605. childpid = waitpid(-1, &status, attributes);
  7606. if (childpid <= 0) {
  7607. if (childpid && errno != ECHILD)
  7608. bb_perror_msg("waitpid");
  7609. #if ENABLE_HUSH_FAST
  7610. else { /* Until next SIGCHLD, waitpid's are useless */
  7611. G.we_have_children = (childpid == 0);
  7612. G.handled_SIGCHLD = i;
  7613. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7614. }
  7615. #endif
  7616. /* ECHILD (no children), or 0 (no change in children status) */
  7617. rcode = childpid;
  7618. break;
  7619. }
  7620. rcode = process_wait_result(fg_pipe, childpid, status);
  7621. if (rcode >= 0) {
  7622. /* fg_pipe exited or stopped */
  7623. break;
  7624. }
  7625. if (childpid == waitfor_pid) {
  7626. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  7627. rcode = WEXITSTATUS(status);
  7628. if (WIFSIGNALED(status))
  7629. rcode = 128 + WTERMSIG(status);
  7630. if (WIFSTOPPED(status))
  7631. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  7632. rcode = 128 + WSTOPSIG(status);
  7633. rcode++;
  7634. break; /* "wait PID" called us, give it exitcode+1 */
  7635. }
  7636. /* This wasn't one of our processes, or */
  7637. /* fg_pipe still has running processes, do waitpid again */
  7638. } /* while (waitpid succeeds)... */
  7639. return rcode;
  7640. }
  7641. #if ENABLE_HUSH_JOB
  7642. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  7643. {
  7644. pid_t p;
  7645. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  7646. if (G_saved_tty_pgrp) {
  7647. /* Job finished, move the shell to the foreground */
  7648. p = getpgrp(); /* our process group id */
  7649. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  7650. tcsetpgrp(G_interactive_fd, p);
  7651. }
  7652. return rcode;
  7653. }
  7654. #endif
  7655. /* Start all the jobs, but don't wait for anything to finish.
  7656. * See checkjobs().
  7657. *
  7658. * Return code is normally -1, when the caller has to wait for children
  7659. * to finish to determine the exit status of the pipe. If the pipe
  7660. * is a simple builtin command, however, the action is done by the
  7661. * time run_pipe returns, and the exit code is provided as the
  7662. * return value.
  7663. *
  7664. * Returns -1 only if started some children. IOW: we have to
  7665. * mask out retvals of builtins etc with 0xff!
  7666. *
  7667. * The only case when we do not need to [v]fork is when the pipe
  7668. * is single, non-backgrounded, non-subshell command. Examples:
  7669. * cmd ; ... { list } ; ...
  7670. * cmd && ... { list } && ...
  7671. * cmd || ... { list } || ...
  7672. * If it is, then we can run cmd as a builtin, NOFORK,
  7673. * or (if SH_STANDALONE) an applet, and we can run the { list }
  7674. * with run_list. If it isn't one of these, we fork and exec cmd.
  7675. *
  7676. * Cases when we must fork:
  7677. * non-single: cmd | cmd
  7678. * backgrounded: cmd & { list } &
  7679. * subshell: ( list ) [&]
  7680. */
  7681. #if !ENABLE_HUSH_MODE_X
  7682. #define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
  7683. redirect_and_varexp_helper(command, squirrel)
  7684. #endif
  7685. static int redirect_and_varexp_helper(
  7686. struct command *command,
  7687. struct squirrel **sqp,
  7688. char **argv_expanded)
  7689. {
  7690. /* Assignments occur before redirects. Try:
  7691. * a=`sleep 1` sleep 2 3>/qwe/rty
  7692. */
  7693. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  7694. dump_cmd_in_x_mode(new_env);
  7695. dump_cmd_in_x_mode(argv_expanded);
  7696. /* this takes ownership of new_env[i] elements, and frees new_env: */
  7697. set_vars_and_save_old(new_env);
  7698. /* setup_redirects acts on file descriptors, not FILEs.
  7699. * This is perfect for work that comes after exec().
  7700. * Is it really safe for inline use? Experimentally,
  7701. * things seem to work. */
  7702. return setup_redirects(command, sqp);
  7703. }
  7704. static NOINLINE int run_pipe(struct pipe *pi)
  7705. {
  7706. static const char *const null_ptr = NULL;
  7707. int cmd_no;
  7708. int next_infd;
  7709. struct command *command;
  7710. char **argv_expanded;
  7711. char **argv;
  7712. struct squirrel *squirrel = NULL;
  7713. int rcode;
  7714. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  7715. debug_enter();
  7716. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  7717. * Result should be 3 lines: q w e, qwe, q w e
  7718. */
  7719. if (G.ifs_whitespace != G.ifs)
  7720. free(G.ifs_whitespace);
  7721. G.ifs = get_local_var_value("IFS");
  7722. if (G.ifs) {
  7723. char *p;
  7724. G.ifs_whitespace = (char*)G.ifs;
  7725. p = skip_whitespace(G.ifs);
  7726. if (*p) {
  7727. /* Not all $IFS is whitespace */
  7728. char *d;
  7729. int len = p - G.ifs;
  7730. p = skip_non_whitespace(p);
  7731. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  7732. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  7733. while (*p) {
  7734. if (isspace(*p))
  7735. *d++ = *p;
  7736. p++;
  7737. }
  7738. *d = '\0';
  7739. }
  7740. } else {
  7741. G.ifs = defifs;
  7742. G.ifs_whitespace = (char*)G.ifs;
  7743. }
  7744. IF_HUSH_JOB(pi->pgrp = -1;)
  7745. pi->stopped_cmds = 0;
  7746. command = &pi->cmds[0];
  7747. argv_expanded = NULL;
  7748. if (pi->num_cmds != 1
  7749. || pi->followup == PIPE_BG
  7750. || command->cmd_type == CMD_SUBSHELL
  7751. ) {
  7752. goto must_fork;
  7753. }
  7754. pi->alive_cmds = 1;
  7755. debug_printf_exec(": group:%p argv:'%s'\n",
  7756. command->group, command->argv ? command->argv[0] : "NONE");
  7757. if (command->group) {
  7758. #if ENABLE_HUSH_FUNCTIONS
  7759. if (command->cmd_type == CMD_FUNCDEF) {
  7760. /* "executing" func () { list } */
  7761. struct function *funcp;
  7762. funcp = new_function(command->argv[0]);
  7763. /* funcp->name is already set to argv[0] */
  7764. funcp->body = command->group;
  7765. # if !BB_MMU
  7766. funcp->body_as_string = command->group_as_string;
  7767. command->group_as_string = NULL;
  7768. # endif
  7769. command->group = NULL;
  7770. command->argv[0] = NULL;
  7771. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  7772. funcp->parent_cmd = command;
  7773. command->child_func = funcp;
  7774. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  7775. debug_leave();
  7776. return EXIT_SUCCESS;
  7777. }
  7778. #endif
  7779. /* { list } */
  7780. debug_printf("non-subshell group\n");
  7781. rcode = 1; /* exitcode if redir failed */
  7782. if (setup_redirects(command, &squirrel) == 0) {
  7783. debug_printf_exec(": run_list\n");
  7784. //FIXME: we need to pass squirrel down into run_list()
  7785. //for SH_STANDALONE case, or else this construct:
  7786. // { find /proc/self/fd; true; } >FILE; cmd2
  7787. //has no way of closing saved fd#1 for "find",
  7788. //and in SH_STANDALONE mode, "find" is not execed,
  7789. //therefore CLOEXEC on saved fd does not help.
  7790. rcode = run_list(command->group) & 0xff;
  7791. }
  7792. restore_redirects(squirrel);
  7793. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7794. debug_leave();
  7795. debug_printf_exec("run_pipe: return %d\n", rcode);
  7796. return rcode;
  7797. }
  7798. argv = command->argv ? command->argv : (char **) &null_ptr;
  7799. {
  7800. const struct built_in_command *x;
  7801. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7802. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  7803. struct variable **sv_shadowed;
  7804. struct variable *old_vars;
  7805. #if ENABLE_HUSH_LINENO_VAR
  7806. if (G.lineno_var)
  7807. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  7808. #endif
  7809. if (argv[command->assignment_cnt] == NULL) {
  7810. /* Assignments, but no command.
  7811. * Ensure redirects take effect (that is, create files).
  7812. * Try "a=t >file"
  7813. */
  7814. unsigned i;
  7815. G.expand_exitcode = 0;
  7816. only_assignments:
  7817. rcode = setup_redirects(command, &squirrel);
  7818. restore_redirects(squirrel);
  7819. /* Set shell variables */
  7820. if (G_x_mode)
  7821. bb_putchar_stderr('+');
  7822. i = 0;
  7823. while (i < command->assignment_cnt) {
  7824. char *p = expand_string_to_string(argv[i],
  7825. EXP_FLAG_ESC_GLOB_CHARS,
  7826. /*unbackslash:*/ 1
  7827. );
  7828. if (G_x_mode)
  7829. fprintf(stderr, " %s", p);
  7830. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  7831. if (set_local_var(p, /*flag:*/ 0)) {
  7832. /* assignment to readonly var / putenv error? */
  7833. rcode = 1;
  7834. }
  7835. i++;
  7836. }
  7837. if (G_x_mode)
  7838. bb_putchar_stderr('\n');
  7839. /* Redirect error sets $? to 1. Otherwise,
  7840. * if evaluating assignment value set $?, retain it.
  7841. * Else, clear $?:
  7842. * false; q=`exit 2`; echo $? - should print 2
  7843. * false; x=1; echo $? - should print 0
  7844. * Because of the 2nd case, we can't just use G.last_exitcode.
  7845. */
  7846. if (rcode == 0)
  7847. rcode = G.expand_exitcode;
  7848. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7849. debug_leave();
  7850. debug_printf_exec("run_pipe: return %d\n", rcode);
  7851. return rcode;
  7852. }
  7853. /* Expand the rest into (possibly) many strings each */
  7854. #if defined(CMD_SINGLEWORD_NOGLOB)
  7855. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  7856. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  7857. else
  7858. #endif
  7859. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  7860. /* If someone gives us an empty string: `cmd with empty output` */
  7861. if (!argv_expanded[0]) {
  7862. free(argv_expanded);
  7863. /* `false` still has to set exitcode 1 */
  7864. G.expand_exitcode = G.last_exitcode;
  7865. goto only_assignments;
  7866. }
  7867. old_vars = NULL;
  7868. sv_shadowed = G.shadowed_vars_pp;
  7869. /* Check if argv[0] matches any functions (this goes before bltins) */
  7870. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  7871. IF_HUSH_FUNCTIONS(x = NULL;)
  7872. IF_HUSH_FUNCTIONS(if (!funcp))
  7873. x = find_builtin(argv_expanded[0]);
  7874. if (x || funcp) {
  7875. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  7876. debug_printf("exec with redirects only\n");
  7877. /*
  7878. * Variable assignments are executed, but then "forgotten":
  7879. * a=`sleep 1;echo A` exec 3>&-; echo $a
  7880. * sleeps, but prints nothing.
  7881. */
  7882. enter_var_nest_level();
  7883. G.shadowed_vars_pp = &old_vars;
  7884. rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
  7885. G.shadowed_vars_pp = sv_shadowed;
  7886. /* rcode=1 can be if redir file can't be opened */
  7887. goto clean_up_and_ret1;
  7888. }
  7889. /* Bump var nesting, or this will leak exported $a:
  7890. * a=b true; env | grep ^a=
  7891. */
  7892. enter_var_nest_level();
  7893. /* Collect all variables "shadowed" by helper
  7894. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  7895. * into old_vars list:
  7896. */
  7897. G.shadowed_vars_pp = &old_vars;
  7898. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  7899. if (rcode == 0) {
  7900. if (!funcp) {
  7901. /* Do not collect *to old_vars list* vars shadowed
  7902. * by e.g. "local VAR" builtin (collect them
  7903. * in the previously nested list instead):
  7904. * don't want them to be restored immediately
  7905. * after "local" completes.
  7906. */
  7907. G.shadowed_vars_pp = sv_shadowed;
  7908. debug_printf_exec(": builtin '%s' '%s'...\n",
  7909. x->b_cmd, argv_expanded[1]);
  7910. fflush_all();
  7911. rcode = x->b_function(argv_expanded) & 0xff;
  7912. fflush_all();
  7913. }
  7914. #if ENABLE_HUSH_FUNCTIONS
  7915. else {
  7916. debug_printf_exec(": function '%s' '%s'...\n",
  7917. funcp->name, argv_expanded[1]);
  7918. rcode = run_function(funcp, argv_expanded) & 0xff;
  7919. /*
  7920. * But do collect *to old_vars list* vars shadowed
  7921. * within function execution. To that end, restore
  7922. * this pointer _after_ function run:
  7923. */
  7924. G.shadowed_vars_pp = sv_shadowed;
  7925. }
  7926. #endif
  7927. }
  7928. } else
  7929. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  7930. int n = find_applet_by_name(argv_expanded[0]);
  7931. if (n < 0 || !APPLET_IS_NOFORK(n))
  7932. goto must_fork;
  7933. enter_var_nest_level();
  7934. /* Collect all variables "shadowed" by helper into old_vars list */
  7935. G.shadowed_vars_pp = &old_vars;
  7936. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  7937. G.shadowed_vars_pp = sv_shadowed;
  7938. if (rcode == 0) {
  7939. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  7940. argv_expanded[0], argv_expanded[1]);
  7941. /*
  7942. * Note: signals (^C) can't interrupt here.
  7943. * We remember them and they will be acted upon
  7944. * after applet returns.
  7945. * This makes applets which can run for a long time
  7946. * and/or wait for user input ineligible for NOFORK:
  7947. * for example, "yes" or "rm" (rm -i waits for input).
  7948. */
  7949. rcode = run_nofork_applet(n, argv_expanded);
  7950. }
  7951. } else
  7952. goto must_fork;
  7953. restore_redirects(squirrel);
  7954. clean_up_and_ret1:
  7955. leave_var_nest_level();
  7956. add_vars(old_vars);
  7957. /*
  7958. * Try "usleep 99999999" + ^C + "echo $?"
  7959. * with FEATURE_SH_NOFORK=y.
  7960. */
  7961. if (!funcp) {
  7962. /* It was builtin or nofork.
  7963. * if this would be a real fork/execed program,
  7964. * it should have died if a fatal sig was received.
  7965. * But OTOH, there was no separate process,
  7966. * the sig was sent to _shell_, not to non-existing
  7967. * child.
  7968. * Let's just handle ^C only, this one is obvious:
  7969. * we aren't ok with exitcode 0 when ^C was pressed
  7970. * during builtin/nofork.
  7971. */
  7972. if (sigismember(&G.pending_set, SIGINT))
  7973. rcode = 128 + SIGINT;
  7974. }
  7975. free(argv_expanded);
  7976. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7977. debug_leave();
  7978. debug_printf_exec("run_pipe return %d\n", rcode);
  7979. return rcode;
  7980. }
  7981. must_fork:
  7982. /* NB: argv_expanded may already be created, and that
  7983. * might include `cmd` runs! Do not rerun it! We *must*
  7984. * use argv_expanded if it's non-NULL */
  7985. /* Going to fork a child per each pipe member */
  7986. pi->alive_cmds = 0;
  7987. next_infd = 0;
  7988. cmd_no = 0;
  7989. while (cmd_no < pi->num_cmds) {
  7990. struct fd_pair pipefds;
  7991. #if !BB_MMU
  7992. int sv_var_nest_level = G.var_nest_level;
  7993. volatile nommu_save_t nommu_save;
  7994. nommu_save.old_vars = NULL;
  7995. nommu_save.argv = NULL;
  7996. nommu_save.argv_from_re_execing = NULL;
  7997. #endif
  7998. command = &pi->cmds[cmd_no];
  7999. cmd_no++;
  8000. if (command->argv) {
  8001. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8002. command->argv[0], command->argv[1]);
  8003. } else {
  8004. debug_printf_exec(": pipe member with no argv\n");
  8005. }
  8006. /* pipes are inserted between pairs of commands */
  8007. pipefds.rd = 0;
  8008. pipefds.wr = 1;
  8009. if (cmd_no < pi->num_cmds)
  8010. xpiped_pair(pipefds);
  8011. #if ENABLE_HUSH_LINENO_VAR
  8012. if (G.lineno_var)
  8013. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  8014. #endif
  8015. command->pid = BB_MMU ? fork() : vfork();
  8016. if (!command->pid) { /* child */
  8017. #if ENABLE_HUSH_JOB
  8018. disable_restore_tty_pgrp_on_exit();
  8019. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8020. /* Every child adds itself to new process group
  8021. * with pgid == pid_of_first_child_in_pipe */
  8022. if (G.run_list_level == 1 && G_interactive_fd) {
  8023. pid_t pgrp;
  8024. pgrp = pi->pgrp;
  8025. if (pgrp < 0) /* true for 1st process only */
  8026. pgrp = getpid();
  8027. if (setpgid(0, pgrp) == 0
  8028. && pi->followup != PIPE_BG
  8029. && G_saved_tty_pgrp /* we have ctty */
  8030. ) {
  8031. /* We do it in *every* child, not just first,
  8032. * to avoid races */
  8033. tcsetpgrp(G_interactive_fd, pgrp);
  8034. }
  8035. }
  8036. #endif
  8037. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8038. /* 1st cmd in backgrounded pipe
  8039. * should have its stdin /dev/null'ed */
  8040. close(0);
  8041. if (open(bb_dev_null, O_RDONLY))
  8042. xopen("/", O_RDONLY);
  8043. } else {
  8044. xmove_fd(next_infd, 0);
  8045. }
  8046. xmove_fd(pipefds.wr, 1);
  8047. if (pipefds.rd > 1)
  8048. close(pipefds.rd);
  8049. /* Like bash, explicit redirects override pipes,
  8050. * and the pipe fd (fd#1) is available for dup'ing:
  8051. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8052. * of cmd1 goes into pipe.
  8053. */
  8054. if (setup_redirects(command, NULL)) {
  8055. /* Happens when redir file can't be opened:
  8056. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8057. * FOO
  8058. * hush: can't open '/qwe/rty': No such file or directory
  8059. * BAZ
  8060. * (echo BAR is not executed, it hits _exit(1) below)
  8061. */
  8062. _exit(1);
  8063. }
  8064. /* Stores to nommu_save list of env vars putenv'ed
  8065. * (NOMMU, on MMU we don't need that) */
  8066. /* cast away volatility... */
  8067. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8068. /* pseudo_exec() does not return */
  8069. }
  8070. /* parent or error */
  8071. #if ENABLE_HUSH_FAST
  8072. G.count_SIGCHLD++;
  8073. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8074. #endif
  8075. enable_restore_tty_pgrp_on_exit();
  8076. #if !BB_MMU
  8077. /* Clean up after vforked child */
  8078. free(nommu_save.argv);
  8079. free(nommu_save.argv_from_re_execing);
  8080. G.var_nest_level = sv_var_nest_level;
  8081. remove_nested_vars();
  8082. add_vars(nommu_save.old_vars);
  8083. #endif
  8084. free(argv_expanded);
  8085. argv_expanded = NULL;
  8086. if (command->pid < 0) { /* [v]fork failed */
  8087. /* Clearly indicate, was it fork or vfork */
  8088. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8089. } else {
  8090. pi->alive_cmds++;
  8091. #if ENABLE_HUSH_JOB
  8092. /* Second and next children need to know pid of first one */
  8093. if (pi->pgrp < 0)
  8094. pi->pgrp = command->pid;
  8095. #endif
  8096. }
  8097. if (cmd_no > 1)
  8098. close(next_infd);
  8099. if (cmd_no < pi->num_cmds)
  8100. close(pipefds.wr);
  8101. /* Pass read (output) pipe end to next iteration */
  8102. next_infd = pipefds.rd;
  8103. }
  8104. if (!pi->alive_cmds) {
  8105. debug_leave();
  8106. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8107. return 1;
  8108. }
  8109. debug_leave();
  8110. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8111. return -1;
  8112. }
  8113. /* NB: called by pseudo_exec, and therefore must not modify any
  8114. * global data until exec/_exit (we can be a child after vfork!) */
  8115. static int run_list(struct pipe *pi)
  8116. {
  8117. #if ENABLE_HUSH_CASE
  8118. char *case_word = NULL;
  8119. #endif
  8120. #if ENABLE_HUSH_LOOPS
  8121. struct pipe *loop_top = NULL;
  8122. char **for_lcur = NULL;
  8123. char **for_list = NULL;
  8124. #endif
  8125. smallint last_followup;
  8126. smalluint rcode;
  8127. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8128. smalluint cond_code = 0;
  8129. #else
  8130. enum { cond_code = 0 };
  8131. #endif
  8132. #if HAS_KEYWORDS
  8133. smallint rword; /* RES_foo */
  8134. smallint last_rword; /* ditto */
  8135. #endif
  8136. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8137. debug_enter();
  8138. #if ENABLE_HUSH_LOOPS
  8139. /* Check syntax for "for" */
  8140. {
  8141. struct pipe *cpipe;
  8142. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8143. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8144. continue;
  8145. /* current word is FOR or IN (BOLD in comments below) */
  8146. if (cpipe->next == NULL) {
  8147. syntax_error("malformed for");
  8148. debug_leave();
  8149. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8150. return 1;
  8151. }
  8152. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8153. if (cpipe->next->res_word == RES_DO)
  8154. continue;
  8155. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8156. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8157. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8158. ) {
  8159. syntax_error("malformed for");
  8160. debug_leave();
  8161. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8162. return 1;
  8163. }
  8164. }
  8165. }
  8166. #endif
  8167. /* Past this point, all code paths should jump to ret: label
  8168. * in order to return, no direct "return" statements please.
  8169. * This helps to ensure that no memory is leaked. */
  8170. #if ENABLE_HUSH_JOB
  8171. G.run_list_level++;
  8172. #endif
  8173. #if HAS_KEYWORDS
  8174. rword = RES_NONE;
  8175. last_rword = RES_XXXX;
  8176. #endif
  8177. last_followup = PIPE_SEQ;
  8178. rcode = G.last_exitcode;
  8179. /* Go through list of pipes, (maybe) executing them. */
  8180. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8181. int r;
  8182. int sv_errexit_depth;
  8183. if (G.flag_SIGINT)
  8184. break;
  8185. if (G_flag_return_in_progress == 1)
  8186. break;
  8187. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8188. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8189. rword, cond_code, last_rword);
  8190. sv_errexit_depth = G.errexit_depth;
  8191. if (
  8192. #if ENABLE_HUSH_IF
  8193. rword == RES_IF || rword == RES_ELIF ||
  8194. #endif
  8195. pi->followup != PIPE_SEQ
  8196. ) {
  8197. G.errexit_depth++;
  8198. }
  8199. #if ENABLE_HUSH_LOOPS
  8200. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8201. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8202. ) {
  8203. /* start of a loop: remember where loop starts */
  8204. loop_top = pi;
  8205. G.depth_of_loop++;
  8206. }
  8207. #endif
  8208. /* Still in the same "if...", "then..." or "do..." branch? */
  8209. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8210. if ((rcode == 0 && last_followup == PIPE_OR)
  8211. || (rcode != 0 && last_followup == PIPE_AND)
  8212. ) {
  8213. /* It is "<true> || CMD" or "<false> && CMD"
  8214. * and we should not execute CMD */
  8215. debug_printf_exec("skipped cmd because of || or &&\n");
  8216. last_followup = pi->followup;
  8217. goto dont_check_jobs_but_continue;
  8218. }
  8219. }
  8220. last_followup = pi->followup;
  8221. IF_HAS_KEYWORDS(last_rword = rword;)
  8222. #if ENABLE_HUSH_IF
  8223. if (cond_code) {
  8224. if (rword == RES_THEN) {
  8225. /* if false; then ... fi has exitcode 0! */
  8226. G.last_exitcode = rcode = EXIT_SUCCESS;
  8227. /* "if <false> THEN cmd": skip cmd */
  8228. continue;
  8229. }
  8230. } else {
  8231. if (rword == RES_ELSE || rword == RES_ELIF) {
  8232. /* "if <true> then ... ELSE/ELIF cmd":
  8233. * skip cmd and all following ones */
  8234. break;
  8235. }
  8236. }
  8237. #endif
  8238. #if ENABLE_HUSH_LOOPS
  8239. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8240. if (!for_lcur) {
  8241. /* first loop through for */
  8242. static const char encoded_dollar_at[] ALIGN1 = {
  8243. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8244. }; /* encoded representation of "$@" */
  8245. static const char *const encoded_dollar_at_argv[] = {
  8246. encoded_dollar_at, NULL
  8247. }; /* argv list with one element: "$@" */
  8248. char **vals;
  8249. vals = (char**)encoded_dollar_at_argv;
  8250. if (pi->next->res_word == RES_IN) {
  8251. /* if no variable values after "in" we skip "for" */
  8252. if (!pi->next->cmds[0].argv) {
  8253. G.last_exitcode = rcode = EXIT_SUCCESS;
  8254. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8255. break;
  8256. }
  8257. vals = pi->next->cmds[0].argv;
  8258. } /* else: "for var; do..." -> assume "$@" list */
  8259. /* create list of variable values */
  8260. debug_print_strings("for_list made from", vals);
  8261. for_list = expand_strvec_to_strvec(vals);
  8262. for_lcur = for_list;
  8263. debug_print_strings("for_list", for_list);
  8264. }
  8265. if (!*for_lcur) {
  8266. /* "for" loop is over, clean up */
  8267. free(for_list);
  8268. for_list = NULL;
  8269. for_lcur = NULL;
  8270. break;
  8271. }
  8272. /* Insert next value from for_lcur */
  8273. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8274. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8275. continue;
  8276. }
  8277. if (rword == RES_IN) {
  8278. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8279. }
  8280. if (rword == RES_DONE) {
  8281. continue; /* "done" has no cmds too */
  8282. }
  8283. #endif
  8284. #if ENABLE_HUSH_CASE
  8285. if (rword == RES_CASE) {
  8286. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8287. case_word = expand_string_to_string(pi->cmds->argv[0],
  8288. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8289. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8290. //unbackslash(case_word);
  8291. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8292. continue;
  8293. }
  8294. if (rword == RES_MATCH) {
  8295. char **argv;
  8296. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8297. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8298. break;
  8299. /* all prev words didn't match, does this one match? */
  8300. argv = pi->cmds->argv;
  8301. while (*argv) {
  8302. char *pattern;
  8303. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8304. pattern = expand_string_to_string(*argv,
  8305. EXP_FLAG_ESC_GLOB_CHARS,
  8306. /*unbackslash:*/ 0
  8307. );
  8308. /* TODO: which FNM_xxx flags to use? */
  8309. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8310. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8311. pattern, case_word, cond_code);
  8312. free(pattern);
  8313. if (cond_code == 0) {
  8314. /* match! we will execute this branch */
  8315. free(case_word);
  8316. case_word = NULL; /* make future "word)" stop */
  8317. break;
  8318. }
  8319. argv++;
  8320. }
  8321. continue;
  8322. }
  8323. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8324. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8325. if (cond_code != 0)
  8326. continue; /* not matched yet, skip this pipe */
  8327. }
  8328. if (rword == RES_ESAC) {
  8329. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8330. if (case_word) {
  8331. /* "case" did not match anything: still set $? (to 0) */
  8332. G.last_exitcode = rcode = EXIT_SUCCESS;
  8333. }
  8334. }
  8335. #endif
  8336. /* Just pressing <enter> in shell should check for jobs.
  8337. * OTOH, in non-interactive shell this is useless
  8338. * and only leads to extra job checks */
  8339. if (pi->num_cmds == 0) {
  8340. if (G_interactive_fd)
  8341. goto check_jobs_and_continue;
  8342. continue;
  8343. }
  8344. /* After analyzing all keywords and conditions, we decided
  8345. * to execute this pipe. NB: have to do checkjobs(NULL)
  8346. * after run_pipe to collect any background children,
  8347. * even if list execution is to be stopped. */
  8348. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8349. #if ENABLE_HUSH_LOOPS
  8350. G.flag_break_continue = 0;
  8351. #endif
  8352. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8353. if (r != -1) {
  8354. /* We ran a builtin, function, or group.
  8355. * rcode is already known
  8356. * and we don't need to wait for anything. */
  8357. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8358. G.last_exitcode = rcode;
  8359. check_and_run_traps();
  8360. #if ENABLE_HUSH_LOOPS
  8361. /* Was it "break" or "continue"? */
  8362. if (G.flag_break_continue) {
  8363. smallint fbc = G.flag_break_continue;
  8364. /* We might fall into outer *loop*,
  8365. * don't want to break it too */
  8366. if (loop_top) {
  8367. G.depth_break_continue--;
  8368. if (G.depth_break_continue == 0)
  8369. G.flag_break_continue = 0;
  8370. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8371. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8372. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8373. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8374. break;
  8375. }
  8376. /* "continue": simulate end of loop */
  8377. rword = RES_DONE;
  8378. continue;
  8379. }
  8380. #endif
  8381. if (G_flag_return_in_progress == 1) {
  8382. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8383. break;
  8384. }
  8385. } else if (pi->followup == PIPE_BG) {
  8386. /* What does bash do with attempts to background builtins? */
  8387. /* even bash 3.2 doesn't do that well with nested bg:
  8388. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8389. * I'm NOT treating inner &'s as jobs */
  8390. #if ENABLE_HUSH_JOB
  8391. if (G.run_list_level == 1)
  8392. insert_job_into_table(pi);
  8393. #endif
  8394. /* Last command's pid goes to $! */
  8395. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  8396. G.last_bg_pid_exitcode = 0;
  8397. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  8398. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  8399. rcode = EXIT_SUCCESS;
  8400. goto check_traps;
  8401. } else {
  8402. #if ENABLE_HUSH_JOB
  8403. if (G.run_list_level == 1 && G_interactive_fd) {
  8404. /* Waits for completion, then fg's main shell */
  8405. rcode = checkjobs_and_fg_shell(pi);
  8406. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  8407. goto check_traps;
  8408. }
  8409. #endif
  8410. /* This one just waits for completion */
  8411. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  8412. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  8413. check_traps:
  8414. G.last_exitcode = rcode;
  8415. check_and_run_traps();
  8416. }
  8417. /* Handle "set -e" */
  8418. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  8419. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  8420. if (G.errexit_depth == 0)
  8421. hush_exit(rcode);
  8422. }
  8423. G.errexit_depth = sv_errexit_depth;
  8424. /* Analyze how result affects subsequent commands */
  8425. #if ENABLE_HUSH_IF
  8426. if (rword == RES_IF || rword == RES_ELIF)
  8427. cond_code = rcode;
  8428. #endif
  8429. check_jobs_and_continue:
  8430. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8431. dont_check_jobs_but_continue: ;
  8432. #if ENABLE_HUSH_LOOPS
  8433. /* Beware of "while false; true; do ..."! */
  8434. if (pi->next
  8435. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  8436. /* check for RES_DONE is needed for "while ...; do \n done" case */
  8437. ) {
  8438. if (rword == RES_WHILE) {
  8439. if (rcode) {
  8440. /* "while false; do...done" - exitcode 0 */
  8441. G.last_exitcode = rcode = EXIT_SUCCESS;
  8442. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  8443. break;
  8444. }
  8445. }
  8446. if (rword == RES_UNTIL) {
  8447. if (!rcode) {
  8448. debug_printf_exec(": until expr is true: breaking\n");
  8449. break;
  8450. }
  8451. }
  8452. }
  8453. #endif
  8454. } /* for (pi) */
  8455. #if ENABLE_HUSH_JOB
  8456. G.run_list_level--;
  8457. #endif
  8458. #if ENABLE_HUSH_LOOPS
  8459. if (loop_top)
  8460. G.depth_of_loop--;
  8461. free(for_list);
  8462. #endif
  8463. #if ENABLE_HUSH_CASE
  8464. free(case_word);
  8465. #endif
  8466. debug_leave();
  8467. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  8468. return rcode;
  8469. }
  8470. /* Select which version we will use */
  8471. static int run_and_free_list(struct pipe *pi)
  8472. {
  8473. int rcode = 0;
  8474. debug_printf_exec("run_and_free_list entered\n");
  8475. if (!G.o_opt[OPT_O_NOEXEC]) {
  8476. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  8477. rcode = run_list(pi);
  8478. }
  8479. /* free_pipe_list has the side effect of clearing memory.
  8480. * In the long run that function can be merged with run_list,
  8481. * but doing that now would hobble the debugging effort. */
  8482. free_pipe_list(pi);
  8483. debug_printf_exec("run_and_free_list return %d\n", rcode);
  8484. return rcode;
  8485. }
  8486. static void install_sighandlers(unsigned mask)
  8487. {
  8488. sighandler_t old_handler;
  8489. unsigned sig = 0;
  8490. while ((mask >>= 1) != 0) {
  8491. sig++;
  8492. if (!(mask & 1))
  8493. continue;
  8494. old_handler = install_sighandler(sig, pick_sighandler(sig));
  8495. /* POSIX allows shell to re-enable SIGCHLD
  8496. * even if it was SIG_IGN on entry.
  8497. * Therefore we skip IGN check for it:
  8498. */
  8499. if (sig == SIGCHLD)
  8500. continue;
  8501. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  8502. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  8503. */
  8504. //if (sig == SIGHUP) continue; - TODO?
  8505. if (old_handler == SIG_IGN) {
  8506. /* oops... restore back to IGN, and record this fact */
  8507. install_sighandler(sig, old_handler);
  8508. #if ENABLE_HUSH_TRAP
  8509. if (!G_traps)
  8510. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  8511. free(G_traps[sig]);
  8512. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  8513. #endif
  8514. }
  8515. }
  8516. }
  8517. /* Called a few times only (or even once if "sh -c") */
  8518. static void install_special_sighandlers(void)
  8519. {
  8520. unsigned mask;
  8521. /* Which signals are shell-special? */
  8522. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  8523. if (G_interactive_fd) {
  8524. mask |= SPECIAL_INTERACTIVE_SIGS;
  8525. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  8526. mask |= SPECIAL_JOBSTOP_SIGS;
  8527. }
  8528. /* Careful, do not re-install handlers we already installed */
  8529. if (G.special_sig_mask != mask) {
  8530. unsigned diff = mask & ~G.special_sig_mask;
  8531. G.special_sig_mask = mask;
  8532. install_sighandlers(diff);
  8533. }
  8534. }
  8535. #if ENABLE_HUSH_JOB
  8536. /* helper */
  8537. /* Set handlers to restore tty pgrp and exit */
  8538. static void install_fatal_sighandlers(void)
  8539. {
  8540. unsigned mask;
  8541. /* We will restore tty pgrp on these signals */
  8542. mask = 0
  8543. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  8544. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  8545. + (1 << SIGBUS ) * HUSH_DEBUG
  8546. + (1 << SIGSEGV) * HUSH_DEBUG
  8547. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  8548. + (1 << SIGABRT)
  8549. /* bash 3.2 seems to handle these just like 'fatal' ones */
  8550. + (1 << SIGPIPE)
  8551. + (1 << SIGALRM)
  8552. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  8553. * if we aren't interactive... but in this case
  8554. * we never want to restore pgrp on exit, and this fn is not called
  8555. */
  8556. /*+ (1 << SIGHUP )*/
  8557. /*+ (1 << SIGTERM)*/
  8558. /*+ (1 << SIGINT )*/
  8559. ;
  8560. G_fatal_sig_mask = mask;
  8561. install_sighandlers(mask);
  8562. }
  8563. #endif
  8564. static int set_mode(int state, char mode, const char *o_opt)
  8565. {
  8566. int idx;
  8567. switch (mode) {
  8568. case 'n':
  8569. G.o_opt[OPT_O_NOEXEC] = state;
  8570. break;
  8571. case 'x':
  8572. IF_HUSH_MODE_X(G_x_mode = state;)
  8573. break;
  8574. case 'o':
  8575. if (!o_opt) {
  8576. /* "set -+o" without parameter.
  8577. * in bash, set -o produces this output:
  8578. * pipefail off
  8579. * and set +o:
  8580. * set +o pipefail
  8581. * We always use the second form.
  8582. */
  8583. const char *p = o_opt_strings;
  8584. idx = 0;
  8585. while (*p) {
  8586. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  8587. idx++;
  8588. p += strlen(p) + 1;
  8589. }
  8590. break;
  8591. }
  8592. idx = index_in_strings(o_opt_strings, o_opt);
  8593. if (idx >= 0) {
  8594. G.o_opt[idx] = state;
  8595. break;
  8596. }
  8597. case 'e':
  8598. G.o_opt[OPT_O_ERREXIT] = state;
  8599. break;
  8600. default:
  8601. return EXIT_FAILURE;
  8602. }
  8603. return EXIT_SUCCESS;
  8604. }
  8605. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  8606. int hush_main(int argc, char **argv)
  8607. {
  8608. enum {
  8609. OPT_login = (1 << 0),
  8610. OPT_s = (1 << 1),
  8611. };
  8612. unsigned flags;
  8613. unsigned builtin_argc;
  8614. char **e;
  8615. struct variable *cur_var;
  8616. struct variable *shell_ver;
  8617. INIT_G();
  8618. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  8619. G.last_exitcode = EXIT_SUCCESS;
  8620. #if ENABLE_HUSH_FAST
  8621. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  8622. #endif
  8623. #if !BB_MMU
  8624. G.argv0_for_re_execing = argv[0];
  8625. #endif
  8626. /* Deal with HUSH_VERSION */
  8627. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  8628. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  8629. shell_ver = xzalloc(sizeof(*shell_ver));
  8630. shell_ver->flg_export = 1;
  8631. shell_ver->flg_read_only = 1;
  8632. /* Code which handles ${var<op>...} needs writable values for all variables,
  8633. * therefore we xstrdup: */
  8634. shell_ver->varstr = xstrdup(hush_version_str);
  8635. /* Create shell local variables from the values
  8636. * currently living in the environment */
  8637. G.top_var = shell_ver;
  8638. cur_var = G.top_var;
  8639. e = environ;
  8640. if (e) while (*e) {
  8641. char *value = strchr(*e, '=');
  8642. if (value) { /* paranoia */
  8643. cur_var->next = xzalloc(sizeof(*cur_var));
  8644. cur_var = cur_var->next;
  8645. cur_var->varstr = *e;
  8646. cur_var->max_len = strlen(*e);
  8647. cur_var->flg_export = 1;
  8648. }
  8649. e++;
  8650. }
  8651. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  8652. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  8653. putenv(shell_ver->varstr);
  8654. /* Export PWD */
  8655. set_pwd_var(SETFLAG_EXPORT);
  8656. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  8657. /* Set (but not export) PS1/2 unless already set */
  8658. if (!get_local_var_value("PS1"))
  8659. set_local_var_from_halves("PS1", "\\w \\$ ");
  8660. if (!get_local_var_value("PS2"))
  8661. set_local_var_from_halves("PS2", "> ");
  8662. #endif
  8663. #if BASH_HOSTNAME_VAR
  8664. /* Set (but not export) HOSTNAME unless already set */
  8665. if (!get_local_var_value("HOSTNAME")) {
  8666. struct utsname uts;
  8667. uname(&uts);
  8668. set_local_var_from_halves("HOSTNAME", uts.nodename);
  8669. }
  8670. /* bash also exports SHLVL and _,
  8671. * and sets (but doesn't export) the following variables:
  8672. * BASH=/bin/bash
  8673. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  8674. * BASH_VERSION='3.2.0(1)-release'
  8675. * HOSTTYPE=i386
  8676. * MACHTYPE=i386-pc-linux-gnu
  8677. * OSTYPE=linux-gnu
  8678. * PPID=<NNNNN> - we also do it elsewhere
  8679. * EUID=<NNNNN>
  8680. * UID=<NNNNN>
  8681. * GROUPS=()
  8682. * LINES=<NNN>
  8683. * COLUMNS=<NNN>
  8684. * BASH_ARGC=()
  8685. * BASH_ARGV=()
  8686. * BASH_LINENO=()
  8687. * BASH_SOURCE=()
  8688. * DIRSTACK=()
  8689. * PIPESTATUS=([0]="0")
  8690. * HISTFILE=/<xxx>/.bash_history
  8691. * HISTFILESIZE=500
  8692. * HISTSIZE=500
  8693. * MAILCHECK=60
  8694. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  8695. * SHELL=/bin/bash
  8696. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  8697. * TERM=dumb
  8698. * OPTERR=1
  8699. * OPTIND=1
  8700. * IFS=$' \t\n'
  8701. * PS4='+ '
  8702. */
  8703. #endif
  8704. #if ENABLE_HUSH_LINENO_VAR
  8705. if (ENABLE_HUSH_LINENO_VAR) {
  8706. char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
  8707. set_local_var(p, /*flags*/ 0);
  8708. G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
  8709. }
  8710. #endif
  8711. #if ENABLE_FEATURE_EDITING
  8712. G.line_input_state = new_line_input_t(FOR_SHELL);
  8713. #endif
  8714. /* Initialize some more globals to non-zero values */
  8715. cmdedit_update_prompt();
  8716. die_func = restore_ttypgrp_and__exit;
  8717. /* Shell is non-interactive at first. We need to call
  8718. * install_special_sighandlers() if we are going to execute "sh <script>",
  8719. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  8720. * If we later decide that we are interactive, we run install_special_sighandlers()
  8721. * in order to intercept (more) signals.
  8722. */
  8723. /* Parse options */
  8724. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  8725. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  8726. builtin_argc = 0;
  8727. while (1) {
  8728. int opt = getopt(argc, argv, "+c:exinsl"
  8729. #if !BB_MMU
  8730. "<:$:R:V:"
  8731. # if ENABLE_HUSH_FUNCTIONS
  8732. "F:"
  8733. # endif
  8734. #endif
  8735. );
  8736. if (opt <= 0)
  8737. break;
  8738. switch (opt) {
  8739. case 'c':
  8740. /* Possibilities:
  8741. * sh ... -c 'script'
  8742. * sh ... -c 'script' ARG0 [ARG1...]
  8743. * On NOMMU, if builtin_argc != 0,
  8744. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  8745. * "" needs to be replaced with NULL
  8746. * and BARGV vector fed to builtin function.
  8747. * Note: the form without ARG0 never happens:
  8748. * sh ... -c 'builtin' BARGV... ""
  8749. */
  8750. if (!G.root_pid) {
  8751. G.root_pid = getpid();
  8752. G.root_ppid = getppid();
  8753. }
  8754. G.global_argv = argv + optind;
  8755. G.global_argc = argc - optind;
  8756. if (builtin_argc) {
  8757. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  8758. const struct built_in_command *x;
  8759. install_special_sighandlers();
  8760. x = find_builtin(optarg);
  8761. if (x) { /* paranoia */
  8762. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  8763. G.global_argv += builtin_argc;
  8764. G.global_argv[-1] = NULL; /* replace "" */
  8765. fflush_all();
  8766. G.last_exitcode = x->b_function(argv + optind - 1);
  8767. }
  8768. goto final_return;
  8769. }
  8770. if (!G.global_argv[0]) {
  8771. /* -c 'script' (no params): prevent empty $0 */
  8772. G.global_argv--; /* points to argv[i] of 'script' */
  8773. G.global_argv[0] = argv[0];
  8774. G.global_argc++;
  8775. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  8776. install_special_sighandlers();
  8777. parse_and_run_string(optarg);
  8778. goto final_return;
  8779. case 'i':
  8780. /* Well, we cannot just declare interactiveness,
  8781. * we have to have some stuff (ctty, etc) */
  8782. /* G_interactive_fd++; */
  8783. break;
  8784. case 's':
  8785. flags |= OPT_s;
  8786. break;
  8787. case 'l':
  8788. flags |= OPT_login;
  8789. break;
  8790. #if !BB_MMU
  8791. case '<': /* "big heredoc" support */
  8792. full_write1_str(optarg);
  8793. _exit(0);
  8794. case '$': {
  8795. unsigned long long empty_trap_mask;
  8796. G.root_pid = bb_strtou(optarg, &optarg, 16);
  8797. optarg++;
  8798. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  8799. optarg++;
  8800. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  8801. optarg++;
  8802. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  8803. optarg++;
  8804. builtin_argc = bb_strtou(optarg, &optarg, 16);
  8805. optarg++;
  8806. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  8807. if (empty_trap_mask != 0) {
  8808. IF_HUSH_TRAP(int sig;)
  8809. install_special_sighandlers();
  8810. # if ENABLE_HUSH_TRAP
  8811. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  8812. for (sig = 1; sig < NSIG; sig++) {
  8813. if (empty_trap_mask & (1LL << sig)) {
  8814. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  8815. install_sighandler(sig, SIG_IGN);
  8816. }
  8817. }
  8818. # endif
  8819. }
  8820. # if ENABLE_HUSH_LOOPS
  8821. optarg++;
  8822. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  8823. # endif
  8824. # if ENABLE_HUSH_FUNCTIONS
  8825. /* nommu uses re-exec trick for "... | func | ...",
  8826. * should allow "return".
  8827. * This accidentally allows returns in subshells.
  8828. */
  8829. G_flag_return_in_progress = -1;
  8830. # endif
  8831. break;
  8832. }
  8833. case 'R':
  8834. case 'V':
  8835. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  8836. break;
  8837. # if ENABLE_HUSH_FUNCTIONS
  8838. case 'F': {
  8839. struct function *funcp = new_function(optarg);
  8840. /* funcp->name is already set to optarg */
  8841. /* funcp->body is set to NULL. It's a special case. */
  8842. funcp->body_as_string = argv[optind];
  8843. optind++;
  8844. break;
  8845. }
  8846. # endif
  8847. #endif
  8848. case 'n':
  8849. case 'x':
  8850. case 'e':
  8851. if (set_mode(1, opt, NULL) == 0) /* no error */
  8852. break;
  8853. default:
  8854. #ifndef BB_VER
  8855. fprintf(stderr, "Usage: sh [FILE]...\n"
  8856. " or: sh -c command [args]...\n\n");
  8857. exit(EXIT_FAILURE);
  8858. #else
  8859. bb_show_usage();
  8860. #endif
  8861. }
  8862. } /* option parsing loop */
  8863. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  8864. G.global_argc = argc - (optind - 1);
  8865. G.global_argv = argv + (optind - 1);
  8866. G.global_argv[0] = argv[0];
  8867. if (!G.root_pid) {
  8868. G.root_pid = getpid();
  8869. G.root_ppid = getppid();
  8870. }
  8871. /* If we are login shell... */
  8872. if (flags & OPT_login) {
  8873. FILE *input;
  8874. debug_printf("sourcing /etc/profile\n");
  8875. input = fopen_for_read("/etc/profile");
  8876. if (input != NULL) {
  8877. remember_FILE(input);
  8878. install_special_sighandlers();
  8879. parse_and_run_file(input);
  8880. fclose_and_forget(input);
  8881. }
  8882. /* bash: after sourcing /etc/profile,
  8883. * tries to source (in the given order):
  8884. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  8885. * stopping on first found. --noprofile turns this off.
  8886. * bash also sources ~/.bash_logout on exit.
  8887. * If called as sh, skips .bash_XXX files.
  8888. */
  8889. }
  8890. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  8891. if (!(flags & OPT_s) && G.global_argv[1]) {
  8892. FILE *input;
  8893. /*
  8894. * "bash <script>" (which is never interactive (unless -i?))
  8895. * sources $BASH_ENV here (without scanning $PATH).
  8896. * If called as sh, does the same but with $ENV.
  8897. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  8898. */
  8899. G.global_argc--;
  8900. G.global_argv++;
  8901. debug_printf("running script '%s'\n", G.global_argv[0]);
  8902. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  8903. input = xfopen_for_read(G.global_argv[0]);
  8904. xfunc_error_retval = 1;
  8905. remember_FILE(input);
  8906. install_special_sighandlers();
  8907. parse_and_run_file(input);
  8908. #if ENABLE_FEATURE_CLEAN_UP
  8909. fclose_and_forget(input);
  8910. #endif
  8911. goto final_return;
  8912. }
  8913. /* Up to here, shell was non-interactive. Now it may become one.
  8914. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  8915. */
  8916. /* A shell is interactive if the '-i' flag was given,
  8917. * or if all of the following conditions are met:
  8918. * no -c command
  8919. * no arguments remaining or the -s flag given
  8920. * standard input is a terminal
  8921. * standard output is a terminal
  8922. * Refer to Posix.2, the description of the 'sh' utility.
  8923. */
  8924. #if ENABLE_HUSH_JOB
  8925. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  8926. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  8927. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  8928. if (G_saved_tty_pgrp < 0)
  8929. G_saved_tty_pgrp = 0;
  8930. /* try to dup stdin to high fd#, >= 255 */
  8931. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  8932. if (G_interactive_fd < 0) {
  8933. /* try to dup to any fd */
  8934. G_interactive_fd = dup(STDIN_FILENO);
  8935. if (G_interactive_fd < 0) {
  8936. /* give up */
  8937. G_interactive_fd = 0;
  8938. G_saved_tty_pgrp = 0;
  8939. }
  8940. }
  8941. // TODO: track & disallow any attempts of user
  8942. // to (inadvertently) close/redirect G_interactive_fd
  8943. }
  8944. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  8945. if (G_interactive_fd) {
  8946. close_on_exec_on(G_interactive_fd);
  8947. if (G_saved_tty_pgrp) {
  8948. /* If we were run as 'hush &', sleep until we are
  8949. * in the foreground (tty pgrp == our pgrp).
  8950. * If we get started under a job aware app (like bash),
  8951. * make sure we are now in charge so we don't fight over
  8952. * who gets the foreground */
  8953. while (1) {
  8954. pid_t shell_pgrp = getpgrp();
  8955. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  8956. if (G_saved_tty_pgrp == shell_pgrp)
  8957. break;
  8958. /* send TTIN to ourself (should stop us) */
  8959. kill(- shell_pgrp, SIGTTIN);
  8960. }
  8961. }
  8962. /* Install more signal handlers */
  8963. install_special_sighandlers();
  8964. if (G_saved_tty_pgrp) {
  8965. /* Set other signals to restore saved_tty_pgrp */
  8966. install_fatal_sighandlers();
  8967. /* Put ourselves in our own process group
  8968. * (bash, too, does this only if ctty is available) */
  8969. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  8970. /* Grab control of the terminal */
  8971. tcsetpgrp(G_interactive_fd, getpid());
  8972. }
  8973. enable_restore_tty_pgrp_on_exit();
  8974. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  8975. {
  8976. const char *hp = get_local_var_value("HISTFILE");
  8977. if (!hp) {
  8978. hp = get_local_var_value("HOME");
  8979. if (hp)
  8980. hp = concat_path_file(hp, ".hush_history");
  8981. } else {
  8982. hp = xstrdup(hp);
  8983. }
  8984. if (hp) {
  8985. G.line_input_state->hist_file = hp;
  8986. //set_local_var(xasprintf("HISTFILE=%s", ...));
  8987. }
  8988. # if ENABLE_FEATURE_SH_HISTFILESIZE
  8989. hp = get_local_var_value("HISTFILESIZE");
  8990. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  8991. # endif
  8992. }
  8993. # endif
  8994. } else {
  8995. install_special_sighandlers();
  8996. }
  8997. #elif ENABLE_HUSH_INTERACTIVE
  8998. /* No job control compiled in, only prompt/line editing */
  8999. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9000. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9001. if (G_interactive_fd < 0) {
  9002. /* try to dup to any fd */
  9003. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9004. if (G_interactive_fd < 0)
  9005. /* give up */
  9006. G_interactive_fd = 0;
  9007. }
  9008. }
  9009. if (G_interactive_fd) {
  9010. close_on_exec_on(G_interactive_fd);
  9011. }
  9012. install_special_sighandlers();
  9013. #else
  9014. /* We have interactiveness code disabled */
  9015. install_special_sighandlers();
  9016. #endif
  9017. /* bash:
  9018. * if interactive but not a login shell, sources ~/.bashrc
  9019. * (--norc turns this off, --rcfile <file> overrides)
  9020. */
  9021. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  9022. /* note: ash and hush share this string */
  9023. printf("\n\n%s %s\n"
  9024. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9025. "\n",
  9026. bb_banner,
  9027. "hush - the humble shell"
  9028. );
  9029. }
  9030. parse_and_run_file(stdin);
  9031. final_return:
  9032. hush_exit(G.last_exitcode);
  9033. }
  9034. /*
  9035. * Built-ins
  9036. */
  9037. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9038. {
  9039. return 0;
  9040. }
  9041. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9042. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9043. {
  9044. int argc = string_array_len(argv);
  9045. return applet_main_func(argc, argv);
  9046. }
  9047. #endif
  9048. #if ENABLE_HUSH_TEST || BASH_TEST2
  9049. static int FAST_FUNC builtin_test(char **argv)
  9050. {
  9051. return run_applet_main(argv, test_main);
  9052. }
  9053. #endif
  9054. #if ENABLE_HUSH_ECHO
  9055. static int FAST_FUNC builtin_echo(char **argv)
  9056. {
  9057. return run_applet_main(argv, echo_main);
  9058. }
  9059. #endif
  9060. #if ENABLE_HUSH_PRINTF
  9061. static int FAST_FUNC builtin_printf(char **argv)
  9062. {
  9063. return run_applet_main(argv, printf_main);
  9064. }
  9065. #endif
  9066. #if ENABLE_HUSH_HELP
  9067. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9068. {
  9069. const struct built_in_command *x;
  9070. printf(
  9071. "Built-in commands:\n"
  9072. "------------------\n");
  9073. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9074. if (x->b_descr)
  9075. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9076. }
  9077. return EXIT_SUCCESS;
  9078. }
  9079. #endif
  9080. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9081. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9082. {
  9083. show_history(G.line_input_state);
  9084. return EXIT_SUCCESS;
  9085. }
  9086. #endif
  9087. static char **skip_dash_dash(char **argv)
  9088. {
  9089. argv++;
  9090. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9091. argv++;
  9092. return argv;
  9093. }
  9094. static int FAST_FUNC builtin_cd(char **argv)
  9095. {
  9096. const char *newdir;
  9097. argv = skip_dash_dash(argv);
  9098. newdir = argv[0];
  9099. if (newdir == NULL) {
  9100. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9101. * bash says "bash: cd: HOME not set" and does nothing
  9102. * (exitcode 1)
  9103. */
  9104. const char *home = get_local_var_value("HOME");
  9105. newdir = home ? home : "/";
  9106. }
  9107. if (chdir(newdir)) {
  9108. /* Mimic bash message exactly */
  9109. bb_perror_msg("cd: %s", newdir);
  9110. return EXIT_FAILURE;
  9111. }
  9112. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9113. * Note: do not enforce exporting. If PWD was unset or unexported,
  9114. * set it again, but do not export. bash does the same.
  9115. */
  9116. set_pwd_var(/*flag:*/ 0);
  9117. return EXIT_SUCCESS;
  9118. }
  9119. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9120. {
  9121. puts(get_cwd(0));
  9122. return EXIT_SUCCESS;
  9123. }
  9124. static int FAST_FUNC builtin_eval(char **argv)
  9125. {
  9126. int rcode = EXIT_SUCCESS;
  9127. argv = skip_dash_dash(argv);
  9128. if (argv[0]) {
  9129. char *str = NULL;
  9130. if (argv[1]) {
  9131. /* "The eval utility shall construct a command by
  9132. * concatenating arguments together, separating
  9133. * each with a <space> character."
  9134. */
  9135. char *p;
  9136. unsigned len = 0;
  9137. char **pp = argv;
  9138. do
  9139. len += strlen(*pp) + 1;
  9140. while (*++pp);
  9141. str = p = xmalloc(len);
  9142. pp = argv;
  9143. do {
  9144. p = stpcpy(p, *pp);
  9145. *p++ = ' ';
  9146. } while (*++pp);
  9147. p[-1] = '\0';
  9148. }
  9149. /* bash:
  9150. * eval "echo Hi; done" ("done" is syntax error):
  9151. * "echo Hi" will not execute too.
  9152. */
  9153. parse_and_run_string(str ? str : argv[0]);
  9154. free(str);
  9155. rcode = G.last_exitcode;
  9156. }
  9157. return rcode;
  9158. }
  9159. static int FAST_FUNC builtin_exec(char **argv)
  9160. {
  9161. argv = skip_dash_dash(argv);
  9162. if (argv[0] == NULL)
  9163. return EXIT_SUCCESS; /* bash does this */
  9164. /* Careful: we can end up here after [v]fork. Do not restore
  9165. * tty pgrp then, only top-level shell process does that */
  9166. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9167. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9168. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9169. * open here. However, they are all CLOEXEC, and execv below
  9170. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9171. * it should show no extra open fds in the "ls" process.
  9172. * If we'd try to run builtins/NOEXECs, this would need improving.
  9173. */
  9174. //close_saved_fds_and_FILE_fds();
  9175. /* TODO: if exec fails, bash does NOT exit! We do.
  9176. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9177. * and tcsetpgrp, and this is inherently racy.
  9178. */
  9179. execvp_or_die(argv);
  9180. }
  9181. static int FAST_FUNC builtin_exit(char **argv)
  9182. {
  9183. debug_printf_exec("%s()\n", __func__);
  9184. /* interactive bash:
  9185. * # trap "echo EEE" EXIT
  9186. * # exit
  9187. * exit
  9188. * There are stopped jobs.
  9189. * (if there are _stopped_ jobs, running ones don't count)
  9190. * # exit
  9191. * exit
  9192. * EEE (then bash exits)
  9193. *
  9194. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9195. */
  9196. /* note: EXIT trap is run by hush_exit */
  9197. argv = skip_dash_dash(argv);
  9198. if (argv[0] == NULL)
  9199. hush_exit(G.last_exitcode);
  9200. /* mimic bash: exit 123abc == exit 255 + error msg */
  9201. xfunc_error_retval = 255;
  9202. /* bash: exit -2 == exit 254, no error msg */
  9203. hush_exit(xatoi(argv[0]) & 0xff);
  9204. }
  9205. #if ENABLE_HUSH_TYPE
  9206. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9207. static int FAST_FUNC builtin_type(char **argv)
  9208. {
  9209. int ret = EXIT_SUCCESS;
  9210. while (*++argv) {
  9211. const char *type;
  9212. char *path = NULL;
  9213. if (0) {} /* make conditional compile easier below */
  9214. /*else if (find_alias(*argv))
  9215. type = "an alias";*/
  9216. #if ENABLE_HUSH_FUNCTIONS
  9217. else if (find_function(*argv))
  9218. type = "a function";
  9219. #endif
  9220. else if (find_builtin(*argv))
  9221. type = "a shell builtin";
  9222. else if ((path = find_in_path(*argv)) != NULL)
  9223. type = path;
  9224. else {
  9225. bb_error_msg("type: %s: not found", *argv);
  9226. ret = EXIT_FAILURE;
  9227. continue;
  9228. }
  9229. printf("%s is %s\n", *argv, type);
  9230. free(path);
  9231. }
  9232. return ret;
  9233. }
  9234. #endif
  9235. #if ENABLE_HUSH_READ
  9236. /* Interruptibility of read builtin in bash
  9237. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9238. *
  9239. * Empty trap makes read ignore corresponding signal, for any signal.
  9240. *
  9241. * SIGINT:
  9242. * - terminates non-interactive shell;
  9243. * - interrupts read in interactive shell;
  9244. * if it has non-empty trap:
  9245. * - executes trap and returns to command prompt in interactive shell;
  9246. * - executes trap and returns to read in non-interactive shell;
  9247. * SIGTERM:
  9248. * - is ignored (does not interrupt) read in interactive shell;
  9249. * - terminates non-interactive shell;
  9250. * if it has non-empty trap:
  9251. * - executes trap and returns to read;
  9252. * SIGHUP:
  9253. * - terminates shell (regardless of interactivity);
  9254. * if it has non-empty trap:
  9255. * - executes trap and returns to read;
  9256. * SIGCHLD from children:
  9257. * - does not interrupt read regardless of interactivity:
  9258. * try: sleep 1 & read x; echo $x
  9259. */
  9260. static int FAST_FUNC builtin_read(char **argv)
  9261. {
  9262. const char *r;
  9263. char *opt_n = NULL;
  9264. char *opt_p = NULL;
  9265. char *opt_t = NULL;
  9266. char *opt_u = NULL;
  9267. char *opt_d = NULL; /* optimized out if !BASH */
  9268. const char *ifs;
  9269. int read_flags;
  9270. /* "!": do not abort on errors.
  9271. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9272. */
  9273. read_flags = getopt32(argv,
  9274. #if BASH_READ_D
  9275. "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
  9276. #else
  9277. "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
  9278. #endif
  9279. );
  9280. if (read_flags == (uint32_t)-1)
  9281. return EXIT_FAILURE;
  9282. argv += optind;
  9283. ifs = get_local_var_value("IFS"); /* can be NULL */
  9284. again:
  9285. r = shell_builtin_read(set_local_var_from_halves,
  9286. argv,
  9287. ifs,
  9288. read_flags,
  9289. opt_n,
  9290. opt_p,
  9291. opt_t,
  9292. opt_u,
  9293. opt_d
  9294. );
  9295. if ((uintptr_t)r == 1 && errno == EINTR) {
  9296. unsigned sig = check_and_run_traps();
  9297. if (sig != SIGINT)
  9298. goto again;
  9299. }
  9300. if ((uintptr_t)r > 1) {
  9301. bb_error_msg("%s", r);
  9302. r = (char*)(uintptr_t)1;
  9303. }
  9304. return (uintptr_t)r;
  9305. }
  9306. #endif
  9307. #if ENABLE_HUSH_UMASK
  9308. static int FAST_FUNC builtin_umask(char **argv)
  9309. {
  9310. int rc;
  9311. mode_t mask;
  9312. rc = 1;
  9313. mask = umask(0);
  9314. argv = skip_dash_dash(argv);
  9315. if (argv[0]) {
  9316. mode_t old_mask = mask;
  9317. /* numeric umasks are taken as-is */
  9318. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9319. if (!isdigit(argv[0][0]))
  9320. mask ^= 0777;
  9321. mask = bb_parse_mode(argv[0], mask);
  9322. if (!isdigit(argv[0][0]))
  9323. mask ^= 0777;
  9324. if ((unsigned)mask > 0777) {
  9325. mask = old_mask;
  9326. /* bash messages:
  9327. * bash: umask: 'q': invalid symbolic mode operator
  9328. * bash: umask: 999: octal number out of range
  9329. */
  9330. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9331. rc = 0;
  9332. }
  9333. } else {
  9334. /* Mimic bash */
  9335. printf("%04o\n", (unsigned) mask);
  9336. /* fall through and restore mask which we set to 0 */
  9337. }
  9338. umask(mask);
  9339. return !rc; /* rc != 0 - success */
  9340. }
  9341. #endif
  9342. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9343. static void print_escaped(const char *s)
  9344. {
  9345. if (*s == '\'')
  9346. goto squote;
  9347. do {
  9348. const char *p = strchrnul(s, '\'');
  9349. /* print 'xxxx', possibly just '' */
  9350. printf("'%.*s'", (int)(p - s), s);
  9351. if (*p == '\0')
  9352. break;
  9353. s = p;
  9354. squote:
  9355. /* s points to '; print "'''...'''" */
  9356. putchar('"');
  9357. do putchar('\''); while (*++s == '\'');
  9358. putchar('"');
  9359. } while (*s);
  9360. }
  9361. #endif
  9362. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9363. static int helper_export_local(char **argv, unsigned flags)
  9364. {
  9365. do {
  9366. char *name = *argv;
  9367. char *name_end = strchrnul(name, '=');
  9368. /* So far we do not check that name is valid (TODO?) */
  9369. if (*name_end == '\0') {
  9370. struct variable *var, **vpp;
  9371. vpp = get_ptr_to_local_var(name, name_end - name);
  9372. var = vpp ? *vpp : NULL;
  9373. if (flags & SETFLAG_UNEXPORT) {
  9374. /* export -n NAME (without =VALUE) */
  9375. if (var) {
  9376. var->flg_export = 0;
  9377. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9378. unsetenv(name);
  9379. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9380. continue;
  9381. }
  9382. if (flags & SETFLAG_EXPORT) {
  9383. /* export NAME (without =VALUE) */
  9384. if (var) {
  9385. var->flg_export = 1;
  9386. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  9387. putenv(var->varstr);
  9388. continue;
  9389. }
  9390. }
  9391. if (flags & SETFLAG_MAKE_RO) {
  9392. /* readonly NAME (without =VALUE) */
  9393. if (var) {
  9394. var->flg_read_only = 1;
  9395. continue;
  9396. }
  9397. }
  9398. # if ENABLE_HUSH_LOCAL
  9399. /* Is this "local" bltin? */
  9400. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  9401. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  9402. if (var && var->var_nest_level == lvl) {
  9403. /* "local x=abc; ...; local x" - ignore second local decl */
  9404. continue;
  9405. }
  9406. }
  9407. # endif
  9408. /* Exporting non-existing variable.
  9409. * bash does not put it in environment,
  9410. * but remembers that it is exported,
  9411. * and does put it in env when it is set later.
  9412. * We just set it to "" and export.
  9413. */
  9414. /* Or, it's "local NAME" (without =VALUE).
  9415. * bash sets the value to "".
  9416. */
  9417. /* Or, it's "readonly NAME" (without =VALUE).
  9418. * bash remembers NAME and disallows its creation
  9419. * in the future.
  9420. */
  9421. name = xasprintf("%s=", name);
  9422. } else {
  9423. /* (Un)exporting/making local NAME=VALUE */
  9424. name = xstrdup(name);
  9425. }
  9426. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  9427. if (set_local_var(name, flags))
  9428. return EXIT_FAILURE;
  9429. } while (*++argv);
  9430. return EXIT_SUCCESS;
  9431. }
  9432. #endif
  9433. #if ENABLE_HUSH_EXPORT
  9434. static int FAST_FUNC builtin_export(char **argv)
  9435. {
  9436. unsigned opt_unexport;
  9437. #if ENABLE_HUSH_EXPORT_N
  9438. /* "!": do not abort on errors */
  9439. opt_unexport = getopt32(argv, "!n");
  9440. if (opt_unexport == (uint32_t)-1)
  9441. return EXIT_FAILURE;
  9442. argv += optind;
  9443. #else
  9444. opt_unexport = 0;
  9445. argv++;
  9446. #endif
  9447. if (argv[0] == NULL) {
  9448. char **e = environ;
  9449. if (e) {
  9450. while (*e) {
  9451. #if 0
  9452. puts(*e++);
  9453. #else
  9454. /* ash emits: export VAR='VAL'
  9455. * bash: declare -x VAR="VAL"
  9456. * we follow ash example */
  9457. const char *s = *e++;
  9458. const char *p = strchr(s, '=');
  9459. if (!p) /* wtf? take next variable */
  9460. continue;
  9461. /* export var= */
  9462. printf("export %.*s", (int)(p - s) + 1, s);
  9463. print_escaped(p + 1);
  9464. putchar('\n');
  9465. #endif
  9466. }
  9467. /*fflush_all(); - done after each builtin anyway */
  9468. }
  9469. return EXIT_SUCCESS;
  9470. }
  9471. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  9472. }
  9473. #endif
  9474. #if ENABLE_HUSH_LOCAL
  9475. static int FAST_FUNC builtin_local(char **argv)
  9476. {
  9477. if (G.func_nest_level == 0) {
  9478. bb_error_msg("%s: not in a function", argv[0]);
  9479. return EXIT_FAILURE; /* bash compat */
  9480. }
  9481. argv++;
  9482. /* Since all builtins run in a nested variable level,
  9483. * need to use level - 1 here. Or else the variable will be removed at once
  9484. * after builtin returns.
  9485. */
  9486. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  9487. }
  9488. #endif
  9489. #if ENABLE_HUSH_READONLY
  9490. static int FAST_FUNC builtin_readonly(char **argv)
  9491. {
  9492. argv++;
  9493. if (*argv == NULL) {
  9494. /* bash: readonly [-p]: list all readonly VARs
  9495. * (-p has no effect in bash)
  9496. */
  9497. struct variable *e;
  9498. for (e = G.top_var; e; e = e->next) {
  9499. if (e->flg_read_only) {
  9500. //TODO: quote value: readonly VAR='VAL'
  9501. printf("readonly %s\n", e->varstr);
  9502. }
  9503. }
  9504. return EXIT_SUCCESS;
  9505. }
  9506. return helper_export_local(argv, SETFLAG_MAKE_RO);
  9507. }
  9508. #endif
  9509. #if ENABLE_HUSH_UNSET
  9510. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  9511. static int FAST_FUNC builtin_unset(char **argv)
  9512. {
  9513. int ret;
  9514. unsigned opts;
  9515. /* "!": do not abort on errors */
  9516. /* "+": stop at 1st non-option */
  9517. opts = getopt32(argv, "!+vf");
  9518. if (opts == (unsigned)-1)
  9519. return EXIT_FAILURE;
  9520. if (opts == 3) {
  9521. bb_error_msg("unset: -v and -f are exclusive");
  9522. return EXIT_FAILURE;
  9523. }
  9524. argv += optind;
  9525. ret = EXIT_SUCCESS;
  9526. while (*argv) {
  9527. if (!(opts & 2)) { /* not -f */
  9528. if (unset_local_var(*argv)) {
  9529. /* unset <nonexistent_var> doesn't fail.
  9530. * Error is when one tries to unset RO var.
  9531. * Message was printed by unset_local_var. */
  9532. ret = EXIT_FAILURE;
  9533. }
  9534. }
  9535. # if ENABLE_HUSH_FUNCTIONS
  9536. else {
  9537. unset_func(*argv);
  9538. }
  9539. # endif
  9540. argv++;
  9541. }
  9542. return ret;
  9543. }
  9544. #endif
  9545. #if ENABLE_HUSH_SET
  9546. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  9547. * built-in 'set' handler
  9548. * SUSv3 says:
  9549. * set [-abCefhmnuvx] [-o option] [argument...]
  9550. * set [+abCefhmnuvx] [+o option] [argument...]
  9551. * set -- [argument...]
  9552. * set -o
  9553. * set +o
  9554. * Implementations shall support the options in both their hyphen and
  9555. * plus-sign forms. These options can also be specified as options to sh.
  9556. * Examples:
  9557. * Write out all variables and their values: set
  9558. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  9559. * Turn on the -x and -v options: set -xv
  9560. * Unset all positional parameters: set --
  9561. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  9562. * Set the positional parameters to the expansion of x, even if x expands
  9563. * with a leading '-' or '+': set -- $x
  9564. *
  9565. * So far, we only support "set -- [argument...]" and some of the short names.
  9566. */
  9567. static int FAST_FUNC builtin_set(char **argv)
  9568. {
  9569. int n;
  9570. char **pp, **g_argv;
  9571. char *arg = *++argv;
  9572. if (arg == NULL) {
  9573. struct variable *e;
  9574. for (e = G.top_var; e; e = e->next)
  9575. puts(e->varstr);
  9576. return EXIT_SUCCESS;
  9577. }
  9578. do {
  9579. if (strcmp(arg, "--") == 0) {
  9580. ++argv;
  9581. goto set_argv;
  9582. }
  9583. if (arg[0] != '+' && arg[0] != '-')
  9584. break;
  9585. for (n = 1; arg[n]; ++n) {
  9586. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  9587. goto error;
  9588. if (arg[n] == 'o' && argv[1])
  9589. argv++;
  9590. }
  9591. } while ((arg = *++argv) != NULL);
  9592. /* Now argv[0] is 1st argument */
  9593. if (arg == NULL)
  9594. return EXIT_SUCCESS;
  9595. set_argv:
  9596. /* NB: G.global_argv[0] ($0) is never freed/changed */
  9597. g_argv = G.global_argv;
  9598. if (G.global_args_malloced) {
  9599. pp = g_argv;
  9600. while (*++pp)
  9601. free(*pp);
  9602. g_argv[1] = NULL;
  9603. } else {
  9604. G.global_args_malloced = 1;
  9605. pp = xzalloc(sizeof(pp[0]) * 2);
  9606. pp[0] = g_argv[0]; /* retain $0 */
  9607. g_argv = pp;
  9608. }
  9609. /* This realloc's G.global_argv */
  9610. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  9611. G.global_argc = 1 + string_array_len(pp + 1);
  9612. return EXIT_SUCCESS;
  9613. /* Nothing known, so abort */
  9614. error:
  9615. bb_error_msg("%s: %s: invalid option", "set", arg);
  9616. return EXIT_FAILURE;
  9617. }
  9618. #endif
  9619. static int FAST_FUNC builtin_shift(char **argv)
  9620. {
  9621. int n = 1;
  9622. argv = skip_dash_dash(argv);
  9623. if (argv[0]) {
  9624. n = bb_strtou(argv[0], NULL, 10);
  9625. if (errno || n < 0) {
  9626. /* shared string with ash.c */
  9627. bb_error_msg("Illegal number: %s", argv[0]);
  9628. /*
  9629. * ash aborts in this case.
  9630. * bash prints error message and set $? to 1.
  9631. * Interestingly, for "shift 99999" bash does not
  9632. * print error message, but does set $? to 1
  9633. * (and does no shifting at all).
  9634. */
  9635. }
  9636. }
  9637. if (n >= 0 && n < G.global_argc) {
  9638. if (G_global_args_malloced) {
  9639. int m = 1;
  9640. while (m <= n)
  9641. free(G.global_argv[m++]);
  9642. }
  9643. G.global_argc -= n;
  9644. memmove(&G.global_argv[1], &G.global_argv[n+1],
  9645. G.global_argc * sizeof(G.global_argv[0]));
  9646. return EXIT_SUCCESS;
  9647. }
  9648. return EXIT_FAILURE;
  9649. }
  9650. #if ENABLE_HUSH_GETOPTS
  9651. static int FAST_FUNC builtin_getopts(char **argv)
  9652. {
  9653. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  9654. TODO:
  9655. If a required argument is not found, and getopts is not silent,
  9656. a question mark (?) is placed in VAR, OPTARG is unset, and a
  9657. diagnostic message is printed. If getopts is silent, then a
  9658. colon (:) is placed in VAR and OPTARG is set to the option
  9659. character found.
  9660. Test that VAR is a valid variable name?
  9661. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  9662. */
  9663. char cbuf[2];
  9664. const char *cp, *optstring, *var;
  9665. int c, n, exitcode, my_opterr;
  9666. unsigned count;
  9667. optstring = *++argv;
  9668. if (!optstring || !(var = *++argv)) {
  9669. bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  9670. return EXIT_FAILURE;
  9671. }
  9672. if (argv[1])
  9673. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  9674. else
  9675. argv = G.global_argv;
  9676. cbuf[1] = '\0';
  9677. my_opterr = 0;
  9678. if (optstring[0] != ':') {
  9679. cp = get_local_var_value("OPTERR");
  9680. /* 0 if "OPTERR=0", 1 otherwise */
  9681. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  9682. }
  9683. /* getopts stops on first non-option. Add "+" to force that */
  9684. /*if (optstring[0] != '+')*/ {
  9685. char *s = alloca(strlen(optstring) + 2);
  9686. sprintf(s, "+%s", optstring);
  9687. optstring = s;
  9688. }
  9689. /* Naively, now we should just
  9690. * cp = get_local_var_value("OPTIND");
  9691. * optind = cp ? atoi(cp) : 0;
  9692. * optarg = NULL;
  9693. * opterr = my_opterr;
  9694. * c = getopt(string_array_len(argv), argv, optstring);
  9695. * and be done? Not so fast...
  9696. * Unlike normal getopt() usage in C programs, here
  9697. * each successive call will (usually) have the same argv[] CONTENTS,
  9698. * but not the ADDRESSES. Worse yet, it's possible that between
  9699. * invocations of "getopts", there will be calls to shell builtins
  9700. * which use getopt() internally. Example:
  9701. * while getopts "abc" RES -a -bc -abc de; do
  9702. * unset -ff func
  9703. * done
  9704. * This would not work correctly: getopt() call inside "unset"
  9705. * modifies internal libc state which is tracking position in
  9706. * multi-option strings ("-abc"). At best, it can skip options
  9707. * or return the same option infinitely. With glibc implementation
  9708. * of getopt(), it would use outright invalid pointers and return
  9709. * garbage even _without_ "unset" mangling internal state.
  9710. *
  9711. * We resort to resetting getopt() state and calling it N times,
  9712. * until we get Nth result (or failure).
  9713. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  9714. */
  9715. GETOPT_RESET();
  9716. count = 0;
  9717. n = string_array_len(argv);
  9718. do {
  9719. optarg = NULL;
  9720. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  9721. c = getopt(n, argv, optstring);
  9722. if (c < 0)
  9723. break;
  9724. count++;
  9725. } while (count <= G.getopt_count);
  9726. /* Set OPTIND. Prevent resetting of the magic counter! */
  9727. set_local_var_from_halves("OPTIND", utoa(optind));
  9728. G.getopt_count = count; /* "next time, give me N+1'th result" */
  9729. GETOPT_RESET(); /* just in case */
  9730. /* Set OPTARG */
  9731. /* Always set or unset, never left as-is, even on exit/error:
  9732. * "If no option was found, or if the option that was found
  9733. * does not have an option-argument, OPTARG shall be unset."
  9734. */
  9735. cp = optarg;
  9736. if (c == '?') {
  9737. /* If ":optstring" and unknown option is seen,
  9738. * it is stored to OPTARG.
  9739. */
  9740. if (optstring[1] == ':') {
  9741. cbuf[0] = optopt;
  9742. cp = cbuf;
  9743. }
  9744. }
  9745. if (cp)
  9746. set_local_var_from_halves("OPTARG", cp);
  9747. else
  9748. unset_local_var("OPTARG");
  9749. /* Convert -1 to "?" */
  9750. exitcode = EXIT_SUCCESS;
  9751. if (c < 0) { /* -1: end of options */
  9752. exitcode = EXIT_FAILURE;
  9753. c = '?';
  9754. }
  9755. /* Set VAR */
  9756. cbuf[0] = c;
  9757. set_local_var_from_halves(var, cbuf);
  9758. return exitcode;
  9759. }
  9760. #endif
  9761. static int FAST_FUNC builtin_source(char **argv)
  9762. {
  9763. char *arg_path, *filename;
  9764. FILE *input;
  9765. save_arg_t sv;
  9766. char *args_need_save;
  9767. #if ENABLE_HUSH_FUNCTIONS
  9768. smallint sv_flg;
  9769. #endif
  9770. argv = skip_dash_dash(argv);
  9771. filename = argv[0];
  9772. if (!filename) {
  9773. /* bash says: "bash: .: filename argument required" */
  9774. return 2; /* bash compat */
  9775. }
  9776. arg_path = NULL;
  9777. if (!strchr(filename, '/')) {
  9778. arg_path = find_in_path(filename);
  9779. if (arg_path)
  9780. filename = arg_path;
  9781. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  9782. errno = ENOENT;
  9783. bb_simple_perror_msg(filename);
  9784. return EXIT_FAILURE;
  9785. }
  9786. }
  9787. input = remember_FILE(fopen_or_warn(filename, "r"));
  9788. free(arg_path);
  9789. if (!input) {
  9790. /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
  9791. /* POSIX: non-interactive shell should abort here,
  9792. * not merely fail. So far no one complained :)
  9793. */
  9794. return EXIT_FAILURE;
  9795. }
  9796. #if ENABLE_HUSH_FUNCTIONS
  9797. sv_flg = G_flag_return_in_progress;
  9798. /* "we are inside sourced file, ok to use return" */
  9799. G_flag_return_in_progress = -1;
  9800. #endif
  9801. args_need_save = argv[1]; /* used as a boolean variable */
  9802. if (args_need_save)
  9803. save_and_replace_G_args(&sv, argv);
  9804. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  9805. G.last_exitcode = 0;
  9806. parse_and_run_file(input);
  9807. fclose_and_forget(input);
  9808. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  9809. restore_G_args(&sv, argv);
  9810. #if ENABLE_HUSH_FUNCTIONS
  9811. G_flag_return_in_progress = sv_flg;
  9812. #endif
  9813. return G.last_exitcode;
  9814. }
  9815. #if ENABLE_HUSH_TRAP
  9816. static int FAST_FUNC builtin_trap(char **argv)
  9817. {
  9818. int sig;
  9819. char *new_cmd;
  9820. if (!G_traps)
  9821. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9822. argv++;
  9823. if (!*argv) {
  9824. int i;
  9825. /* No args: print all trapped */
  9826. for (i = 0; i < NSIG; ++i) {
  9827. if (G_traps[i]) {
  9828. printf("trap -- ");
  9829. print_escaped(G_traps[i]);
  9830. /* note: bash adds "SIG", but only if invoked
  9831. * as "bash". If called as "sh", or if set -o posix,
  9832. * then it prints short signal names.
  9833. * We are printing short names: */
  9834. printf(" %s\n", get_signame(i));
  9835. }
  9836. }
  9837. /*fflush_all(); - done after each builtin anyway */
  9838. return EXIT_SUCCESS;
  9839. }
  9840. new_cmd = NULL;
  9841. /* If first arg is a number: reset all specified signals */
  9842. sig = bb_strtou(*argv, NULL, 10);
  9843. if (errno == 0) {
  9844. int ret;
  9845. process_sig_list:
  9846. ret = EXIT_SUCCESS;
  9847. while (*argv) {
  9848. sighandler_t handler;
  9849. sig = get_signum(*argv++);
  9850. if (sig < 0) {
  9851. ret = EXIT_FAILURE;
  9852. /* Mimic bash message exactly */
  9853. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  9854. continue;
  9855. }
  9856. free(G_traps[sig]);
  9857. G_traps[sig] = xstrdup(new_cmd);
  9858. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  9859. get_signame(sig), sig, G_traps[sig]);
  9860. /* There is no signal for 0 (EXIT) */
  9861. if (sig == 0)
  9862. continue;
  9863. if (new_cmd)
  9864. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  9865. else
  9866. /* We are removing trap handler */
  9867. handler = pick_sighandler(sig);
  9868. install_sighandler(sig, handler);
  9869. }
  9870. return ret;
  9871. }
  9872. if (!argv[1]) { /* no second arg */
  9873. bb_error_msg("trap: invalid arguments");
  9874. return EXIT_FAILURE;
  9875. }
  9876. /* First arg is "-": reset all specified to default */
  9877. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  9878. /* Everything else: set arg as signal handler
  9879. * (includes "" case, which ignores signal) */
  9880. if (argv[0][0] == '-') {
  9881. if (argv[0][1] == '\0') { /* "-" */
  9882. /* new_cmd remains NULL: "reset these sigs" */
  9883. goto reset_traps;
  9884. }
  9885. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  9886. argv++;
  9887. }
  9888. /* else: "-something", no special meaning */
  9889. }
  9890. new_cmd = *argv;
  9891. reset_traps:
  9892. argv++;
  9893. goto process_sig_list;
  9894. }
  9895. #endif
  9896. #if ENABLE_HUSH_JOB
  9897. static struct pipe *parse_jobspec(const char *str)
  9898. {
  9899. struct pipe *pi;
  9900. unsigned jobnum;
  9901. if (sscanf(str, "%%%u", &jobnum) != 1) {
  9902. if (str[0] != '%'
  9903. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  9904. ) {
  9905. bb_error_msg("bad argument '%s'", str);
  9906. return NULL;
  9907. }
  9908. /* It is "%%", "%+" or "%" - current job */
  9909. jobnum = G.last_jobid;
  9910. if (jobnum == 0) {
  9911. bb_error_msg("no current job");
  9912. return NULL;
  9913. }
  9914. }
  9915. for (pi = G.job_list; pi; pi = pi->next) {
  9916. if (pi->jobid == jobnum) {
  9917. return pi;
  9918. }
  9919. }
  9920. bb_error_msg("%u: no such job", jobnum);
  9921. return NULL;
  9922. }
  9923. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  9924. {
  9925. struct pipe *job;
  9926. const char *status_string;
  9927. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9928. for (job = G.job_list; job; job = job->next) {
  9929. if (job->alive_cmds == job->stopped_cmds)
  9930. status_string = "Stopped";
  9931. else
  9932. status_string = "Running";
  9933. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  9934. }
  9935. clean_up_last_dead_job();
  9936. return EXIT_SUCCESS;
  9937. }
  9938. /* built-in 'fg' and 'bg' handler */
  9939. static int FAST_FUNC builtin_fg_bg(char **argv)
  9940. {
  9941. int i;
  9942. struct pipe *pi;
  9943. if (!G_interactive_fd)
  9944. return EXIT_FAILURE;
  9945. /* If they gave us no args, assume they want the last backgrounded task */
  9946. if (!argv[1]) {
  9947. for (pi = G.job_list; pi; pi = pi->next) {
  9948. if (pi->jobid == G.last_jobid) {
  9949. goto found;
  9950. }
  9951. }
  9952. bb_error_msg("%s: no current job", argv[0]);
  9953. return EXIT_FAILURE;
  9954. }
  9955. pi = parse_jobspec(argv[1]);
  9956. if (!pi)
  9957. return EXIT_FAILURE;
  9958. found:
  9959. /* TODO: bash prints a string representation
  9960. * of job being foregrounded (like "sleep 1 | cat") */
  9961. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  9962. /* Put the job into the foreground. */
  9963. tcsetpgrp(G_interactive_fd, pi->pgrp);
  9964. }
  9965. /* Restart the processes in the job */
  9966. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  9967. for (i = 0; i < pi->num_cmds; i++) {
  9968. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  9969. }
  9970. pi->stopped_cmds = 0;
  9971. i = kill(- pi->pgrp, SIGCONT);
  9972. if (i < 0) {
  9973. if (errno == ESRCH) {
  9974. delete_finished_job(pi);
  9975. return EXIT_SUCCESS;
  9976. }
  9977. bb_perror_msg("kill (SIGCONT)");
  9978. }
  9979. if (argv[0][0] == 'f') {
  9980. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  9981. return checkjobs_and_fg_shell(pi);
  9982. }
  9983. return EXIT_SUCCESS;
  9984. }
  9985. #endif
  9986. #if ENABLE_HUSH_KILL
  9987. static int FAST_FUNC builtin_kill(char **argv)
  9988. {
  9989. int ret = 0;
  9990. # if ENABLE_HUSH_JOB
  9991. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  9992. int i = 1;
  9993. do {
  9994. struct pipe *pi;
  9995. char *dst;
  9996. int j, n;
  9997. if (argv[i][0] != '%')
  9998. continue;
  9999. /*
  10000. * "kill %N" - job kill
  10001. * Converting to pgrp / pid kill
  10002. */
  10003. pi = parse_jobspec(argv[i]);
  10004. if (!pi) {
  10005. /* Eat bad jobspec */
  10006. j = i;
  10007. do {
  10008. j++;
  10009. argv[j - 1] = argv[j];
  10010. } while (argv[j]);
  10011. ret = 1;
  10012. i--;
  10013. continue;
  10014. }
  10015. /*
  10016. * In jobs started under job control, we signal
  10017. * entire process group by kill -PGRP_ID.
  10018. * This happens, f.e., in interactive shell.
  10019. *
  10020. * Otherwise, we signal each child via
  10021. * kill PID1 PID2 PID3.
  10022. * Testcases:
  10023. * sh -c 'sleep 1|sleep 1 & kill %1'
  10024. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10025. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10026. */
  10027. n = G_interactive_fd ? 1 : pi->num_cmds;
  10028. dst = alloca(n * sizeof(int)*4);
  10029. argv[i] = dst;
  10030. if (G_interactive_fd)
  10031. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10032. else for (j = 0; j < n; j++) {
  10033. struct command *cmd = &pi->cmds[j];
  10034. /* Skip exited members of the job */
  10035. if (cmd->pid == 0)
  10036. continue;
  10037. /*
  10038. * kill_main has matching code to expect
  10039. * leading space. Needed to not confuse
  10040. * negative pids with "kill -SIGNAL_NO" syntax
  10041. */
  10042. dst += sprintf(dst, " %u", (int)cmd->pid);
  10043. }
  10044. *dst = '\0';
  10045. } while (argv[++i]);
  10046. }
  10047. # endif
  10048. if (argv[1] || ret == 0) {
  10049. ret = run_applet_main(argv, kill_main);
  10050. }
  10051. /* else: ret = 1, "kill %bad_jobspec" case */
  10052. return ret;
  10053. }
  10054. #endif
  10055. #if ENABLE_HUSH_WAIT
  10056. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10057. #if !ENABLE_HUSH_JOB
  10058. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10059. #endif
  10060. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10061. {
  10062. int ret = 0;
  10063. for (;;) {
  10064. int sig;
  10065. sigset_t oldset;
  10066. if (!sigisemptyset(&G.pending_set))
  10067. goto check_sig;
  10068. /* waitpid is not interruptible by SA_RESTARTed
  10069. * signals which we use. Thus, this ugly dance:
  10070. */
  10071. /* Make sure possible SIGCHLD is stored in kernel's
  10072. * pending signal mask before we call waitpid.
  10073. * Or else we may race with SIGCHLD, lose it,
  10074. * and get stuck in sigsuspend...
  10075. */
  10076. sigfillset(&oldset); /* block all signals, remember old set */
  10077. sigprocmask(SIG_SETMASK, &oldset, &oldset);
  10078. if (!sigisemptyset(&G.pending_set)) {
  10079. /* Crap! we raced with some signal! */
  10080. goto restore;
  10081. }
  10082. /*errno = 0; - checkjobs does this */
  10083. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10084. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10085. debug_printf_exec("checkjobs:%d\n", ret);
  10086. #if ENABLE_HUSH_JOB
  10087. if (waitfor_pipe) {
  10088. int rcode = job_exited_or_stopped(waitfor_pipe);
  10089. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10090. if (rcode >= 0) {
  10091. ret = rcode;
  10092. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10093. break;
  10094. }
  10095. }
  10096. #endif
  10097. /* if ECHILD, there are no children (ret is -1 or 0) */
  10098. /* if ret == 0, no children changed state */
  10099. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10100. if (errno == ECHILD || ret) {
  10101. ret--;
  10102. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10103. ret = 0;
  10104. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10105. break;
  10106. }
  10107. /* Wait for SIGCHLD or any other signal */
  10108. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10109. /* Note: sigsuspend invokes signal handler */
  10110. sigsuspend(&oldset);
  10111. restore:
  10112. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10113. check_sig:
  10114. /* So, did we get a signal? */
  10115. sig = check_and_run_traps();
  10116. if (sig /*&& sig != SIGCHLD - always true */) {
  10117. /* Do this for any (non-ignored) signal, not only for ^C */
  10118. ret = 128 + sig;
  10119. break;
  10120. }
  10121. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10122. }
  10123. return ret;
  10124. }
  10125. static int FAST_FUNC builtin_wait(char **argv)
  10126. {
  10127. int ret;
  10128. int status;
  10129. argv = skip_dash_dash(argv);
  10130. if (argv[0] == NULL) {
  10131. /* Don't care about wait results */
  10132. /* Note 1: must wait until there are no more children */
  10133. /* Note 2: must be interruptible */
  10134. /* Examples:
  10135. * $ sleep 3 & sleep 6 & wait
  10136. * [1] 30934 sleep 3
  10137. * [2] 30935 sleep 6
  10138. * [1] Done sleep 3
  10139. * [2] Done sleep 6
  10140. * $ sleep 3 & sleep 6 & wait
  10141. * [1] 30936 sleep 3
  10142. * [2] 30937 sleep 6
  10143. * [1] Done sleep 3
  10144. * ^C <-- after ~4 sec from keyboard
  10145. * $
  10146. */
  10147. return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
  10148. }
  10149. do {
  10150. pid_t pid = bb_strtou(*argv, NULL, 10);
  10151. if (errno || pid <= 0) {
  10152. #if ENABLE_HUSH_JOB
  10153. if (argv[0][0] == '%') {
  10154. struct pipe *wait_pipe;
  10155. ret = 127; /* bash compat for bad jobspecs */
  10156. wait_pipe = parse_jobspec(*argv);
  10157. if (wait_pipe) {
  10158. ret = job_exited_or_stopped(wait_pipe);
  10159. if (ret < 0) {
  10160. ret = wait_for_child_or_signal(wait_pipe, 0);
  10161. } else {
  10162. /* waiting on "last dead job" removes it */
  10163. clean_up_last_dead_job();
  10164. }
  10165. }
  10166. /* else: parse_jobspec() already emitted error msg */
  10167. continue;
  10168. }
  10169. #endif
  10170. /* mimic bash message */
  10171. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10172. ret = EXIT_FAILURE;
  10173. continue; /* bash checks all argv[] */
  10174. }
  10175. /* Do we have such child? */
  10176. ret = waitpid(pid, &status, WNOHANG);
  10177. if (ret < 0) {
  10178. /* No */
  10179. ret = 127;
  10180. if (errno == ECHILD) {
  10181. if (pid == G.last_bg_pid) {
  10182. /* "wait $!" but last bg task has already exited. Try:
  10183. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10184. * In bash it prints exitcode 0, then 3.
  10185. * In dash, it is 127.
  10186. */
  10187. ret = G.last_bg_pid_exitcode;
  10188. } else {
  10189. /* Example: "wait 1". mimic bash message */
  10190. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10191. }
  10192. } else {
  10193. /* ??? */
  10194. bb_perror_msg("wait %s", *argv);
  10195. }
  10196. continue; /* bash checks all argv[] */
  10197. }
  10198. if (ret == 0) {
  10199. /* Yes, and it still runs */
  10200. ret = wait_for_child_or_signal(NULL, pid);
  10201. } else {
  10202. /* Yes, and it just exited */
  10203. process_wait_result(NULL, pid, status);
  10204. ret = WEXITSTATUS(status);
  10205. if (WIFSIGNALED(status))
  10206. ret = 128 + WTERMSIG(status);
  10207. }
  10208. } while (*++argv);
  10209. return ret;
  10210. }
  10211. #endif
  10212. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10213. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10214. {
  10215. if (argv[1]) {
  10216. def = bb_strtou(argv[1], NULL, 10);
  10217. if (errno || def < def_min || argv[2]) {
  10218. bb_error_msg("%s: bad arguments", argv[0]);
  10219. def = UINT_MAX;
  10220. }
  10221. }
  10222. return def;
  10223. }
  10224. #endif
  10225. #if ENABLE_HUSH_LOOPS
  10226. static int FAST_FUNC builtin_break(char **argv)
  10227. {
  10228. unsigned depth;
  10229. if (G.depth_of_loop == 0) {
  10230. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10231. /* if we came from builtin_continue(), need to undo "= 1" */
  10232. G.flag_break_continue = 0;
  10233. return EXIT_SUCCESS; /* bash compat */
  10234. }
  10235. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10236. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10237. if (depth == UINT_MAX)
  10238. G.flag_break_continue = BC_BREAK;
  10239. if (G.depth_of_loop < depth)
  10240. G.depth_break_continue = G.depth_of_loop;
  10241. return EXIT_SUCCESS;
  10242. }
  10243. static int FAST_FUNC builtin_continue(char **argv)
  10244. {
  10245. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10246. return builtin_break(argv);
  10247. }
  10248. #endif
  10249. #if ENABLE_HUSH_FUNCTIONS
  10250. static int FAST_FUNC builtin_return(char **argv)
  10251. {
  10252. int rc;
  10253. if (G_flag_return_in_progress != -1) {
  10254. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10255. return EXIT_FAILURE; /* bash compat */
  10256. }
  10257. G_flag_return_in_progress = 1;
  10258. /* bash:
  10259. * out of range: wraps around at 256, does not error out
  10260. * non-numeric param:
  10261. * f() { false; return qwe; }; f; echo $?
  10262. * bash: return: qwe: numeric argument required <== we do this
  10263. * 255 <== we also do this
  10264. */
  10265. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10266. return rc;
  10267. }
  10268. #endif
  10269. #if ENABLE_HUSH_TIMES
  10270. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10271. {
  10272. static const uint8_t times_tbl[] ALIGN1 = {
  10273. ' ', offsetof(struct tms, tms_utime),
  10274. '\n', offsetof(struct tms, tms_stime),
  10275. ' ', offsetof(struct tms, tms_cutime),
  10276. '\n', offsetof(struct tms, tms_cstime),
  10277. 0
  10278. };
  10279. const uint8_t *p;
  10280. unsigned clk_tck;
  10281. struct tms buf;
  10282. clk_tck = bb_clk_tck();
  10283. times(&buf);
  10284. p = times_tbl;
  10285. do {
  10286. unsigned sec, frac;
  10287. unsigned long t;
  10288. t = *(clock_t *)(((char *) &buf) + p[1]);
  10289. sec = t / clk_tck;
  10290. frac = t % clk_tck;
  10291. printf("%um%u.%03us%c",
  10292. sec / 60, sec % 60,
  10293. (frac * 1000) / clk_tck,
  10294. p[0]);
  10295. p += 2;
  10296. } while (*p);
  10297. return EXIT_SUCCESS;
  10298. }
  10299. #endif
  10300. #if ENABLE_HUSH_MEMLEAK
  10301. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10302. {
  10303. void *p;
  10304. unsigned long l;
  10305. # ifdef M_TRIM_THRESHOLD
  10306. /* Optional. Reduces probability of false positives */
  10307. malloc_trim(0);
  10308. # endif
  10309. /* Crude attempt to find where "free memory" starts,
  10310. * sans fragmentation. */
  10311. p = malloc(240);
  10312. l = (unsigned long)p;
  10313. free(p);
  10314. p = malloc(3400);
  10315. if (l < (unsigned long)p) l = (unsigned long)p;
  10316. free(p);
  10317. # if 0 /* debug */
  10318. {
  10319. struct mallinfo mi = mallinfo();
  10320. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10321. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10322. }
  10323. # endif
  10324. if (!G.memleak_value)
  10325. G.memleak_value = l;
  10326. l -= G.memleak_value;
  10327. if ((long)l < 0)
  10328. l = 0;
  10329. l /= 1024;
  10330. if (l > 127)
  10331. l = 127;
  10332. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10333. return l;
  10334. }
  10335. #endif