hush.c 337 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235
  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. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (68 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_BASH_SOURCE_CURDIR
  131. //config: bool "'source' and '.' builtins search current directory after $PATH"
  132. //config: default n # do not encourage non-standard behavior
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config: help
  135. //config: This is not compliant with standards. Avoid if possible.
  136. //config:
  137. //config:config HUSH_LINENO_VAR
  138. //config: bool "$LINENO variable (bashism)"
  139. //config: default y
  140. //config: depends on SHELL_HUSH
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !ENABLE_SHELL_ASH
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  383. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  384. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  385. /* Build knobs */
  386. #define LEAK_HUNTING 0
  387. #define BUILD_AS_NOMMU 0
  388. /* Enable/disable sanity checks. Ok to enable in production,
  389. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  390. * Keeping 1 for now even in released versions.
  391. */
  392. #define HUSH_DEBUG 1
  393. /* Slightly bigger (+200 bytes), but faster hush.
  394. * So far it only enables a trick with counting SIGCHLDs and forks,
  395. * which allows us to do fewer waitpid's.
  396. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  397. * and therefore waitpid will return the same result as last time)
  398. */
  399. #define ENABLE_HUSH_FAST 0
  400. /* TODO: implement simplified code for users which do not need ${var%...} ops
  401. * So far ${var%...} ops are always enabled:
  402. */
  403. #define ENABLE_HUSH_DOLLAR_OPS 1
  404. #if BUILD_AS_NOMMU
  405. # undef BB_MMU
  406. # undef USE_FOR_NOMMU
  407. # undef USE_FOR_MMU
  408. # define BB_MMU 0
  409. # define USE_FOR_NOMMU(...) __VA_ARGS__
  410. # define USE_FOR_MMU(...)
  411. #endif
  412. #include "NUM_APPLETS.h"
  413. #if NUM_APPLETS == 1
  414. /* STANDALONE does not make sense, and won't compile */
  415. # undef CONFIG_FEATURE_SH_STANDALONE
  416. # undef ENABLE_FEATURE_SH_STANDALONE
  417. # undef IF_FEATURE_SH_STANDALONE
  418. # undef IF_NOT_FEATURE_SH_STANDALONE
  419. # define ENABLE_FEATURE_SH_STANDALONE 0
  420. # define IF_FEATURE_SH_STANDALONE(...)
  421. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  422. #endif
  423. #if !ENABLE_HUSH_INTERACTIVE
  424. # undef ENABLE_FEATURE_EDITING
  425. # define ENABLE_FEATURE_EDITING 0
  426. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  427. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  428. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  429. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  430. #endif
  431. /* Do we support ANY keywords? */
  432. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  433. # define HAS_KEYWORDS 1
  434. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  435. # define IF_HAS_NO_KEYWORDS(...)
  436. #else
  437. # define HAS_KEYWORDS 0
  438. # define IF_HAS_KEYWORDS(...)
  439. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  440. #endif
  441. /* If you comment out one of these below, it will be #defined later
  442. * to perform debug printfs to stderr: */
  443. #define debug_printf(...) do {} while (0)
  444. /* Finer-grained debug switches */
  445. #define debug_printf_parse(...) do {} while (0)
  446. #define debug_printf_heredoc(...) do {} while (0)
  447. #define debug_print_tree(a, b) do {} while (0)
  448. #define debug_printf_exec(...) do {} while (0)
  449. #define debug_printf_env(...) do {} while (0)
  450. #define debug_printf_jobs(...) do {} while (0)
  451. #define debug_printf_expand(...) do {} while (0)
  452. #define debug_printf_varexp(...) do {} while (0)
  453. #define debug_printf_glob(...) do {} while (0)
  454. #define debug_printf_redir(...) do {} while (0)
  455. #define debug_printf_list(...) do {} while (0)
  456. #define debug_printf_subst(...) do {} while (0)
  457. #define debug_printf_prompt(...) do {} while (0)
  458. #define debug_printf_clean(...) do {} while (0)
  459. #define ERR_PTR ((void*)(long)1)
  460. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  461. #define _SPECIAL_VARS_STR "_*@$!?#-"
  462. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  463. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  464. #if BASH_PATTERN_SUBST
  465. /* Support / and // replace ops */
  466. /* Note that // is stored as \ in "encoded" string representation */
  467. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  468. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  469. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  470. #else
  471. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  472. # define VAR_SUBST_OPS "%#:-=+?"
  473. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  474. #endif
  475. #define SPECIAL_VAR_SYMBOL_STR "\3"
  476. #define SPECIAL_VAR_SYMBOL 3
  477. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  478. #define SPECIAL_VAR_QUOTED_SVS 1
  479. struct variable;
  480. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  481. /* This supports saving pointers malloced in vfork child,
  482. * to be freed in the parent.
  483. */
  484. #if !BB_MMU
  485. typedef struct nommu_save_t {
  486. struct variable *old_vars;
  487. char **argv;
  488. char **argv_from_re_execing;
  489. } nommu_save_t;
  490. #endif
  491. enum {
  492. RES_NONE = 0,
  493. #if ENABLE_HUSH_IF
  494. RES_IF ,
  495. RES_THEN ,
  496. RES_ELIF ,
  497. RES_ELSE ,
  498. RES_FI ,
  499. #endif
  500. #if ENABLE_HUSH_LOOPS
  501. RES_FOR ,
  502. RES_WHILE ,
  503. RES_UNTIL ,
  504. RES_DO ,
  505. RES_DONE ,
  506. #endif
  507. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  508. RES_IN ,
  509. #endif
  510. #if ENABLE_HUSH_CASE
  511. RES_CASE ,
  512. /* three pseudo-keywords support contrived "case" syntax: */
  513. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  514. RES_MATCH , /* "word)" */
  515. RES_CASE_BODY, /* "this command is inside CASE" */
  516. RES_ESAC ,
  517. #endif
  518. RES_XXXX ,
  519. RES_SNTX
  520. };
  521. typedef struct o_string {
  522. char *data;
  523. int length; /* position where data is appended */
  524. int maxlen;
  525. int o_expflags;
  526. /* At least some part of the string was inside '' or "",
  527. * possibly empty one: word"", wo''rd etc. */
  528. smallint has_quoted_part;
  529. smallint has_empty_slot;
  530. smallint ended_in_ifs;
  531. } o_string;
  532. enum {
  533. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  534. EXP_FLAG_GLOB = 0x2,
  535. /* Protect newly added chars against globbing
  536. * by prepending \ to *, ?, [, \ */
  537. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  538. };
  539. /* Used for initialization: o_string foo = NULL_O_STRING; */
  540. #define NULL_O_STRING { NULL }
  541. #ifndef debug_printf_parse
  542. static const char *const assignment_flag[] ALIGN_PTR = {
  543. "MAYBE_ASSIGNMENT",
  544. "DEFINITELY_ASSIGNMENT",
  545. "NOT_ASSIGNMENT",
  546. "WORD_IS_KEYWORD",
  547. };
  548. #endif
  549. /* We almost can use standard FILE api, but we need an ability to move
  550. * its fd when redirects coincide with it. No api exists for that
  551. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  552. * HFILE is our internal alternative. Only supports reading.
  553. * Since we now can, we incorporate linked list of all opened HFILEs
  554. * into the struct (used to be a separate mini-list).
  555. */
  556. typedef struct HFILE {
  557. char *cur;
  558. char *end;
  559. struct HFILE *next_hfile;
  560. int fd;
  561. char buf[1024];
  562. } HFILE;
  563. typedef struct in_str {
  564. const char *p;
  565. int peek_buf[2];
  566. int last_char;
  567. HFILE *file;
  568. } in_str;
  569. /* The descrip member of this structure is only used to make
  570. * debugging output pretty */
  571. static const struct {
  572. int32_t mode;
  573. signed char default_fd;
  574. char descrip[3];
  575. } redir_table[] ALIGN4 = {
  576. { O_RDONLY, 0, "<" },
  577. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  578. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  579. { O_CREAT|O_RDWR, 1, "<>" },
  580. { O_RDONLY, 0, "<<" },
  581. /* Should not be needed. Bogus default_fd helps in debugging */
  582. /* { O_RDONLY, 77, "<<" }, */
  583. };
  584. struct redir_struct {
  585. struct redir_struct *next;
  586. char *rd_filename; /* filename */
  587. int rd_fd; /* fd to redirect */
  588. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  589. int rd_dup;
  590. smallint rd_type; /* (enum redir_type) */
  591. /* note: for heredocs, rd_filename contains heredoc delimiter,
  592. * and subsequently heredoc itself; and rd_dup is a bitmask:
  593. * bit 0: do we need to trim leading tabs?
  594. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  595. */
  596. };
  597. typedef enum redir_type {
  598. REDIRECT_INPUT = 0,
  599. REDIRECT_OVERWRITE = 1,
  600. REDIRECT_APPEND = 2,
  601. REDIRECT_IO = 3,
  602. REDIRECT_HEREDOC = 4,
  603. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  604. REDIRFD_CLOSE = -3,
  605. REDIRFD_SYNTAX_ERR = -2,
  606. REDIRFD_TO_FILE = -1,
  607. /* otherwise, rd_fd is redirected to rd_dup */
  608. HEREDOC_SKIPTABS = 1,
  609. HEREDOC_QUOTED = 2,
  610. } redir_type;
  611. struct command {
  612. pid_t pid; /* 0 if exited */
  613. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  614. #if ENABLE_HUSH_LINENO_VAR
  615. unsigned lineno;
  616. #endif
  617. smallint cmd_type; /* CMD_xxx */
  618. #define CMD_NORMAL 0
  619. #define CMD_SUBSHELL 1
  620. #if BASH_TEST2
  621. /* used for "[[ EXPR ]]" */
  622. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  623. #endif
  624. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  625. /* used to prevent word splitting and globbing in "export v=t*" */
  626. # define CMD_SINGLEWORD_NOGLOB 3
  627. #endif
  628. #if ENABLE_HUSH_FUNCTIONS
  629. # define CMD_FUNCDEF 4
  630. #endif
  631. smalluint cmd_exitcode;
  632. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  633. struct pipe *group;
  634. #if !BB_MMU
  635. char *group_as_string;
  636. #endif
  637. #if ENABLE_HUSH_FUNCTIONS
  638. struct function *child_func;
  639. /* This field is used to prevent a bug here:
  640. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  641. * When we execute "f1() {a;}" cmd, we create new function and clear
  642. * cmd->group, cmd->group_as_string, cmd->argv[0].
  643. * When we execute "f1() {b;}", we notice that f1 exists,
  644. * and that its "parent cmd" struct is still "alive",
  645. * we put those fields back into cmd->xxx
  646. * (struct function has ->parent_cmd ptr to facilitate that).
  647. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  648. * Without this trick, loop would execute a;b;b;b;...
  649. * instead of correct sequence a;b;a;b;...
  650. * When command is freed, it severs the link
  651. * (sets ->child_func->parent_cmd to NULL).
  652. */
  653. #endif
  654. char **argv; /* command name and arguments */
  655. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  656. * and on execution these are substituted with their values.
  657. * Substitution can make _several_ words out of one argv[n]!
  658. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  659. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  660. */
  661. struct redir_struct *redirects; /* I/O redirections */
  662. };
  663. /* Is there anything in this command at all? */
  664. #define IS_NULL_CMD(cmd) \
  665. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  666. struct pipe {
  667. struct pipe *next;
  668. int num_cmds; /* total number of commands in pipe */
  669. int alive_cmds; /* number of commands running (not exited) */
  670. int stopped_cmds; /* number of commands alive, but stopped */
  671. #if ENABLE_HUSH_JOB
  672. unsigned jobid; /* job number */
  673. pid_t pgrp; /* process group ID for the job */
  674. char *cmdtext; /* name of job */
  675. #endif
  676. struct command *cmds; /* array of commands in pipe */
  677. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  678. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  679. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  680. };
  681. typedef enum pipe_style {
  682. PIPE_SEQ = 0,
  683. PIPE_AND = 1,
  684. PIPE_OR = 2,
  685. PIPE_BG = 3,
  686. } pipe_style;
  687. /* Is there anything in this pipe at all? */
  688. #define IS_NULL_PIPE(pi) \
  689. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  690. /* This holds pointers to the various results of parsing */
  691. struct parse_context {
  692. /* linked list of pipes */
  693. struct pipe *list_head;
  694. /* last pipe (being constructed right now) */
  695. struct pipe *pipe;
  696. /* last command in pipe (being constructed right now) */
  697. struct command *command;
  698. /* last redirect in command->redirects list */
  699. struct redir_struct *pending_redirect;
  700. o_string word;
  701. #if !BB_MMU
  702. o_string as_string;
  703. #endif
  704. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  705. #if HAS_KEYWORDS
  706. smallint ctx_res_w;
  707. smallint ctx_inverted; /* "! cmd | cmd" */
  708. #if ENABLE_HUSH_CASE
  709. smallint ctx_dsemicolon; /* ";;" seen */
  710. #endif
  711. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  712. int old_flag;
  713. /* group we are enclosed in:
  714. * example: "if pipe1; pipe2; then pipe3; fi"
  715. * when we see "if" or "then", we malloc and copy current context,
  716. * and make ->stack point to it. then we parse pipeN.
  717. * when closing "then" / fi" / whatever is found,
  718. * we move list_head into ->stack->command->group,
  719. * copy ->stack into current context, and delete ->stack.
  720. * (parsing of { list } and ( list ) doesn't use this method)
  721. */
  722. struct parse_context *stack;
  723. #endif
  724. };
  725. enum {
  726. MAYBE_ASSIGNMENT = 0,
  727. DEFINITELY_ASSIGNMENT = 1,
  728. NOT_ASSIGNMENT = 2,
  729. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  730. WORD_IS_KEYWORD = 3,
  731. };
  732. /* On program start, environ points to initial environment.
  733. * putenv adds new pointers into it, unsetenv removes them.
  734. * Neither of these (de)allocates the strings.
  735. * setenv allocates new strings in malloc space and does putenv,
  736. * and thus setenv is unusable (leaky) for shell's purposes */
  737. #define setenv(...) setenv_is_leaky_dont_use()
  738. struct variable {
  739. struct variable *next;
  740. char *varstr; /* points to "name=" portion */
  741. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  742. uint16_t var_nest_level;
  743. smallint flg_export; /* putenv should be done on this var */
  744. smallint flg_read_only;
  745. };
  746. enum {
  747. BC_BREAK = 1,
  748. BC_CONTINUE = 2,
  749. };
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function {
  752. struct function *next;
  753. char *name;
  754. struct command *parent_cmd;
  755. struct pipe *body;
  756. # if !BB_MMU
  757. char *body_as_string;
  758. # endif
  759. };
  760. #endif
  761. /* set -/+o OPT support. (TODO: make it optional)
  762. * bash supports the following opts:
  763. * allexport off
  764. * braceexpand on
  765. * emacs on
  766. * errexit off
  767. * errtrace off
  768. * functrace off
  769. * hashall on
  770. * histexpand off
  771. * history on
  772. * ignoreeof off
  773. * interactive-comments on
  774. * keyword off
  775. * monitor on
  776. * noclobber off
  777. * noexec off
  778. * noglob off
  779. * nolog off
  780. * notify off
  781. * nounset off
  782. * onecmd off
  783. * physical off
  784. * pipefail off
  785. * posix off
  786. * privileged off
  787. * verbose off
  788. * vi off
  789. * xtrace off
  790. */
  791. static const char o_opt_strings[] ALIGN1 =
  792. "pipefail\0"
  793. "noexec\0"
  794. "errexit\0"
  795. #if ENABLE_HUSH_MODE_X
  796. "xtrace\0"
  797. #endif
  798. ;
  799. enum {
  800. OPT_O_PIPEFAIL,
  801. OPT_O_NOEXEC,
  802. OPT_O_ERREXIT,
  803. #if ENABLE_HUSH_MODE_X
  804. OPT_O_XTRACE,
  805. #endif
  806. NUM_OPT_O
  807. };
  808. /* "Globals" within this file */
  809. /* Sorted roughly by size (smaller offsets == smaller code) */
  810. struct globals {
  811. /* interactive_fd != 0 means we are an interactive shell.
  812. * If we are, then saved_tty_pgrp can also be != 0, meaning
  813. * that controlling tty is available. With saved_tty_pgrp == 0,
  814. * job control still works, but terminal signals
  815. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  816. * process groups can only be created with "cmd &".
  817. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  818. * to give tty to the foreground process group,
  819. * and will take it back when the group is stopped (^Z)
  820. * or killed (^C).
  821. */
  822. #if ENABLE_HUSH_INTERACTIVE
  823. /* 'interactive_fd' is a fd# open to ctty, if we have one
  824. * _AND_ if we decided to act interactively */
  825. int interactive_fd;
  826. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  827. # define G_interactive_fd (G.interactive_fd)
  828. #else
  829. # define G_interactive_fd 0
  830. #endif
  831. #if ENABLE_FEATURE_EDITING
  832. line_input_t *line_input_state;
  833. #endif
  834. pid_t root_pid;
  835. pid_t root_ppid;
  836. pid_t last_bg_pid;
  837. #if ENABLE_HUSH_RANDOM_SUPPORT
  838. random_t random_gen;
  839. #endif
  840. #if ENABLE_HUSH_JOB
  841. int run_list_level;
  842. unsigned last_jobid;
  843. pid_t saved_tty_pgrp;
  844. struct pipe *job_list;
  845. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  846. #else
  847. # define G_saved_tty_pgrp 0
  848. #endif
  849. /* How deeply are we in context where "set -e" is ignored */
  850. int errexit_depth;
  851. /* "set -e" rules (do we follow them correctly?):
  852. * Exit if pipe, list, or compound command exits with a non-zero status.
  853. * Shell does not exit if failed command is part of condition in
  854. * if/while, part of && or || list except the last command, any command
  855. * in a pipe but the last, or if the command's return value is being
  856. * inverted with !. If a compound command other than a subshell returns a
  857. * non-zero status because a command failed while -e was being ignored, the
  858. * shell does not exit. A trap on ERR, if set, is executed before the shell
  859. * exits [ERR is a bashism].
  860. *
  861. * If a compound command or function executes in a context where -e is
  862. * ignored, none of the commands executed within are affected by the -e
  863. * setting. If a compound command or function sets -e while executing in a
  864. * context where -e is ignored, that setting does not have any effect until
  865. * the compound command or the command containing the function call completes.
  866. */
  867. char o_opt[NUM_OPT_O];
  868. #if ENABLE_HUSH_MODE_X
  869. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  870. #else
  871. # define G_x_mode 0
  872. #endif
  873. char opt_s;
  874. char opt_c;
  875. #if ENABLE_HUSH_INTERACTIVE
  876. smallint promptmode; /* 0: PS1, 1: PS2 */
  877. #endif
  878. /* set by signal handler if SIGINT is received _and_ its trap is not set */
  879. smallint flag_SIGINT;
  880. #if ENABLE_HUSH_LOOPS
  881. smallint flag_break_continue;
  882. #endif
  883. #if ENABLE_HUSH_FUNCTIONS
  884. /* 0: outside of a function (or sourced file)
  885. * -1: inside of a function, ok to use return builtin
  886. * 1: return is invoked, skip all till end of func
  887. */
  888. smallint flag_return_in_progress;
  889. # define G_flag_return_in_progress (G.flag_return_in_progress)
  890. #else
  891. # define G_flag_return_in_progress 0
  892. #endif
  893. smallint exiting; /* used to prevent EXIT trap recursion */
  894. /* These support $? */
  895. smalluint last_exitcode;
  896. smalluint expand_exitcode;
  897. smalluint last_bg_pid_exitcode;
  898. #if ENABLE_HUSH_SET
  899. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  900. smalluint global_args_malloced;
  901. # define G_global_args_malloced (G.global_args_malloced)
  902. #else
  903. # define G_global_args_malloced 0
  904. #endif
  905. #if ENABLE_HUSH_BASH_COMPAT
  906. int dead_job_exitcode; /* for "wait -n" */
  907. #endif
  908. /* how many non-NULL argv's we have. NB: $# + 1 */
  909. int global_argc;
  910. char **global_argv;
  911. #if !BB_MMU
  912. char *argv0_for_re_execing;
  913. #endif
  914. #if ENABLE_HUSH_LOOPS
  915. unsigned depth_break_continue;
  916. unsigned depth_of_loop;
  917. #endif
  918. #if ENABLE_HUSH_GETOPTS
  919. unsigned getopt_count;
  920. #endif
  921. const char *ifs;
  922. char *ifs_whitespace; /* = G.ifs or malloced */
  923. const char *cwd;
  924. struct variable *top_var;
  925. char **expanded_assignments;
  926. struct variable **shadowed_vars_pp;
  927. unsigned var_nest_level;
  928. #if ENABLE_HUSH_FUNCTIONS
  929. # if ENABLE_HUSH_LOCAL
  930. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  931. # endif
  932. struct function *top_func;
  933. #endif
  934. /* Signal and trap handling */
  935. #if ENABLE_HUSH_FAST
  936. unsigned count_SIGCHLD;
  937. unsigned handled_SIGCHLD;
  938. smallint we_have_children;
  939. #endif
  940. #if ENABLE_HUSH_LINENO_VAR
  941. unsigned parse_lineno;
  942. unsigned execute_lineno;
  943. #endif
  944. HFILE *HFILE_list;
  945. HFILE *HFILE_stdin;
  946. /* Which signals have non-DFL handler (even with no traps set)?
  947. * Set at the start to:
  948. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  949. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  950. * The rest is cleared right before execv syscalls.
  951. * Other than these two times, never modified.
  952. */
  953. unsigned special_sig_mask;
  954. #if ENABLE_HUSH_JOB
  955. unsigned fatal_sig_mask;
  956. # define G_fatal_sig_mask (G.fatal_sig_mask)
  957. #else
  958. # define G_fatal_sig_mask 0
  959. #endif
  960. #if ENABLE_HUSH_TRAP
  961. int pre_trap_exitcode;
  962. # if ENABLE_HUSH_FUNCTIONS
  963. int return_exitcode;
  964. # endif
  965. char **traps; /* char *traps[NSIG] */
  966. # define G_traps G.traps
  967. #else
  968. # define G_traps ((char**)NULL)
  969. #endif
  970. sigset_t pending_set;
  971. #if ENABLE_HUSH_MEMLEAK
  972. unsigned long memleak_value;
  973. #endif
  974. #if ENABLE_HUSH_MODE_X
  975. unsigned x_mode_depth;
  976. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  977. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  978. * for all subsequent output.
  979. */
  980. int x_mode_fd;
  981. o_string x_mode_buf;
  982. #endif
  983. #if HUSH_DEBUG >= 2
  984. int debug_indent;
  985. #endif
  986. struct sigaction sa;
  987. char optstring_buf[sizeof("eixcs")];
  988. #if BASH_EPOCH_VARS
  989. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  990. #endif
  991. #if ENABLE_FEATURE_EDITING
  992. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  993. #endif
  994. };
  995. #define G (*ptr_to_globals)
  996. /* Not #defining name to G.name - this quickly gets unwieldy
  997. * (too many defines). Also, I actually prefer to see when a variable
  998. * is global, thus "G." prefix is a useful hint */
  999. #define INIT_G() do { \
  1000. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1001. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1002. sigfillset(&G.sa.sa_mask); \
  1003. G.sa.sa_flags = SA_RESTART; \
  1004. } while (0)
  1005. /* Function prototypes for builtins */
  1006. static int builtin_cd(char **argv) FAST_FUNC;
  1007. #if ENABLE_HUSH_ECHO
  1008. static int builtin_echo(char **argv) FAST_FUNC;
  1009. #endif
  1010. static int builtin_eval(char **argv) FAST_FUNC;
  1011. static int builtin_exec(char **argv) FAST_FUNC;
  1012. static int builtin_exit(char **argv) FAST_FUNC;
  1013. #if ENABLE_HUSH_EXPORT
  1014. static int builtin_export(char **argv) FAST_FUNC;
  1015. #endif
  1016. #if ENABLE_HUSH_READONLY
  1017. static int builtin_readonly(char **argv) FAST_FUNC;
  1018. #endif
  1019. #if ENABLE_HUSH_JOB
  1020. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1021. static int builtin_jobs(char **argv) FAST_FUNC;
  1022. #endif
  1023. #if ENABLE_HUSH_GETOPTS
  1024. static int builtin_getopts(char **argv) FAST_FUNC;
  1025. #endif
  1026. #if ENABLE_HUSH_HELP
  1027. static int builtin_help(char **argv) FAST_FUNC;
  1028. #endif
  1029. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1030. static int builtin_history(char **argv) FAST_FUNC;
  1031. #endif
  1032. #if ENABLE_HUSH_LOCAL
  1033. static int builtin_local(char **argv) FAST_FUNC;
  1034. #endif
  1035. #if ENABLE_HUSH_MEMLEAK
  1036. static int builtin_memleak(char **argv) FAST_FUNC;
  1037. #endif
  1038. #if ENABLE_HUSH_PRINTF
  1039. static int builtin_printf(char **argv) FAST_FUNC;
  1040. #endif
  1041. static int builtin_pwd(char **argv) FAST_FUNC;
  1042. #if ENABLE_HUSH_READ
  1043. static int builtin_read(char **argv) FAST_FUNC;
  1044. #endif
  1045. #if ENABLE_HUSH_SET
  1046. static int builtin_set(char **argv) FAST_FUNC;
  1047. #endif
  1048. static int builtin_shift(char **argv) FAST_FUNC;
  1049. static int builtin_source(char **argv) FAST_FUNC;
  1050. #if ENABLE_HUSH_TEST || BASH_TEST2
  1051. static int builtin_test(char **argv) FAST_FUNC;
  1052. #endif
  1053. #if ENABLE_HUSH_TRAP
  1054. static int builtin_trap(char **argv) FAST_FUNC;
  1055. #endif
  1056. #if ENABLE_HUSH_TYPE
  1057. static int builtin_type(char **argv) FAST_FUNC;
  1058. #endif
  1059. #if ENABLE_HUSH_TIMES
  1060. static int builtin_times(char **argv) FAST_FUNC;
  1061. #endif
  1062. static int builtin_true(char **argv) FAST_FUNC;
  1063. #if ENABLE_HUSH_UMASK
  1064. static int builtin_umask(char **argv) FAST_FUNC;
  1065. #endif
  1066. #if ENABLE_HUSH_UNSET
  1067. static int builtin_unset(char **argv) FAST_FUNC;
  1068. #endif
  1069. #if ENABLE_HUSH_KILL
  1070. static int builtin_kill(char **argv) FAST_FUNC;
  1071. #endif
  1072. #if ENABLE_HUSH_WAIT
  1073. static int builtin_wait(char **argv) FAST_FUNC;
  1074. #endif
  1075. #if ENABLE_HUSH_LOOPS
  1076. static int builtin_break(char **argv) FAST_FUNC;
  1077. static int builtin_continue(char **argv) FAST_FUNC;
  1078. #endif
  1079. #if ENABLE_HUSH_FUNCTIONS
  1080. static int builtin_return(char **argv) FAST_FUNC;
  1081. #endif
  1082. /* Table of built-in functions. They can be forked or not, depending on
  1083. * context: within pipes, they fork. As simple commands, they do not.
  1084. * When used in non-forking context, they can change global variables
  1085. * in the parent shell process. If forked, of course they cannot.
  1086. * For example, 'unset foo | whatever' will parse and run, but foo will
  1087. * still be set at the end. */
  1088. struct built_in_command {
  1089. const char *b_cmd;
  1090. int (*b_function)(char **argv) FAST_FUNC;
  1091. #if ENABLE_HUSH_HELP
  1092. const char *b_descr;
  1093. # define BLTIN(cmd, func, help) { cmd, func, help }
  1094. #else
  1095. # define BLTIN(cmd, func, help) { cmd, func }
  1096. #endif
  1097. };
  1098. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1099. BLTIN("." , builtin_source , "Run commands in file"),
  1100. BLTIN(":" , builtin_true , NULL),
  1101. #if ENABLE_HUSH_JOB
  1102. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1103. #endif
  1104. #if ENABLE_HUSH_LOOPS
  1105. BLTIN("break" , builtin_break , "Exit loop"),
  1106. #endif
  1107. BLTIN("cd" , builtin_cd , "Change directory"),
  1108. #if ENABLE_HUSH_LOOPS
  1109. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1110. #endif
  1111. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1112. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1113. BLTIN("exit" , builtin_exit , NULL),
  1114. #if ENABLE_HUSH_EXPORT
  1115. BLTIN("export" , builtin_export , "Set environment variables"),
  1116. #endif
  1117. #if ENABLE_HUSH_JOB
  1118. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1119. #endif
  1120. #if ENABLE_HUSH_GETOPTS
  1121. BLTIN("getopts" , builtin_getopts , NULL),
  1122. #endif
  1123. #if ENABLE_HUSH_HELP
  1124. BLTIN("help" , builtin_help , NULL),
  1125. #endif
  1126. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1127. BLTIN("history" , builtin_history , "Show history"),
  1128. #endif
  1129. #if ENABLE_HUSH_JOB
  1130. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1131. #endif
  1132. #if ENABLE_HUSH_KILL
  1133. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1134. #endif
  1135. #if ENABLE_HUSH_LOCAL
  1136. BLTIN("local" , builtin_local , "Set local variables"),
  1137. #endif
  1138. #if ENABLE_HUSH_MEMLEAK
  1139. BLTIN("memleak" , builtin_memleak , NULL),
  1140. #endif
  1141. #if ENABLE_HUSH_READ
  1142. BLTIN("read" , builtin_read , "Input into variable"),
  1143. #endif
  1144. #if ENABLE_HUSH_READONLY
  1145. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1146. #endif
  1147. #if ENABLE_HUSH_FUNCTIONS
  1148. BLTIN("return" , builtin_return , "Return from function"),
  1149. #endif
  1150. #if ENABLE_HUSH_SET
  1151. BLTIN("set" , builtin_set , "Set positional parameters"),
  1152. #endif
  1153. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1154. #if BASH_SOURCE
  1155. BLTIN("source" , builtin_source , NULL),
  1156. #endif
  1157. #if ENABLE_HUSH_TIMES
  1158. BLTIN("times" , builtin_times , NULL),
  1159. #endif
  1160. #if ENABLE_HUSH_TRAP
  1161. BLTIN("trap" , builtin_trap , "Trap signals"),
  1162. #endif
  1163. BLTIN("true" , builtin_true , NULL),
  1164. #if ENABLE_HUSH_TYPE
  1165. BLTIN("type" , builtin_type , "Show command type"),
  1166. #endif
  1167. #if ENABLE_HUSH_ULIMIT
  1168. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1169. #endif
  1170. #if ENABLE_HUSH_UMASK
  1171. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1172. #endif
  1173. #if ENABLE_HUSH_UNSET
  1174. BLTIN("unset" , builtin_unset , "Unset variables"),
  1175. #endif
  1176. #if ENABLE_HUSH_WAIT
  1177. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1178. #endif
  1179. };
  1180. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1181. * (it's cheaper to run an external program in this case):
  1182. */
  1183. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1184. #if ENABLE_HUSH_TEST
  1185. BLTIN("[" , builtin_test , NULL),
  1186. #endif
  1187. #if BASH_TEST2
  1188. BLTIN("[[" , builtin_test , NULL),
  1189. #endif
  1190. #if ENABLE_HUSH_ECHO
  1191. BLTIN("echo" , builtin_echo , NULL),
  1192. #endif
  1193. #if ENABLE_HUSH_PRINTF
  1194. BLTIN("printf" , builtin_printf , NULL),
  1195. #endif
  1196. BLTIN("pwd" , builtin_pwd , NULL),
  1197. #if ENABLE_HUSH_TEST
  1198. BLTIN("test" , builtin_test , NULL),
  1199. #endif
  1200. };
  1201. /* Debug printouts.
  1202. */
  1203. #if HUSH_DEBUG >= 2
  1204. /* prevent disasters with G.debug_indent < 0 */
  1205. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1206. # define debug_enter() (G.debug_indent++)
  1207. # define debug_leave() (G.debug_indent--)
  1208. #else
  1209. # define indent() ((void)0)
  1210. # define debug_enter() ((void)0)
  1211. # define debug_leave() ((void)0)
  1212. #endif
  1213. #ifndef debug_printf
  1214. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1215. #endif
  1216. #ifndef debug_printf_parse
  1217. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1218. #endif
  1219. #ifndef debug_printf_heredoc
  1220. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1221. #endif
  1222. #ifndef debug_printf_exec
  1223. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1224. #endif
  1225. #ifndef debug_printf_env
  1226. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1227. #endif
  1228. #ifndef debug_printf_jobs
  1229. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1230. # define DEBUG_JOBS 1
  1231. #else
  1232. # define DEBUG_JOBS 0
  1233. #endif
  1234. #ifndef debug_printf_expand
  1235. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1236. # define DEBUG_EXPAND 1
  1237. #else
  1238. # define DEBUG_EXPAND 0
  1239. #endif
  1240. #ifndef debug_printf_varexp
  1241. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1242. #endif
  1243. #ifndef debug_printf_glob
  1244. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1245. # define DEBUG_GLOB 1
  1246. #else
  1247. # define DEBUG_GLOB 0
  1248. #endif
  1249. #ifndef debug_printf_redir
  1250. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1251. #endif
  1252. #ifndef debug_printf_list
  1253. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1254. #endif
  1255. #ifndef debug_printf_subst
  1256. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1257. #endif
  1258. #ifndef debug_printf_prompt
  1259. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1260. #endif
  1261. #ifndef debug_printf_clean
  1262. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1263. # define DEBUG_CLEAN 1
  1264. #else
  1265. # define DEBUG_CLEAN 0
  1266. #endif
  1267. #if DEBUG_EXPAND
  1268. static void debug_print_strings(const char *prefix, char **vv)
  1269. {
  1270. indent();
  1271. fdprintf(2, "%s:\n", prefix);
  1272. while (*vv)
  1273. fdprintf(2, " '%s'\n", *vv++);
  1274. }
  1275. #else
  1276. # define debug_print_strings(prefix, vv) ((void)0)
  1277. #endif
  1278. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1279. */
  1280. #if LEAK_HUNTING
  1281. static void *xxmalloc(int lineno, size_t size)
  1282. {
  1283. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1284. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1285. return ptr;
  1286. }
  1287. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1288. {
  1289. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1290. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1291. return ptr;
  1292. }
  1293. static char *xxstrdup(int lineno, const char *str)
  1294. {
  1295. char *ptr = xstrdup(str);
  1296. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1297. return ptr;
  1298. }
  1299. static void xxfree(void *ptr)
  1300. {
  1301. fdprintf(2, "free %p\n", ptr);
  1302. free(ptr);
  1303. }
  1304. # define xmalloc(s) xxmalloc(__LINE__, s)
  1305. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1306. # define xstrdup(s) xxstrdup(__LINE__, s)
  1307. # define free(p) xxfree(p)
  1308. #endif
  1309. /* Syntax and runtime errors. They always abort scripts.
  1310. * In interactive use they usually discard unparsed and/or unexecuted commands
  1311. * and return to the prompt.
  1312. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1313. */
  1314. #if HUSH_DEBUG < 2
  1315. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1316. # define syntax_error(lineno, msg) syntax_error(msg)
  1317. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1318. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1319. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1320. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1321. #endif
  1322. static void die_if_script(void)
  1323. {
  1324. if (!G_interactive_fd) {
  1325. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1326. xfunc_error_retval = G.last_exitcode;
  1327. xfunc_die();
  1328. }
  1329. }
  1330. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1331. {
  1332. va_list p;
  1333. #if HUSH_DEBUG >= 2
  1334. bb_error_msg("hush.c:%u", lineno);
  1335. #endif
  1336. va_start(p, fmt);
  1337. bb_verror_msg(fmt, p, NULL);
  1338. va_end(p);
  1339. die_if_script();
  1340. }
  1341. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1342. {
  1343. if (msg)
  1344. bb_error_msg("syntax error: %s", msg);
  1345. else
  1346. bb_simple_error_msg("syntax error");
  1347. die_if_script();
  1348. }
  1349. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1350. {
  1351. bb_error_msg("syntax error at '%s'", msg);
  1352. die_if_script();
  1353. }
  1354. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1355. {
  1356. bb_error_msg("syntax error: unterminated %s", s);
  1357. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1358. // die_if_script();
  1359. }
  1360. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1361. {
  1362. char msg[2] = { ch, '\0' };
  1363. syntax_error_unterm_str(lineno, msg);
  1364. }
  1365. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1366. {
  1367. char msg[2];
  1368. msg[0] = ch;
  1369. msg[1] = '\0';
  1370. #if HUSH_DEBUG >= 2
  1371. bb_error_msg("hush.c:%u", lineno);
  1372. #endif
  1373. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1374. die_if_script();
  1375. }
  1376. #if HUSH_DEBUG < 2
  1377. # undef msg_and_die_if_script
  1378. # undef syntax_error
  1379. # undef syntax_error_at
  1380. # undef syntax_error_unterm_ch
  1381. # undef syntax_error_unterm_str
  1382. # undef syntax_error_unexpected_ch
  1383. #else
  1384. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1385. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1386. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1387. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1388. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1389. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1390. #endif
  1391. /* Utility functions
  1392. */
  1393. /* Replace each \x with x in place, return ptr past NUL. */
  1394. static char *unbackslash(char *src)
  1395. {
  1396. char *dst = src = strchrnul(src, '\\');
  1397. while (1) {
  1398. if (*src == '\\') {
  1399. src++;
  1400. if (*src != '\0') {
  1401. /* \x -> x */
  1402. *dst++ = *src++;
  1403. continue;
  1404. }
  1405. /* else: "\<nul>". Do not delete this backslash.
  1406. * Testcase: eval 'echo ok\'
  1407. */
  1408. *dst++ = '\\';
  1409. /* fallthrough */
  1410. }
  1411. if ((*dst++ = *src++) == '\0')
  1412. break;
  1413. }
  1414. return dst;
  1415. }
  1416. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1417. {
  1418. int i;
  1419. unsigned count1;
  1420. unsigned count2;
  1421. char **v;
  1422. v = strings;
  1423. count1 = 0;
  1424. if (v) {
  1425. while (*v) {
  1426. count1++;
  1427. v++;
  1428. }
  1429. }
  1430. count2 = 0;
  1431. v = add;
  1432. while (*v) {
  1433. count2++;
  1434. v++;
  1435. }
  1436. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1437. v[count1 + count2] = NULL;
  1438. i = count2;
  1439. while (--i >= 0)
  1440. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1441. return v;
  1442. }
  1443. #if LEAK_HUNTING
  1444. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1445. {
  1446. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1447. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1448. return ptr;
  1449. }
  1450. #define add_strings_to_strings(strings, add, need_to_dup) \
  1451. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1452. #endif
  1453. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1454. static char **add_string_to_strings(char **strings, char *add)
  1455. {
  1456. char *v[2];
  1457. v[0] = add;
  1458. v[1] = NULL;
  1459. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1460. }
  1461. #if LEAK_HUNTING
  1462. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1463. {
  1464. char **ptr = add_string_to_strings(strings, add);
  1465. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1466. return ptr;
  1467. }
  1468. #define add_string_to_strings(strings, add) \
  1469. xx_add_string_to_strings(__LINE__, strings, add)
  1470. #endif
  1471. static void free_strings(char **strings)
  1472. {
  1473. char **v;
  1474. if (!strings)
  1475. return;
  1476. v = strings;
  1477. while (*v) {
  1478. free(*v);
  1479. v++;
  1480. }
  1481. free(strings);
  1482. }
  1483. static int dup_CLOEXEC(int fd, int avoid_fd)
  1484. {
  1485. int newfd;
  1486. repeat:
  1487. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1488. if (newfd >= 0) {
  1489. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1490. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1491. } else { /* newfd < 0 */
  1492. if (errno == EBUSY)
  1493. goto repeat;
  1494. if (errno == EINTR)
  1495. goto repeat;
  1496. }
  1497. return newfd;
  1498. }
  1499. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1500. {
  1501. int newfd;
  1502. repeat:
  1503. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1504. if (newfd < 0) {
  1505. if (errno == EBUSY)
  1506. goto repeat;
  1507. if (errno == EINTR)
  1508. goto repeat;
  1509. /* fd was not open? */
  1510. if (errno == EBADF)
  1511. return fd;
  1512. xfunc_die();
  1513. }
  1514. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1515. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1516. close(fd);
  1517. return newfd;
  1518. }
  1519. /* Manipulating HFILEs */
  1520. static HFILE *hfopen(const char *name)
  1521. {
  1522. HFILE *fp;
  1523. int fd;
  1524. fd = STDIN_FILENO;
  1525. if (name) {
  1526. fd = open(name, O_RDONLY | O_CLOEXEC);
  1527. if (fd < 0)
  1528. return NULL;
  1529. if (O_CLOEXEC == 0) /* ancient libc */
  1530. close_on_exec_on(fd);
  1531. }
  1532. fp = xmalloc(sizeof(*fp));
  1533. if (name == NULL)
  1534. G.HFILE_stdin = fp;
  1535. fp->fd = fd;
  1536. fp->cur = fp->end = fp->buf;
  1537. fp->next_hfile = G.HFILE_list;
  1538. G.HFILE_list = fp;
  1539. return fp;
  1540. }
  1541. static void hfclose(HFILE *fp)
  1542. {
  1543. HFILE **pp = &G.HFILE_list;
  1544. while (*pp) {
  1545. HFILE *cur = *pp;
  1546. if (cur == fp) {
  1547. *pp = cur->next_hfile;
  1548. break;
  1549. }
  1550. pp = &cur->next_hfile;
  1551. }
  1552. if (fp->fd >= 0)
  1553. close(fp->fd);
  1554. free(fp);
  1555. }
  1556. static int refill_HFILE_and_getc(HFILE *fp)
  1557. {
  1558. int n;
  1559. if (fp->fd < 0) {
  1560. /* Already saw EOF */
  1561. return EOF;
  1562. }
  1563. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1564. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1565. * IOW: ^C will not immediately stop line input.
  1566. * But poll() is different: it does NOT restart after signals.
  1567. */
  1568. if (fp == G.HFILE_stdin) {
  1569. struct pollfd pfd[1];
  1570. pfd[0].fd = fp->fd;
  1571. pfd[0].events = POLLIN;
  1572. n = poll(pfd, 1, -1);
  1573. if (n < 0
  1574. /*&& errno == EINTR - assumed true */
  1575. && sigismember(&G.pending_set, SIGINT)
  1576. ) {
  1577. return '\0';
  1578. }
  1579. }
  1580. #else
  1581. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1582. #endif
  1583. /* Try to buffer more input */
  1584. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1585. if (n < 0) {
  1586. bb_simple_perror_msg("read error");
  1587. n = 0;
  1588. }
  1589. fp->cur = fp->buf;
  1590. fp->end = fp->buf + n;
  1591. if (n == 0) {
  1592. /* EOF/error */
  1593. close(fp->fd);
  1594. fp->fd = -1;
  1595. return EOF;
  1596. }
  1597. return (unsigned char)(*fp->cur++);
  1598. }
  1599. /* Inlined for common case of non-empty buffer.
  1600. */
  1601. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1602. {
  1603. if (fp->cur < fp->end)
  1604. return (unsigned char)(*fp->cur++);
  1605. /* Buffer empty */
  1606. return refill_HFILE_and_getc(fp);
  1607. }
  1608. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1609. {
  1610. HFILE *fl = G.HFILE_list;
  1611. while (fl) {
  1612. if (fd == fl->fd) {
  1613. /* We use it only on script files, they are all CLOEXEC */
  1614. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1615. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1616. return 1; /* "found and moved" */
  1617. }
  1618. fl = fl->next_hfile;
  1619. }
  1620. #if ENABLE_HUSH_MODE_X
  1621. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1622. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1623. return 1; /* "found and moved" */
  1624. }
  1625. #endif
  1626. return 0; /* "not in the list" */
  1627. }
  1628. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1629. static void close_all_HFILE_list(void)
  1630. {
  1631. HFILE *fl = G.HFILE_list;
  1632. while (fl) {
  1633. /* hfclose would also free HFILE object.
  1634. * It is disastrous if we share memory with a vforked parent.
  1635. * I'm not sure we never come here after vfork.
  1636. * Therefore just close fd, nothing more.
  1637. *
  1638. * ">" instead of ">=": we don't close fd#0,
  1639. * interactive shell uses hfopen(NULL) as stdin input
  1640. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1641. * If we'd close it here, then e.g. interactive "set | sort"
  1642. * with NOFORKed sort, would have sort's input fd closed.
  1643. */
  1644. if (fl->fd > 0)
  1645. /*hfclose(fl); - unsafe */
  1646. close(fl->fd);
  1647. fl = fl->next_hfile;
  1648. }
  1649. }
  1650. #endif
  1651. static int fd_in_HFILEs(int fd)
  1652. {
  1653. HFILE *fl = G.HFILE_list;
  1654. while (fl) {
  1655. if (fl->fd == fd)
  1656. return 1;
  1657. fl = fl->next_hfile;
  1658. }
  1659. return 0;
  1660. }
  1661. /* Helpers for setting new $n and restoring them back
  1662. */
  1663. typedef struct save_arg_t {
  1664. char *sv_argv0;
  1665. char **sv_g_argv;
  1666. int sv_g_argc;
  1667. IF_HUSH_SET(smallint sv_g_malloced;)
  1668. } save_arg_t;
  1669. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1670. {
  1671. sv->sv_argv0 = argv[0];
  1672. sv->sv_g_argv = G.global_argv;
  1673. sv->sv_g_argc = G.global_argc;
  1674. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1675. argv[0] = G.global_argv[0]; /* retain $0 */
  1676. G.global_argv = argv;
  1677. IF_HUSH_SET(G.global_args_malloced = 0;)
  1678. G.global_argc = 1 + string_array_len(argv + 1);
  1679. }
  1680. static void restore_G_args(save_arg_t *sv, char **argv)
  1681. {
  1682. #if ENABLE_HUSH_SET
  1683. if (G.global_args_malloced) {
  1684. /* someone ran "set -- arg1 arg2 ...", undo */
  1685. char **pp = G.global_argv;
  1686. while (*++pp) /* note: does not free $0 */
  1687. free(*pp);
  1688. free(G.global_argv);
  1689. }
  1690. #endif
  1691. argv[0] = sv->sv_argv0;
  1692. G.global_argv = sv->sv_g_argv;
  1693. G.global_argc = sv->sv_g_argc;
  1694. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1695. }
  1696. /* Basic theory of signal handling in shell
  1697. * ========================================
  1698. * This does not describe what hush does, rather, it is current understanding
  1699. * what it _should_ do. If it doesn't, it's a bug.
  1700. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1701. *
  1702. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1703. * is finished or backgrounded. It is the same in interactive and
  1704. * non-interactive shells, and is the same regardless of whether
  1705. * a user trap handler is installed or a shell special one is in effect.
  1706. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1707. * backgrounds (i.e. stops) or kills all members of currently running
  1708. * pipe.
  1709. *
  1710. * Wait builtin is interruptible by signals for which user trap is set
  1711. * or by SIGINT in interactive shell.
  1712. *
  1713. * Trap handlers will execute even within trap handlers. (right?)
  1714. *
  1715. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1716. * except for handlers set to '' (empty string).
  1717. *
  1718. * If job control is off, backgrounded commands ("cmd &")
  1719. * have SIGINT, SIGQUIT set to SIG_IGN.
  1720. *
  1721. * Commands which are run in command substitution ("`cmd`")
  1722. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1723. *
  1724. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1725. * by the shell from its parent.
  1726. *
  1727. * Signals which differ from SIG_DFL action
  1728. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1729. *
  1730. * SIGQUIT: ignore
  1731. * SIGTERM (interactive): ignore
  1732. * SIGHUP (interactive):
  1733. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1734. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1735. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1736. * that all pipe members are stopped. Try this in bash:
  1737. * while :; do :; done - ^Z does not background it
  1738. * (while :; do :; done) - ^Z backgrounds it
  1739. * SIGINT (interactive): wait for last pipe, ignore the rest
  1740. * of the command line, show prompt. NB: ^C does not send SIGINT
  1741. * to interactive shell while shell is waiting for a pipe,
  1742. * since shell is bg'ed (is not in foreground process group).
  1743. * Example 1: this waits 5 sec, but does not execute ls:
  1744. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1745. * Example 2: this does not wait and does not execute ls:
  1746. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1747. * Example 3: this does not wait 5 sec, but executes ls:
  1748. * "sleep 5; ls -l" + press ^C
  1749. * Example 4: this does not wait and does not execute ls:
  1750. * "sleep 5 & wait; ls -l" + press ^C
  1751. *
  1752. * (What happens to signals which are IGN on shell start?)
  1753. * (What happens with signal mask on shell start?)
  1754. *
  1755. * Old implementation
  1756. * ==================
  1757. * We use in-kernel pending signal mask to determine which signals were sent.
  1758. * We block all signals which we don't want to take action immediately,
  1759. * i.e. we block all signals which need to have special handling as described
  1760. * above, and all signals which have traps set.
  1761. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1762. * and act on them.
  1763. *
  1764. * unsigned special_sig_mask: a mask of such "special" signals
  1765. * sigset_t blocked_set: current blocked signal set
  1766. *
  1767. * "trap - SIGxxx":
  1768. * clear bit in blocked_set unless it is also in special_sig_mask
  1769. * "trap 'cmd' SIGxxx":
  1770. * set bit in blocked_set (even if 'cmd' is '')
  1771. * after [v]fork, if we plan to be a shell:
  1772. * unblock signals with special interactive handling
  1773. * (child shell is not interactive),
  1774. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1775. * after [v]fork, if we plan to exec:
  1776. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1777. * Restore blocked signal set to one inherited by shell just prior to exec.
  1778. *
  1779. * Note: as a result, we do not use signal handlers much. The only uses
  1780. * are to count SIGCHLDs
  1781. * and to restore tty pgrp on signal-induced exit.
  1782. *
  1783. * Note 2 (compat):
  1784. * Standard says "When a subshell is entered, traps that are not being ignored
  1785. * are set to the default actions". bash interprets it so that traps which
  1786. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1787. *
  1788. * Problem: the above approach makes it unwieldy to catch signals while
  1789. * we are in read builtin, or while we read commands from stdin:
  1790. * masked signals are not visible!
  1791. *
  1792. * New implementation
  1793. * ==================
  1794. * We record each signal we are interested in by installing signal handler
  1795. * for them - a bit like emulating kernel pending signal mask in userspace.
  1796. * We are interested in: signals which need to have special handling
  1797. * as described above, and all signals which have traps set.
  1798. * Signals are recorded in pending_set.
  1799. * After each pipe execution, we extract any pending signals
  1800. * and act on them.
  1801. *
  1802. * unsigned special_sig_mask: a mask of shell-special signals.
  1803. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1804. * char *traps[sig] if trap for sig is set (even if it's '').
  1805. * sigset_t pending_set: set of sigs we received.
  1806. *
  1807. * "trap - SIGxxx":
  1808. * if sig is in special_sig_mask, set handler back to:
  1809. * record_pending_signo, or to IGN if it's a tty stop signal
  1810. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1811. * else: set handler back to SIG_DFL
  1812. * "trap 'cmd' SIGxxx":
  1813. * set handler to record_pending_signo.
  1814. * "trap '' SIGxxx":
  1815. * set handler to SIG_IGN.
  1816. * after [v]fork, if we plan to be a shell:
  1817. * set signals with special interactive handling to SIG_DFL
  1818. * (because child shell is not interactive),
  1819. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1820. * after [v]fork, if we plan to exec:
  1821. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1822. *
  1823. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1824. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1825. *
  1826. * Note (compat):
  1827. * Standard says "When a subshell is entered, traps that are not being ignored
  1828. * are set to the default actions". bash interprets it so that traps which
  1829. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1830. */
  1831. enum {
  1832. SPECIAL_INTERACTIVE_SIGS = 0
  1833. | (1 << SIGTERM)
  1834. | (1 << SIGINT)
  1835. | (1 << SIGHUP)
  1836. ,
  1837. SPECIAL_JOBSTOP_SIGS = 0
  1838. #if ENABLE_HUSH_JOB
  1839. | (1 << SIGTTIN)
  1840. | (1 << SIGTTOU)
  1841. | (1 << SIGTSTP)
  1842. #endif
  1843. ,
  1844. };
  1845. static void record_pending_signo(int sig)
  1846. {
  1847. sigaddset(&G.pending_set, sig);
  1848. #if ENABLE_FEATURE_EDITING
  1849. bb_got_signal = sig; /* for read_line_input: "we got a signal" */
  1850. #endif
  1851. #if ENABLE_HUSH_FAST
  1852. if (sig == SIGCHLD) {
  1853. G.count_SIGCHLD++;
  1854. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1855. }
  1856. #endif
  1857. }
  1858. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1859. {
  1860. struct sigaction old_sa;
  1861. /* We could use signal() to install handlers... almost:
  1862. * except that we need to mask ALL signals while handlers run.
  1863. * I saw signal nesting in strace, race window isn't small.
  1864. * SA_RESTART is also needed, but in Linux, signal()
  1865. * sets SA_RESTART too.
  1866. */
  1867. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1868. /* sigfillset(&G.sa.sa_mask); - already done */
  1869. /* G.sa.sa_flags = SA_RESTART; - already done */
  1870. G.sa.sa_handler = handler;
  1871. sigaction(sig, &G.sa, &old_sa);
  1872. return old_sa.sa_handler;
  1873. }
  1874. static void hush_exit(int exitcode) NORETURN;
  1875. static void restore_ttypgrp_and__exit(void) NORETURN;
  1876. static void restore_ttypgrp_and__exit(void)
  1877. {
  1878. /* xfunc has failed! die die die */
  1879. /* no EXIT traps, this is an escape hatch! */
  1880. G.exiting = 1;
  1881. hush_exit(xfunc_error_retval);
  1882. }
  1883. #if ENABLE_HUSH_JOB
  1884. /* Needed only on some libc:
  1885. * It was observed that on exit(), fgetc'ed buffered data
  1886. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1887. * With the net effect that even after fork(), not vfork(),
  1888. * exit() in NOEXECed applet in "sh SCRIPT":
  1889. * noexec_applet_here
  1890. * echo END_OF_SCRIPT
  1891. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1892. * This makes "echo END_OF_SCRIPT" executed twice.
  1893. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1894. * and in `cmd` handling.
  1895. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1896. */
  1897. static void fflush_and__exit(void) NORETURN;
  1898. static void fflush_and__exit(void)
  1899. {
  1900. fflush_all();
  1901. _exit(xfunc_error_retval);
  1902. }
  1903. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1904. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1905. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1906. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1907. /* Restores tty foreground process group, and exits.
  1908. * May be called as signal handler for fatal signal
  1909. * (will resend signal to itself, producing correct exit state)
  1910. * or called directly with -EXITCODE.
  1911. * We also call it if xfunc is exiting.
  1912. */
  1913. static void sigexit(int sig) NORETURN;
  1914. static void sigexit(int sig)
  1915. {
  1916. /* Careful: we can end up here after [v]fork. Do not restore
  1917. * tty pgrp then, only top-level shell process does that */
  1918. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1919. /* Disable all signals: job control, SIGPIPE, etc.
  1920. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1921. */
  1922. sigprocmask_allsigs(SIG_BLOCK);
  1923. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1924. }
  1925. /* Not a signal, just exit */
  1926. if (sig <= 0)
  1927. _exit(- sig);
  1928. kill_myself_with_sig(sig); /* does not return */
  1929. }
  1930. #else
  1931. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1932. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1933. #endif
  1934. static sighandler_t pick_sighandler(unsigned sig)
  1935. {
  1936. sighandler_t handler = SIG_DFL;
  1937. if (sig < sizeof(unsigned)*8) {
  1938. unsigned sigmask = (1 << sig);
  1939. #if ENABLE_HUSH_JOB
  1940. /* is sig fatal? */
  1941. if (G_fatal_sig_mask & sigmask)
  1942. handler = sigexit;
  1943. else
  1944. #endif
  1945. /* sig has special handling? */
  1946. if (G.special_sig_mask & sigmask) {
  1947. handler = record_pending_signo;
  1948. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1949. * in order to ignore them: they will be raised
  1950. * in an endless loop when we try to do some
  1951. * terminal ioctls! We do have to _ignore_ these.
  1952. */
  1953. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1954. handler = SIG_IGN;
  1955. }
  1956. }
  1957. return handler;
  1958. }
  1959. /* Restores tty foreground process group, and exits. */
  1960. static void hush_exit(int exitcode)
  1961. {
  1962. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1963. save_history(G.line_input_state); /* may be NULL */
  1964. #endif
  1965. fflush_all();
  1966. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1967. char *argv[3];
  1968. /* argv[0] is unused */
  1969. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1970. argv[2] = NULL;
  1971. G.exiting = 1; /* prevent EXIT trap recursion */
  1972. /* Note: G_traps[0] is not cleared!
  1973. * "trap" will still show it, if executed
  1974. * in the handler */
  1975. builtin_eval(argv);
  1976. }
  1977. #if ENABLE_FEATURE_CLEAN_UP
  1978. {
  1979. struct variable *cur_var;
  1980. if (G.cwd != bb_msg_unknown)
  1981. free((char*)G.cwd);
  1982. cur_var = G.top_var;
  1983. while (cur_var) {
  1984. struct variable *tmp = cur_var;
  1985. if (!cur_var->max_len)
  1986. free(cur_var->varstr);
  1987. cur_var = cur_var->next;
  1988. free(tmp);
  1989. }
  1990. }
  1991. #endif
  1992. fflush_all();
  1993. #if ENABLE_HUSH_JOB
  1994. sigexit(- (exitcode & 0xff));
  1995. #else
  1996. _exit(exitcode);
  1997. #endif
  1998. }
  1999. //TODO: return a mask of ALL handled sigs?
  2000. static int check_and_run_traps(void)
  2001. {
  2002. int last_sig = 0;
  2003. while (1) {
  2004. int sig;
  2005. if (sigisemptyset(&G.pending_set))
  2006. break;
  2007. sig = 0;
  2008. do {
  2009. sig++;
  2010. if (sigismember(&G.pending_set, sig)) {
  2011. sigdelset(&G.pending_set, sig);
  2012. goto got_sig;
  2013. }
  2014. } while (sig < NSIG);
  2015. break;
  2016. got_sig:
  2017. #if ENABLE_HUSH_TRAP
  2018. if (G_traps && G_traps[sig]) {
  2019. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2020. if (G_traps[sig][0]) {
  2021. /* We have user-defined handler */
  2022. smalluint save_rcode;
  2023. int save_pre;
  2024. char *argv[3];
  2025. /* argv[0] is unused */
  2026. argv[1] = xstrdup(G_traps[sig]);
  2027. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2028. argv[2] = NULL;
  2029. save_pre = G.pre_trap_exitcode;
  2030. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2031. builtin_eval(argv);
  2032. free(argv[1]);
  2033. G.pre_trap_exitcode = save_pre;
  2034. G.last_exitcode = save_rcode;
  2035. # if ENABLE_HUSH_FUNCTIONS
  2036. if (G.return_exitcode >= 0) {
  2037. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2038. G.last_exitcode = G.return_exitcode;
  2039. }
  2040. # endif
  2041. last_sig = sig;
  2042. } /* else: "" trap, ignoring signal */
  2043. continue;
  2044. }
  2045. #endif
  2046. /* not a trap: special action */
  2047. switch (sig) {
  2048. case SIGINT:
  2049. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2050. G.flag_SIGINT = 1;
  2051. last_sig = sig;
  2052. break;
  2053. #if ENABLE_HUSH_JOB
  2054. case SIGHUP: {
  2055. //TODO: why are we doing this? ash and dash don't do this,
  2056. //they have no handler for SIGHUP at all,
  2057. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2058. struct pipe *job;
  2059. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2060. /* bash is observed to signal whole process groups,
  2061. * not individual processes */
  2062. for (job = G.job_list; job; job = job->next) {
  2063. if (job->pgrp <= 0)
  2064. continue;
  2065. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2066. if (kill(- job->pgrp, SIGHUP) == 0)
  2067. kill(- job->pgrp, SIGCONT);
  2068. }
  2069. sigexit(SIGHUP);
  2070. }
  2071. #endif
  2072. #if ENABLE_HUSH_FAST
  2073. case SIGCHLD:
  2074. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2075. G.count_SIGCHLD++;
  2076. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2077. /* Note:
  2078. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2079. * This simplifies wait builtin a bit.
  2080. */
  2081. break;
  2082. #endif
  2083. default: /* ignored: */
  2084. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2085. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2086. /* Note:
  2087. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2088. * Example: wait is not interrupted by TERM
  2089. * in interactive shell, because TERM is ignored.
  2090. */
  2091. break;
  2092. }
  2093. }
  2094. return last_sig;
  2095. }
  2096. static const char *get_cwd(int force)
  2097. {
  2098. if (force || G.cwd == NULL) {
  2099. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2100. * we must not try to free(bb_msg_unknown) */
  2101. if (G.cwd == bb_msg_unknown)
  2102. G.cwd = NULL;
  2103. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2104. if (!G.cwd)
  2105. G.cwd = bb_msg_unknown;
  2106. }
  2107. return G.cwd;
  2108. }
  2109. /*
  2110. * Shell and environment variable support
  2111. */
  2112. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2113. {
  2114. struct variable **pp;
  2115. struct variable *cur;
  2116. pp = &G.top_var;
  2117. while ((cur = *pp) != NULL) {
  2118. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2119. return pp;
  2120. pp = &cur->next;
  2121. }
  2122. return NULL;
  2123. }
  2124. static const char* FAST_FUNC get_local_var_value(const char *name)
  2125. {
  2126. struct variable **vpp;
  2127. unsigned len = strlen(name);
  2128. if (G.expanded_assignments) {
  2129. char **cpp = G.expanded_assignments;
  2130. while (*cpp) {
  2131. char *cp = *cpp;
  2132. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2133. return cp + len + 1;
  2134. cpp++;
  2135. }
  2136. }
  2137. vpp = get_ptr_to_local_var(name, len);
  2138. if (vpp)
  2139. return (*vpp)->varstr + len + 1;
  2140. if (strcmp(name, "PPID") == 0)
  2141. return utoa(G.root_ppid);
  2142. // bash compat: UID? EUID?
  2143. #if ENABLE_HUSH_RANDOM_SUPPORT
  2144. if (strcmp(name, "RANDOM") == 0)
  2145. return utoa(next_random(&G.random_gen));
  2146. #endif
  2147. #if ENABLE_HUSH_LINENO_VAR
  2148. if (strcmp(name, "LINENO") == 0)
  2149. return utoa(G.execute_lineno);
  2150. #endif
  2151. #if BASH_EPOCH_VARS
  2152. {
  2153. const char *fmt = NULL;
  2154. if (strcmp(name, "EPOCHSECONDS") == 0)
  2155. fmt = "%llu";
  2156. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2157. fmt = "%llu.%06u";
  2158. if (fmt) {
  2159. struct timeval tv;
  2160. xgettimeofday(&tv);
  2161. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2162. (unsigned)tv.tv_usec);
  2163. return G.epoch_buf;
  2164. }
  2165. }
  2166. #endif
  2167. return NULL;
  2168. }
  2169. #if ENABLE_HUSH_GETOPTS
  2170. static void handle_changed_special_names(const char *name, unsigned name_len)
  2171. {
  2172. if (name_len == 6) {
  2173. if (strncmp(name, "OPTIND", 6) == 0) {
  2174. G.getopt_count = 0;
  2175. return;
  2176. }
  2177. }
  2178. }
  2179. #else
  2180. /* Do not even bother evaluating arguments */
  2181. # define handle_changed_special_names(...) ((void)0)
  2182. #endif
  2183. /* str holds "NAME=VAL" and is expected to be malloced.
  2184. * We take ownership of it.
  2185. */
  2186. #define SETFLAG_EXPORT (1 << 0)
  2187. #define SETFLAG_UNEXPORT (1 << 1)
  2188. #define SETFLAG_MAKE_RO (1 << 2)
  2189. #define SETFLAG_VARLVL_SHIFT 3
  2190. static int set_local_var(char *str, unsigned flags)
  2191. {
  2192. struct variable **cur_pp;
  2193. struct variable *cur;
  2194. char *free_me = NULL;
  2195. char *eq_sign;
  2196. int name_len;
  2197. int retval;
  2198. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2199. eq_sign = strchr(str, '=');
  2200. if (HUSH_DEBUG && !eq_sign)
  2201. bb_simple_error_msg_and_die("BUG in setvar");
  2202. name_len = eq_sign - str + 1; /* including '=' */
  2203. cur_pp = &G.top_var;
  2204. while ((cur = *cur_pp) != NULL) {
  2205. if (strncmp(cur->varstr, str, name_len) != 0) {
  2206. cur_pp = &cur->next;
  2207. continue;
  2208. }
  2209. /* We found an existing var with this name */
  2210. if (cur->flg_read_only) {
  2211. bb_error_msg("%s: readonly variable", str);
  2212. free(str);
  2213. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2214. //but export per se succeeds (does put the var in env). We don't mimic that.
  2215. return -1;
  2216. }
  2217. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2218. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2219. *eq_sign = '\0';
  2220. unsetenv(str);
  2221. *eq_sign = '=';
  2222. }
  2223. if (cur->var_nest_level < local_lvl) {
  2224. /* bash 3.2.33(1) and exported vars:
  2225. * # export z=z
  2226. * # f() { local z=a; env | grep ^z; }
  2227. * # f
  2228. * z=a
  2229. * # env | grep ^z
  2230. * z=z
  2231. */
  2232. if (cur->flg_export)
  2233. flags |= SETFLAG_EXPORT;
  2234. /* New variable is local ("local VAR=VAL" or
  2235. * "VAR=VAL cmd")
  2236. * and existing one is global, or local
  2237. * on a lower level that new one.
  2238. * Remove it from global variable list:
  2239. */
  2240. *cur_pp = cur->next;
  2241. if (G.shadowed_vars_pp) {
  2242. /* Save in "shadowed" list */
  2243. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2244. cur->flg_export ? "exported " : "",
  2245. cur->varstr, cur->var_nest_level, str, local_lvl
  2246. );
  2247. cur->next = *G.shadowed_vars_pp;
  2248. *G.shadowed_vars_pp = cur;
  2249. } else {
  2250. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2251. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2252. cur->flg_export ? "exported " : "",
  2253. cur->varstr, cur->var_nest_level, str, local_lvl
  2254. );
  2255. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2256. free_me = cur->varstr; /* then free it later */
  2257. free(cur);
  2258. }
  2259. break;
  2260. }
  2261. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2262. debug_printf_env("assignement '%s' does not change anything\n", str);
  2263. free_and_exp:
  2264. free(str);
  2265. goto exp;
  2266. }
  2267. /* Replace the value in the found "struct variable" */
  2268. if (cur->max_len != 0) {
  2269. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2270. /* This one is from startup env, reuse space */
  2271. debug_printf_env("reusing startup env for '%s'\n", str);
  2272. strcpy(cur->varstr, str);
  2273. goto free_and_exp;
  2274. }
  2275. /* Can't reuse */
  2276. cur->max_len = 0;
  2277. goto set_str_and_exp;
  2278. }
  2279. /* max_len == 0 signifies "malloced" var, which we can
  2280. * (and have to) free. But we can't free(cur->varstr) here:
  2281. * if cur->flg_export is 1, it is in the environment.
  2282. * We should either unsetenv+free, or wait until putenv,
  2283. * then putenv(new)+free(old).
  2284. */
  2285. free_me = cur->varstr;
  2286. goto set_str_and_exp;
  2287. }
  2288. /* Not found or shadowed - create new variable struct */
  2289. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2290. cur = xzalloc(sizeof(*cur));
  2291. cur->var_nest_level = local_lvl;
  2292. cur->next = *cur_pp;
  2293. *cur_pp = cur;
  2294. set_str_and_exp:
  2295. cur->varstr = str;
  2296. exp:
  2297. #if !BB_MMU || ENABLE_HUSH_READONLY
  2298. if (flags & SETFLAG_MAKE_RO) {
  2299. cur->flg_read_only = 1;
  2300. }
  2301. #endif
  2302. if (flags & SETFLAG_EXPORT)
  2303. cur->flg_export = 1;
  2304. retval = 0;
  2305. if (cur->flg_export) {
  2306. if (flags & SETFLAG_UNEXPORT) {
  2307. cur->flg_export = 0;
  2308. /* unsetenv was already done */
  2309. } else {
  2310. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2311. retval = putenv(cur->varstr);
  2312. /* fall through to "free(free_me)" -
  2313. * only now we can free old exported malloced string
  2314. */
  2315. }
  2316. }
  2317. free(free_me);
  2318. handle_changed_special_names(cur->varstr, name_len - 1);
  2319. return retval;
  2320. }
  2321. static int set_local_var0(char *str)
  2322. {
  2323. return set_local_var(str, 0);
  2324. }
  2325. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2326. {
  2327. char *var = xasprintf("%s=%s", name, val);
  2328. set_local_var0(var);
  2329. }
  2330. /* Used at startup and after each cd */
  2331. static void set_pwd_var(unsigned flag)
  2332. {
  2333. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2334. }
  2335. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2336. static int unset_local_var_len(const char *name, int name_len)
  2337. {
  2338. struct variable *cur;
  2339. struct variable **cur_pp;
  2340. cur_pp = &G.top_var;
  2341. while ((cur = *cur_pp) != NULL) {
  2342. if (strncmp(cur->varstr, name, name_len) == 0
  2343. && cur->varstr[name_len] == '='
  2344. ) {
  2345. if (cur->flg_read_only) {
  2346. bb_error_msg("%s: readonly variable", name);
  2347. return EXIT_FAILURE;
  2348. }
  2349. *cur_pp = cur->next;
  2350. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2351. bb_unsetenv(cur->varstr);
  2352. if (!cur->max_len)
  2353. free(cur->varstr);
  2354. free(cur);
  2355. break;
  2356. }
  2357. cur_pp = &cur->next;
  2358. }
  2359. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2360. handle_changed_special_names(name, name_len);
  2361. return EXIT_SUCCESS;
  2362. }
  2363. static int unset_local_var(const char *name)
  2364. {
  2365. return unset_local_var_len(name, strlen(name));
  2366. }
  2367. #endif
  2368. /*
  2369. * Helpers for "var1=val1 var2=val2 cmd" feature
  2370. */
  2371. static void add_vars(struct variable *var)
  2372. {
  2373. struct variable *next;
  2374. while (var) {
  2375. next = var->next;
  2376. var->next = G.top_var;
  2377. G.top_var = var;
  2378. if (var->flg_export) {
  2379. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2380. putenv(var->varstr);
  2381. } else {
  2382. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2383. }
  2384. var = next;
  2385. }
  2386. }
  2387. /* We put strings[i] into variable table and possibly putenv them.
  2388. * If variable is read only, we can free the strings[i]
  2389. * which attempts to overwrite it.
  2390. * The strings[] vector itself is freed.
  2391. */
  2392. static void set_vars_and_save_old(char **strings)
  2393. {
  2394. char **s;
  2395. if (!strings)
  2396. return;
  2397. s = strings;
  2398. while (*s) {
  2399. struct variable *var_p;
  2400. struct variable **var_pp;
  2401. char *eq;
  2402. eq = strchr(*s, '=');
  2403. if (HUSH_DEBUG && !eq)
  2404. bb_simple_error_msg_and_die("BUG in varexp4");
  2405. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2406. if (var_pp) {
  2407. var_p = *var_pp;
  2408. if (var_p->flg_read_only) {
  2409. char **p;
  2410. bb_error_msg("%s: readonly variable", *s);
  2411. /*
  2412. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2413. * If VAR is readonly, leaving it in the list
  2414. * after asssignment error (msg above)
  2415. * causes doubled error message later, on unset.
  2416. */
  2417. debug_printf_env("removing/freeing '%s' element\n", *s);
  2418. free(*s);
  2419. p = s;
  2420. do { *p = p[1]; p++; } while (*p);
  2421. goto next;
  2422. }
  2423. /* below, set_local_var() with nest level will
  2424. * "shadow" (remove) this variable from
  2425. * global linked list.
  2426. */
  2427. }
  2428. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2429. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2430. s++;
  2431. next: ;
  2432. }
  2433. free(strings);
  2434. }
  2435. /*
  2436. * Unicode helper
  2437. */
  2438. static void reinit_unicode_for_hush(void)
  2439. {
  2440. /* Unicode support should be activated even if LANG is set
  2441. * _during_ shell execution, not only if it was set when
  2442. * shell was started. Therefore, re-check LANG every time:
  2443. */
  2444. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2445. || ENABLE_UNICODE_USING_LOCALE
  2446. ) {
  2447. const char *s = get_local_var_value("LC_ALL");
  2448. if (!s) s = get_local_var_value("LC_CTYPE");
  2449. if (!s) s = get_local_var_value("LANG");
  2450. reinit_unicode(s);
  2451. }
  2452. }
  2453. /*
  2454. * in_str support (strings, and "strings" read from files).
  2455. */
  2456. #if ENABLE_HUSH_INTERACTIVE
  2457. /* To test correct lineedit/interactive behavior, type from command line:
  2458. * echo $P\
  2459. * \
  2460. * AT\
  2461. * H\
  2462. * \
  2463. * It exercises a lot of corner cases.
  2464. */
  2465. static const char *setup_prompt_string(void)
  2466. {
  2467. const char *prompt_str;
  2468. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2469. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2470. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2471. if (!prompt_str)
  2472. prompt_str = "";
  2473. # else
  2474. prompt_str = "> "; /* if PS2, else... */
  2475. if (G.promptmode == 0) { /* PS1 */
  2476. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2477. free(G.PS1);
  2478. /* bash uses $PWD value, even if it is set by user.
  2479. * It uses current dir only if PWD is unset.
  2480. * We always use current dir. */
  2481. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2482. }
  2483. # endif
  2484. debug_printf("prompt_str '%s'\n", prompt_str);
  2485. return prompt_str;
  2486. }
  2487. static int get_user_input(struct in_str *i)
  2488. {
  2489. # if ENABLE_FEATURE_EDITING
  2490. /* In EDITING case, this function reads next input line,
  2491. * saves it in i->p, then returns 1st char of it.
  2492. */
  2493. int r;
  2494. const char *prompt_str;
  2495. prompt_str = setup_prompt_string();
  2496. for (;;) {
  2497. reinit_unicode_for_hush();
  2498. G.flag_SIGINT = 0;
  2499. bb_got_signal = 0;
  2500. if (!sigisemptyset(&G.pending_set)) {
  2501. /* Whoops, already got a signal, do not call read_line_input */
  2502. bb_got_signal = r = -1;
  2503. } else {
  2504. /* For shell, LI_INTERRUPTIBLE is set:
  2505. * read_line_input will abort on either
  2506. * getting EINTR in poll(), or if it sees bb_got_signal != 0
  2507. * (IOW: if signal arrives before poll() is reached).
  2508. * Interactive testcases:
  2509. * (while kill -INT $$; do sleep 1; done) &
  2510. * #^^^ prints ^C, prints prompt, repeats
  2511. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  2512. * #^^^ prints ^C, prints "I", prints prompt, repeats
  2513. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  2514. * #^^^ prints "T", prints prompt, repeats
  2515. * #(bash 5.0.17 exits after first "T", looks like a bug)
  2516. */
  2517. r = read_line_input(G.line_input_state, prompt_str,
  2518. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2519. );
  2520. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2521. if (r == 0)
  2522. raise(SIGINT);
  2523. }
  2524. /* bash prints ^C (before running a trap, if any)
  2525. * both on keyboard ^C and on real SIGINT (non-kbd generated).
  2526. */
  2527. if (sigismember(&G.pending_set, SIGINT)) {
  2528. write(STDOUT_FILENO, "^C\n", 3);
  2529. G.last_exitcode = 128 | SIGINT;
  2530. }
  2531. check_and_run_traps();
  2532. if (r == 0) /* keyboard ^C? */
  2533. continue; /* go back, read another input line */
  2534. if (r > 0) /* normal input? (no ^C, no ^D, no signals) */
  2535. break;
  2536. if (!bb_got_signal) {
  2537. /* r < 0: ^D/EOF/error detected (but not signal) */
  2538. /* ^D on interactive input goes to next line before exiting: */
  2539. write(STDOUT_FILENO, "\n", 1);
  2540. i->p = NULL;
  2541. i->peek_buf[0] = r = EOF;
  2542. return r;
  2543. }
  2544. /* it was a signal: go back, read another input line */
  2545. }
  2546. i->p = G.user_input_buf;
  2547. return (unsigned char)*i->p++;
  2548. # else
  2549. /* In !EDITING case, this function gets called for every char.
  2550. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2551. */
  2552. int r;
  2553. for (;;) {
  2554. G.flag_SIGINT = 0;
  2555. if (i->last_char == '\0' || i->last_char == '\n') {
  2556. const char *prompt_str = setup_prompt_string();
  2557. /* Why check_and_run_traps here? Try this interactively:
  2558. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2559. * $ <[enter], repeatedly...>
  2560. * Without check_and_run_traps, handler never runs.
  2561. */
  2562. check_and_run_traps();
  2563. fputs_stdout(prompt_str);
  2564. fflush_all();
  2565. }
  2566. r = hfgetc(i->file);
  2567. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2568. * no ^C masking happens during fgetc, no special code for ^C:
  2569. * it generates SIGINT as usual.
  2570. */
  2571. check_and_run_traps();
  2572. if (r != '\0' && !G.flag_SIGINT)
  2573. break;
  2574. if (G.flag_SIGINT) {
  2575. /* ^C or SIGINT: repeat */
  2576. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2577. /* kernel prints "^C" itself, just print newline: */
  2578. write(STDOUT_FILENO, "\n", 1);
  2579. G.last_exitcode = 128 | SIGINT;
  2580. }
  2581. }
  2582. return r;
  2583. # endif
  2584. }
  2585. /* This is the magic location that prints prompts
  2586. * and gets data back from the user */
  2587. static int fgetc_interactive(struct in_str *i)
  2588. {
  2589. int ch;
  2590. /* If it's interactive stdin, get new line. */
  2591. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2592. /* Returns first char (or EOF), the rest is in i->p[] */
  2593. ch = get_user_input(i);
  2594. G.promptmode = 1; /* PS2 */
  2595. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2596. } else {
  2597. /* Not stdin: script file, sourced file, etc */
  2598. do ch = hfgetc(i->file); while (ch == '\0');
  2599. }
  2600. return ch;
  2601. }
  2602. #else /* !INTERACTIVE */
  2603. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2604. {
  2605. int ch;
  2606. do ch = hfgetc(i->file); while (ch == '\0');
  2607. return ch;
  2608. }
  2609. #endif /* !INTERACTIVE */
  2610. static int i_getch(struct in_str *i)
  2611. {
  2612. int ch;
  2613. if (!i->file) {
  2614. /* string-based in_str */
  2615. ch = (unsigned char)*i->p;
  2616. if (ch != '\0') {
  2617. i->p++;
  2618. i->last_char = ch;
  2619. #if ENABLE_HUSH_LINENO_VAR
  2620. if (ch == '\n') {
  2621. G.parse_lineno++;
  2622. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2623. }
  2624. #endif
  2625. return ch;
  2626. }
  2627. return EOF;
  2628. }
  2629. /* FILE-based in_str */
  2630. #if ENABLE_FEATURE_EDITING
  2631. /* This can be stdin, check line editing char[] buffer */
  2632. if (i->p && *i->p != '\0') {
  2633. ch = (unsigned char)*i->p++;
  2634. goto out;
  2635. }
  2636. #endif
  2637. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2638. ch = i->peek_buf[0];
  2639. if (ch != 0) {
  2640. int ch2 = i->peek_buf[1];
  2641. i->peek_buf[0] = ch2;
  2642. if (ch2 == 0) /* very likely, avoid redundant write */
  2643. goto out;
  2644. i->peek_buf[1] = 0;
  2645. goto out;
  2646. }
  2647. ch = fgetc_interactive(i);
  2648. out:
  2649. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2650. i->last_char = ch;
  2651. #if ENABLE_HUSH_LINENO_VAR
  2652. if (ch == '\n') {
  2653. G.parse_lineno++;
  2654. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2655. }
  2656. #endif
  2657. return ch;
  2658. }
  2659. static int i_peek(struct in_str *i)
  2660. {
  2661. int ch;
  2662. if (!i->file) {
  2663. /* string-based in_str */
  2664. /* Doesn't report EOF on NUL. None of the callers care. */
  2665. return (unsigned char)*i->p;
  2666. }
  2667. /* FILE-based in_str */
  2668. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2669. /* This can be stdin, check line editing char[] buffer */
  2670. if (i->p && *i->p != '\0')
  2671. return (unsigned char)*i->p;
  2672. #endif
  2673. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2674. ch = i->peek_buf[0];
  2675. if (ch != 0)
  2676. return ch;
  2677. /* Need to get a new char */
  2678. ch = fgetc_interactive(i);
  2679. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2680. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2681. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2682. if (i->p) {
  2683. i->p -= 1;
  2684. return ch;
  2685. }
  2686. #endif
  2687. i->peek_buf[0] = ch;
  2688. /*i->peek_buf[1] = 0; - already is */
  2689. return ch;
  2690. }
  2691. /* Only ever called if i_peek() was called, and did not return EOF.
  2692. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2693. * not end-of-line. Therefore we never need to read a new editing line here.
  2694. */
  2695. static int i_peek2(struct in_str *i)
  2696. {
  2697. int ch;
  2698. /* There are two cases when i->p[] buffer exists.
  2699. * (1) it's a string in_str.
  2700. * (2) It's a file, and we have a saved line editing buffer.
  2701. * In both cases, we know that i->p[0] exists and not NUL, and
  2702. * the peek2 result is in i->p[1].
  2703. */
  2704. if (i->p)
  2705. return (unsigned char)i->p[1];
  2706. /* Now we know it is a file-based in_str. */
  2707. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2708. /* Is there 2nd char? */
  2709. ch = i->peek_buf[1];
  2710. if (ch == 0) {
  2711. /* We did not read it yet, get it now */
  2712. do ch = hfgetc(i->file); while (ch == '\0');
  2713. i->peek_buf[1] = ch;
  2714. }
  2715. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2716. return ch;
  2717. }
  2718. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2719. {
  2720. for (;;) {
  2721. int ch, ch2;
  2722. ch = i_getch(input);
  2723. if (ch != '\\')
  2724. return ch;
  2725. ch2 = i_peek(input);
  2726. if (ch2 != '\n')
  2727. return ch;
  2728. /* backslash+newline, skip it */
  2729. i_getch(input);
  2730. }
  2731. }
  2732. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2733. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2734. */
  2735. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2736. {
  2737. for (;;) {
  2738. int ch, ch2;
  2739. ch = i_peek(input);
  2740. if (ch != '\\')
  2741. return ch;
  2742. ch2 = i_peek2(input);
  2743. if (ch2 != '\n')
  2744. return ch;
  2745. /* backslash+newline, skip it */
  2746. i_getch(input);
  2747. i_getch(input);
  2748. }
  2749. }
  2750. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2751. {
  2752. memset(i, 0, sizeof(*i));
  2753. i->file = fp;
  2754. /* i->p = NULL; */
  2755. }
  2756. static void setup_string_in_str(struct in_str *i, const char *s)
  2757. {
  2758. memset(i, 0, sizeof(*i));
  2759. /*i->file = NULL */;
  2760. i->p = s;
  2761. }
  2762. /*
  2763. * o_string support
  2764. */
  2765. #define B_CHUNK (32 * sizeof(char*))
  2766. static void o_reset_to_empty_unquoted(o_string *o)
  2767. {
  2768. o->length = 0;
  2769. o->has_quoted_part = 0;
  2770. if (o->data)
  2771. o->data[0] = '\0';
  2772. }
  2773. static void o_free_and_set_NULL(o_string *o)
  2774. {
  2775. free(o->data);
  2776. memset(o, 0, sizeof(*o));
  2777. }
  2778. static ALWAYS_INLINE void o_free(o_string *o)
  2779. {
  2780. free(o->data);
  2781. }
  2782. static void o_grow_by(o_string *o, int len)
  2783. {
  2784. if (o->length + len > o->maxlen) {
  2785. o->maxlen += (2 * len) | (B_CHUNK-1);
  2786. o->data = xrealloc(o->data, 1 + o->maxlen);
  2787. }
  2788. }
  2789. static void o_addchr(o_string *o, int ch)
  2790. {
  2791. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2792. if (o->length < o->maxlen) {
  2793. /* likely. avoid o_grow_by() call */
  2794. add:
  2795. o->data[o->length] = ch;
  2796. o->length++;
  2797. o->data[o->length] = '\0';
  2798. return;
  2799. }
  2800. o_grow_by(o, 1);
  2801. goto add;
  2802. }
  2803. #if 0
  2804. /* Valid only if we know o_string is not empty */
  2805. static void o_delchr(o_string *o)
  2806. {
  2807. o->length--;
  2808. o->data[o->length] = '\0';
  2809. }
  2810. #endif
  2811. static void o_addblock(o_string *o, const char *str, int len)
  2812. {
  2813. o_grow_by(o, len);
  2814. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2815. o->length += len;
  2816. }
  2817. static void o_addstr(o_string *o, const char *str)
  2818. {
  2819. o_addblock(o, str, strlen(str));
  2820. }
  2821. static void o_addstr_with_NUL(o_string *o, const char *str)
  2822. {
  2823. o_addblock(o, str, strlen(str) + 1);
  2824. }
  2825. #if !BB_MMU
  2826. static void nommu_addchr(o_string *o, int ch)
  2827. {
  2828. if (o)
  2829. o_addchr(o, ch);
  2830. }
  2831. #else
  2832. # define nommu_addchr(o, str) ((void)0)
  2833. #endif
  2834. #if ENABLE_HUSH_MODE_X
  2835. static void x_mode_addchr(int ch)
  2836. {
  2837. o_addchr(&G.x_mode_buf, ch);
  2838. }
  2839. static void x_mode_addstr(const char *str)
  2840. {
  2841. o_addstr(&G.x_mode_buf, str);
  2842. }
  2843. static void x_mode_addblock(const char *str, int len)
  2844. {
  2845. o_addblock(&G.x_mode_buf, str, len);
  2846. }
  2847. static void x_mode_prefix(void)
  2848. {
  2849. int n = G.x_mode_depth;
  2850. do x_mode_addchr('+'); while (--n >= 0);
  2851. }
  2852. static void x_mode_flush(void)
  2853. {
  2854. int len = G.x_mode_buf.length;
  2855. if (len <= 0)
  2856. return;
  2857. if (G.x_mode_fd > 0) {
  2858. G.x_mode_buf.data[len] = '\n';
  2859. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2860. }
  2861. G.x_mode_buf.length = 0;
  2862. }
  2863. #endif
  2864. /*
  2865. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2866. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2867. * Apparently, on unquoted $v bash still does globbing
  2868. * ("v='*.txt'; echo $v" prints all .txt files),
  2869. * but NOT brace expansion! Thus, there should be TWO independent
  2870. * quoting mechanisms on $v expansion side: one protects
  2871. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2872. * We have only second one.
  2873. */
  2874. #if ENABLE_HUSH_BRACE_EXPANSION
  2875. # define MAYBE_BRACES "{}"
  2876. #else
  2877. # define MAYBE_BRACES ""
  2878. #endif
  2879. /* My analysis of quoting semantics tells me that state information
  2880. * is associated with a destination, not a source.
  2881. */
  2882. static void o_addqchr(o_string *o, int ch)
  2883. {
  2884. int sz = 1;
  2885. /* '-' is included because of this case:
  2886. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2887. */
  2888. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2889. if (found)
  2890. sz++;
  2891. o_grow_by(o, sz);
  2892. if (found) {
  2893. o->data[o->length] = '\\';
  2894. o->length++;
  2895. }
  2896. o->data[o->length] = ch;
  2897. o->length++;
  2898. o->data[o->length] = '\0';
  2899. }
  2900. static void o_addQchr(o_string *o, int ch)
  2901. {
  2902. int sz = 1;
  2903. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2904. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2905. ) {
  2906. sz++;
  2907. o->data[o->length] = '\\';
  2908. o->length++;
  2909. }
  2910. o_grow_by(o, sz);
  2911. o->data[o->length] = ch;
  2912. o->length++;
  2913. o->data[o->length] = '\0';
  2914. }
  2915. static void o_addqblock(o_string *o, const char *str, int len)
  2916. {
  2917. while (len) {
  2918. char ch;
  2919. int sz;
  2920. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2921. if (ordinary_cnt > len) /* paranoia */
  2922. ordinary_cnt = len;
  2923. o_addblock(o, str, ordinary_cnt);
  2924. if (ordinary_cnt == len)
  2925. return; /* NUL is already added by o_addblock */
  2926. str += ordinary_cnt;
  2927. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2928. ch = *str++;
  2929. sz = 1;
  2930. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2931. sz++;
  2932. o->data[o->length] = '\\';
  2933. o->length++;
  2934. }
  2935. o_grow_by(o, sz);
  2936. o->data[o->length] = ch;
  2937. o->length++;
  2938. }
  2939. o->data[o->length] = '\0';
  2940. }
  2941. static void o_addQblock(o_string *o, const char *str, int len)
  2942. {
  2943. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2944. o_addblock(o, str, len);
  2945. return;
  2946. }
  2947. o_addqblock(o, str, len);
  2948. }
  2949. static void o_addQstr(o_string *o, const char *str)
  2950. {
  2951. o_addQblock(o, str, strlen(str));
  2952. }
  2953. /* A special kind of o_string for $VAR and `cmd` expansion.
  2954. * It contains char* list[] at the beginning, which is grown in 16 element
  2955. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2956. * list[i] contains an INDEX (int!) into this string data.
  2957. * It means that if list[] needs to grow, data needs to be moved higher up
  2958. * but list[i]'s need not be modified.
  2959. * NB: remembering how many list[i]'s you have there is crucial.
  2960. * o_finalize_list() operation post-processes this structure - calculates
  2961. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2962. */
  2963. #if DEBUG_EXPAND || DEBUG_GLOB
  2964. static void debug_print_list(const char *prefix, o_string *o, int n)
  2965. {
  2966. char **list = (char**)o->data;
  2967. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2968. int i = 0;
  2969. indent();
  2970. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2971. prefix, list, n, string_start, o->length, o->maxlen,
  2972. !!(o->o_expflags & EXP_FLAG_GLOB),
  2973. o->has_quoted_part,
  2974. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2975. while (i < n) {
  2976. indent();
  2977. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2978. o->data + (int)(uintptr_t)list[i] + string_start,
  2979. o->data + (int)(uintptr_t)list[i] + string_start);
  2980. i++;
  2981. }
  2982. if (n) {
  2983. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2984. indent();
  2985. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2986. }
  2987. }
  2988. #else
  2989. # define debug_print_list(prefix, o, n) ((void)0)
  2990. #endif
  2991. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2992. * in list[n] so that it points past last stored byte so far.
  2993. * It returns n+1. */
  2994. static int o_save_ptr_helper(o_string *o, int n)
  2995. {
  2996. char **list = (char**)o->data;
  2997. int string_start;
  2998. int string_len;
  2999. if (!o->has_empty_slot) {
  3000. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3001. string_len = o->length - string_start;
  3002. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  3003. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  3004. /* list[n] points to string_start, make space for 16 more pointers */
  3005. o->maxlen += 0x10 * sizeof(list[0]);
  3006. o->data = xrealloc(o->data, o->maxlen + 1);
  3007. list = (char**)o->data;
  3008. memmove(list + n + 0x10, list + n, string_len);
  3009. /*
  3010. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  3011. * check. (grep for -prev-ifs-check-).
  3012. * Ensure that argv[-1][last] is not garbage
  3013. * but zero bytes, to save index check there.
  3014. */
  3015. list[n + 0x10 - 1] = 0;
  3016. o->length += 0x10 * sizeof(list[0]);
  3017. } else {
  3018. debug_printf_list("list[%d]=%d string_start=%d\n",
  3019. n, string_len, string_start);
  3020. }
  3021. } else {
  3022. /* We have empty slot at list[n], reuse without growth */
  3023. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  3024. string_len = o->length - string_start;
  3025. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  3026. n, string_len, string_start);
  3027. o->has_empty_slot = 0;
  3028. }
  3029. o->has_quoted_part = 0;
  3030. list[n] = (char*)(uintptr_t)string_len;
  3031. return n + 1;
  3032. }
  3033. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  3034. static int o_get_last_ptr(o_string *o, int n)
  3035. {
  3036. char **list = (char**)o->data;
  3037. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3038. return ((int)(uintptr_t)list[n-1]) + string_start;
  3039. }
  3040. /*
  3041. * Globbing routines.
  3042. *
  3043. * Most words in commands need to be globbed, even ones which are
  3044. * (single or double) quoted. This stems from the possiblity of
  3045. * constructs like "abc"* and 'abc'* - these should be globbed.
  3046. * Having a different code path for fully-quoted strings ("abc",
  3047. * 'abc') would only help performance-wise, but we still need
  3048. * code for partially-quoted strings.
  3049. *
  3050. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3051. * the logic can't be "shell-syntax argument is first transformed
  3052. * to a string, then globbed, and if globbing does not match anything,
  3053. * it is used verbatim". Here are two examples where it fails:
  3054. *
  3055. * echo 'b\*'?
  3056. *
  3057. * The globbing can't be avoided (because of '?' at the end).
  3058. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3059. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3060. * - IOW: they "unbackslash" the glob pattern.
  3061. * Now, look at this:
  3062. *
  3063. * v='\\\*'; echo b$v?
  3064. *
  3065. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3066. * should be used as glob pattern with no changes. However, if glob
  3067. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3068. *
  3069. * ash implements this by having an encoded representation of the word
  3070. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3071. * Glob pattern is derived from it. If glob fails, the decision what result
  3072. * should be is made using that encoded representation. Not glob pattern.
  3073. */
  3074. #if ENABLE_HUSH_BRACE_EXPANSION
  3075. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3076. * first, it processes even {a} (no commas), second,
  3077. * I didn't manage to make it return strings when they don't match
  3078. * existing files. Need to re-implement it.
  3079. */
  3080. /* Helper */
  3081. static int glob_needed(const char *s)
  3082. {
  3083. while (*s) {
  3084. if (*s == '\\') {
  3085. if (!s[1])
  3086. return 0;
  3087. s += 2;
  3088. continue;
  3089. }
  3090. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3091. return 1;
  3092. s++;
  3093. }
  3094. return 0;
  3095. }
  3096. /* Return pointer to next closing brace or to comma */
  3097. static const char *next_brace_sub(const char *cp)
  3098. {
  3099. unsigned depth = 0;
  3100. cp++;
  3101. while (*cp != '\0') {
  3102. if (*cp == '\\') {
  3103. if (*++cp == '\0')
  3104. break;
  3105. cp++;
  3106. continue;
  3107. }
  3108. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3109. break;
  3110. if (*cp++ == '{')
  3111. depth++;
  3112. }
  3113. return *cp != '\0' ? cp : NULL;
  3114. }
  3115. /* Recursive brace globber. Note: may garble pattern[]. */
  3116. static int glob_brace(char *pattern, o_string *o, int n)
  3117. {
  3118. char *new_pattern_buf;
  3119. const char *begin;
  3120. const char *next;
  3121. const char *rest;
  3122. const char *p;
  3123. size_t rest_len;
  3124. debug_printf_glob("glob_brace('%s')\n", pattern);
  3125. begin = pattern;
  3126. while (1) {
  3127. if (*begin == '\0')
  3128. goto simple_glob;
  3129. if (*begin == '{') {
  3130. /* Find the first sub-pattern and at the same time
  3131. * find the rest after the closing brace */
  3132. next = next_brace_sub(begin);
  3133. if (next == NULL) {
  3134. /* An illegal expression */
  3135. goto simple_glob;
  3136. }
  3137. if (*next == '}') {
  3138. /* "{abc}" with no commas - illegal
  3139. * brace expr, disregard and skip it */
  3140. begin = next + 1;
  3141. continue;
  3142. }
  3143. break;
  3144. }
  3145. if (*begin == '\\' && begin[1] != '\0')
  3146. begin++;
  3147. begin++;
  3148. }
  3149. debug_printf_glob("begin:%s\n", begin);
  3150. debug_printf_glob("next:%s\n", next);
  3151. /* Now find the end of the whole brace expression */
  3152. rest = next;
  3153. while (*rest != '}') {
  3154. rest = next_brace_sub(rest);
  3155. if (rest == NULL) {
  3156. /* An illegal expression */
  3157. goto simple_glob;
  3158. }
  3159. debug_printf_glob("rest:%s\n", rest);
  3160. }
  3161. rest_len = strlen(++rest) + 1;
  3162. /* We are sure the brace expression is well-formed */
  3163. /* Allocate working buffer large enough for our work */
  3164. new_pattern_buf = xmalloc(strlen(pattern));
  3165. /* We have a brace expression. BEGIN points to the opening {,
  3166. * NEXT points past the terminator of the first element, and REST
  3167. * points past the final }. We will accumulate result names from
  3168. * recursive runs for each brace alternative in the buffer using
  3169. * GLOB_APPEND. */
  3170. p = begin + 1;
  3171. while (1) {
  3172. /* Construct the new glob expression */
  3173. memcpy(
  3174. mempcpy(
  3175. mempcpy(new_pattern_buf,
  3176. /* We know the prefix for all sub-patterns */
  3177. pattern, begin - pattern),
  3178. p, next - p),
  3179. rest, rest_len);
  3180. /* Note: glob_brace() may garble new_pattern_buf[].
  3181. * That's why we re-copy prefix every time (1st memcpy above).
  3182. */
  3183. n = glob_brace(new_pattern_buf, o, n);
  3184. if (*next == '}') {
  3185. /* We saw the last entry */
  3186. break;
  3187. }
  3188. p = next + 1;
  3189. next = next_brace_sub(next);
  3190. }
  3191. free(new_pattern_buf);
  3192. return n;
  3193. simple_glob:
  3194. {
  3195. int gr;
  3196. glob_t globdata;
  3197. memset(&globdata, 0, sizeof(globdata));
  3198. gr = glob(pattern, 0, NULL, &globdata);
  3199. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3200. if (gr != 0) {
  3201. if (gr == GLOB_NOMATCH) {
  3202. globfree(&globdata);
  3203. /* NB: garbles parameter */
  3204. unbackslash(pattern);
  3205. o_addstr_with_NUL(o, pattern);
  3206. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3207. return o_save_ptr_helper(o, n);
  3208. }
  3209. if (gr == GLOB_NOSPACE)
  3210. bb_die_memory_exhausted();
  3211. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3212. * but we didn't specify it. Paranoia again. */
  3213. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3214. }
  3215. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3216. char **argv = globdata.gl_pathv;
  3217. while (1) {
  3218. o_addstr_with_NUL(o, *argv);
  3219. n = o_save_ptr_helper(o, n);
  3220. argv++;
  3221. if (!*argv)
  3222. break;
  3223. }
  3224. }
  3225. globfree(&globdata);
  3226. }
  3227. return n;
  3228. }
  3229. /* Performs globbing on last list[],
  3230. * saving each result as a new list[].
  3231. */
  3232. static int perform_glob(o_string *o, int n)
  3233. {
  3234. char *pattern, *copy;
  3235. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3236. if (!o->data)
  3237. return o_save_ptr_helper(o, n);
  3238. pattern = o->data + o_get_last_ptr(o, n);
  3239. debug_printf_glob("glob pattern '%s'\n", pattern);
  3240. if (!glob_needed(pattern)) {
  3241. /* unbackslash last string in o in place, fix length */
  3242. o->length = unbackslash(pattern) - o->data;
  3243. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3244. return o_save_ptr_helper(o, n);
  3245. }
  3246. copy = xstrdup(pattern);
  3247. /* "forget" pattern in o */
  3248. o->length = pattern - o->data;
  3249. n = glob_brace(copy, o, n);
  3250. free(copy);
  3251. if (DEBUG_GLOB)
  3252. debug_print_list("perform_glob returning", o, n);
  3253. return n;
  3254. }
  3255. #else /* !HUSH_BRACE_EXPANSION */
  3256. /* Helper */
  3257. static int glob_needed(const char *s)
  3258. {
  3259. while (*s) {
  3260. if (*s == '\\') {
  3261. if (!s[1])
  3262. return 0;
  3263. s += 2;
  3264. continue;
  3265. }
  3266. if (*s == '*' || *s == '[' || *s == '?')
  3267. return 1;
  3268. s++;
  3269. }
  3270. return 0;
  3271. }
  3272. /* Performs globbing on last list[],
  3273. * saving each result as a new list[].
  3274. */
  3275. static int perform_glob(o_string *o, int n)
  3276. {
  3277. glob_t globdata;
  3278. int gr;
  3279. char *pattern;
  3280. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3281. if (!o->data)
  3282. return o_save_ptr_helper(o, n);
  3283. pattern = o->data + o_get_last_ptr(o, n);
  3284. debug_printf_glob("glob pattern '%s'\n", pattern);
  3285. if (!glob_needed(pattern)) {
  3286. literal:
  3287. /* unbackslash last string in o in place, fix length */
  3288. o->length = unbackslash(pattern) - o->data;
  3289. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3290. return o_save_ptr_helper(o, n);
  3291. }
  3292. memset(&globdata, 0, sizeof(globdata));
  3293. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3294. * If we glob "*.\*" and don't find anything, we need
  3295. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3296. * will return "*.\*"!
  3297. */
  3298. gr = glob(pattern, 0, NULL, &globdata);
  3299. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3300. if (gr != 0) {
  3301. if (gr == GLOB_NOMATCH) {
  3302. globfree(&globdata);
  3303. goto literal;
  3304. }
  3305. if (gr == GLOB_NOSPACE)
  3306. bb_die_memory_exhausted();
  3307. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3308. * but we didn't specify it. Paranoia again. */
  3309. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3310. }
  3311. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3312. char **argv = globdata.gl_pathv;
  3313. /* "forget" pattern in o */
  3314. o->length = pattern - o->data;
  3315. while (1) {
  3316. o_addstr_with_NUL(o, *argv);
  3317. n = o_save_ptr_helper(o, n);
  3318. argv++;
  3319. if (!*argv)
  3320. break;
  3321. }
  3322. }
  3323. globfree(&globdata);
  3324. if (DEBUG_GLOB)
  3325. debug_print_list("perform_glob returning", o, n);
  3326. return n;
  3327. }
  3328. #endif /* !HUSH_BRACE_EXPANSION */
  3329. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3330. * Otherwise, just finish current list[] and start new */
  3331. static int o_save_ptr(o_string *o, int n)
  3332. {
  3333. if (o->o_expflags & EXP_FLAG_GLOB) {
  3334. /* If o->has_empty_slot, list[n] was already globbed
  3335. * (if it was requested back then when it was filled)
  3336. * so don't do that again! */
  3337. if (!o->has_empty_slot)
  3338. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3339. }
  3340. return o_save_ptr_helper(o, n);
  3341. }
  3342. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3343. static char **o_finalize_list(o_string *o, int n)
  3344. {
  3345. char **list;
  3346. int string_start;
  3347. if (DEBUG_EXPAND)
  3348. debug_print_list("finalized", o, n);
  3349. debug_printf_expand("finalized n:%d\n", n);
  3350. list = (char**)o->data;
  3351. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3352. list[--n] = NULL;
  3353. while (n) {
  3354. n--;
  3355. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3356. }
  3357. return list;
  3358. }
  3359. static void free_pipe_list(struct pipe *pi);
  3360. /* Returns pi->next - next pipe in the list */
  3361. static struct pipe *free_pipe(struct pipe *pi)
  3362. {
  3363. struct pipe *next;
  3364. int i;
  3365. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3366. for (i = 0; i < pi->num_cmds; i++) {
  3367. struct command *command;
  3368. struct redir_struct *r, *rnext;
  3369. command = &pi->cmds[i];
  3370. debug_printf_clean(" command %d:\n", i);
  3371. if (command->argv) {
  3372. if (DEBUG_CLEAN) {
  3373. int a;
  3374. char **p;
  3375. for (a = 0, p = command->argv; *p; a++, p++) {
  3376. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3377. }
  3378. }
  3379. free_strings(command->argv);
  3380. //command->argv = NULL;
  3381. }
  3382. /* not "else if": on syntax error, we may have both! */
  3383. if (command->group) {
  3384. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3385. command->cmd_type);
  3386. free_pipe_list(command->group);
  3387. debug_printf_clean(" end group\n");
  3388. //command->group = NULL;
  3389. }
  3390. /* else is crucial here.
  3391. * If group != NULL, child_func is meaningless */
  3392. #if ENABLE_HUSH_FUNCTIONS
  3393. else if (command->child_func) {
  3394. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3395. command->child_func->parent_cmd = NULL;
  3396. }
  3397. #endif
  3398. #if !BB_MMU
  3399. free(command->group_as_string);
  3400. //command->group_as_string = NULL;
  3401. #endif
  3402. for (r = command->redirects; r; r = rnext) {
  3403. debug_printf_clean(" redirect %d%s",
  3404. r->rd_fd, redir_table[r->rd_type].descrip);
  3405. /* guard against the case >$FOO, where foo is unset or blank */
  3406. if (r->rd_filename) {
  3407. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3408. free(r->rd_filename);
  3409. //r->rd_filename = NULL;
  3410. }
  3411. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3412. rnext = r->next;
  3413. free(r);
  3414. }
  3415. //command->redirects = NULL;
  3416. }
  3417. free(pi->cmds); /* children are an array, they get freed all at once */
  3418. //pi->cmds = NULL;
  3419. #if ENABLE_HUSH_JOB
  3420. free(pi->cmdtext);
  3421. //pi->cmdtext = NULL;
  3422. #endif
  3423. next = pi->next;
  3424. free(pi);
  3425. return next;
  3426. }
  3427. static void free_pipe_list(struct pipe *pi)
  3428. {
  3429. while (pi) {
  3430. #if HAS_KEYWORDS
  3431. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3432. #endif
  3433. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3434. pi = free_pipe(pi);
  3435. }
  3436. }
  3437. /*** Parsing routines ***/
  3438. #ifndef debug_print_tree
  3439. static void debug_print_tree(struct pipe *pi, int lvl)
  3440. {
  3441. static const char *const PIPE[] ALIGN_PTR = {
  3442. [PIPE_SEQ] = "SEQ",
  3443. [PIPE_AND] = "AND",
  3444. [PIPE_OR ] = "OR" ,
  3445. [PIPE_BG ] = "BG" ,
  3446. };
  3447. static const char *RES[] = {
  3448. [RES_NONE ] = "NONE" ,
  3449. # if ENABLE_HUSH_IF
  3450. [RES_IF ] = "IF" ,
  3451. [RES_THEN ] = "THEN" ,
  3452. [RES_ELIF ] = "ELIF" ,
  3453. [RES_ELSE ] = "ELSE" ,
  3454. [RES_FI ] = "FI" ,
  3455. # endif
  3456. # if ENABLE_HUSH_LOOPS
  3457. [RES_FOR ] = "FOR" ,
  3458. [RES_WHILE] = "WHILE",
  3459. [RES_UNTIL] = "UNTIL",
  3460. [RES_DO ] = "DO" ,
  3461. [RES_DONE ] = "DONE" ,
  3462. # endif
  3463. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3464. [RES_IN ] = "IN" ,
  3465. # endif
  3466. # if ENABLE_HUSH_CASE
  3467. [RES_CASE ] = "CASE" ,
  3468. [RES_CASE_IN ] = "CASE_IN" ,
  3469. [RES_MATCH] = "MATCH",
  3470. [RES_CASE_BODY] = "CASE_BODY",
  3471. [RES_ESAC ] = "ESAC" ,
  3472. # endif
  3473. [RES_XXXX ] = "XXXX" ,
  3474. [RES_SNTX ] = "SNTX" ,
  3475. };
  3476. static const char *const CMDTYPE[] ALIGN_PTR = {
  3477. "{}",
  3478. "()",
  3479. "[noglob]",
  3480. # if ENABLE_HUSH_FUNCTIONS
  3481. "func()",
  3482. # endif
  3483. };
  3484. int pin, prn;
  3485. pin = 0;
  3486. while (pi) {
  3487. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3488. lvl*2, "",
  3489. pin,
  3490. pi->num_cmds,
  3491. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3492. RES[pi->res_word],
  3493. pi->followup, PIPE[pi->followup]
  3494. );
  3495. prn = 0;
  3496. while (prn < pi->num_cmds) {
  3497. struct command *command = &pi->cmds[prn];
  3498. char **argv = command->argv;
  3499. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3500. lvl*2, "", prn,
  3501. command->assignment_cnt);
  3502. # if ENABLE_HUSH_LINENO_VAR
  3503. fdprintf(2, " LINENO:%u", command->lineno);
  3504. # endif
  3505. if (command->group) {
  3506. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3507. CMDTYPE[command->cmd_type],
  3508. argv
  3509. # if !BB_MMU
  3510. , " group_as_string:", command->group_as_string
  3511. # else
  3512. , "", ""
  3513. # endif
  3514. );
  3515. debug_print_tree(command->group, lvl+1);
  3516. prn++;
  3517. continue;
  3518. }
  3519. if (argv) while (*argv) {
  3520. fdprintf(2, " '%s'", *argv);
  3521. argv++;
  3522. }
  3523. if (command->redirects)
  3524. fdprintf(2, " {redir}");
  3525. fdprintf(2, "\n");
  3526. prn++;
  3527. }
  3528. pi = pi->next;
  3529. pin++;
  3530. }
  3531. }
  3532. #endif /* debug_print_tree */
  3533. static struct pipe *new_pipe(void)
  3534. {
  3535. struct pipe *pi;
  3536. pi = xzalloc(sizeof(struct pipe));
  3537. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3538. return pi;
  3539. }
  3540. /* Command (member of a pipe) is complete, or we start a new pipe
  3541. * if ctx->command is NULL.
  3542. * No errors possible here.
  3543. */
  3544. static int done_command(struct parse_context *ctx)
  3545. {
  3546. /* The command is really already in the pipe structure, so
  3547. * advance the pipe counter and make a new, null command. */
  3548. struct pipe *pi = ctx->pipe;
  3549. struct command *command = ctx->command;
  3550. #if 0 /* Instead we emit error message at run time */
  3551. if (ctx->pending_redirect) {
  3552. /* For example, "cmd >" (no filename to redirect to) */
  3553. syntax_error("invalid redirect");
  3554. ctx->pending_redirect = NULL;
  3555. }
  3556. #endif
  3557. if (command) {
  3558. if (IS_NULL_CMD(command)) {
  3559. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3560. goto clear_and_ret;
  3561. }
  3562. pi->num_cmds++;
  3563. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3564. //debug_print_tree(ctx->list_head, 20);
  3565. } else {
  3566. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3567. }
  3568. /* Only real trickiness here is that the uncommitted
  3569. * command structure is not counted in pi->num_cmds. */
  3570. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3571. ctx->command = command = &pi->cmds[pi->num_cmds];
  3572. clear_and_ret:
  3573. memset(command, 0, sizeof(*command));
  3574. #if ENABLE_HUSH_LINENO_VAR
  3575. command->lineno = G.parse_lineno;
  3576. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3577. #endif
  3578. return pi->num_cmds; /* used only for 0/nonzero check */
  3579. }
  3580. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3581. {
  3582. int not_null;
  3583. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3584. /* Close previous command */
  3585. not_null = done_command(ctx);
  3586. #if HAS_KEYWORDS
  3587. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3588. ctx->ctx_inverted = 0;
  3589. ctx->pipe->res_word = ctx->ctx_res_w;
  3590. #endif
  3591. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3592. /* Necessary since && and || have precedence over &:
  3593. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3594. * in a backgrounded subshell.
  3595. */
  3596. struct pipe *pi;
  3597. struct command *command;
  3598. /* Is this actually this construct, all pipes end with && or ||? */
  3599. pi = ctx->list_head;
  3600. while (pi != ctx->pipe) {
  3601. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3602. goto no_conv;
  3603. pi = pi->next;
  3604. }
  3605. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3606. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3607. pi = xzalloc(sizeof(*pi));
  3608. pi->followup = PIPE_BG;
  3609. pi->num_cmds = 1;
  3610. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3611. command = &pi->cmds[0];
  3612. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3613. command->cmd_type = CMD_NORMAL;
  3614. command->group = ctx->list_head;
  3615. #if !BB_MMU
  3616. command->group_as_string = xstrndup(
  3617. ctx->as_string.data,
  3618. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3619. );
  3620. #endif
  3621. /* Replace all pipes in ctx with one newly created */
  3622. ctx->list_head = ctx->pipe = pi;
  3623. /* for cases like "cmd && &", do not be tricked by last command
  3624. * being null - the entire {...} & is NOT null! */
  3625. not_null = 1;
  3626. } else {
  3627. no_conv:
  3628. ctx->pipe->followup = type;
  3629. }
  3630. /* Without this check, even just <enter> on command line generates
  3631. * tree of three NOPs (!). Which is harmless but annoying.
  3632. * IOW: it is safe to do it unconditionally. */
  3633. if (not_null
  3634. #if ENABLE_HUSH_IF
  3635. || ctx->ctx_res_w == RES_FI
  3636. #endif
  3637. #if ENABLE_HUSH_LOOPS
  3638. || ctx->ctx_res_w == RES_DONE
  3639. || ctx->ctx_res_w == RES_FOR
  3640. || ctx->ctx_res_w == RES_IN
  3641. #endif
  3642. #if ENABLE_HUSH_CASE
  3643. || ctx->ctx_res_w == RES_ESAC
  3644. #endif
  3645. ) {
  3646. struct pipe *new_p;
  3647. debug_printf_parse("done_pipe: adding new pipe: "
  3648. "not_null:%d ctx->ctx_res_w:%d\n",
  3649. not_null, ctx->ctx_res_w);
  3650. new_p = new_pipe();
  3651. ctx->pipe->next = new_p;
  3652. ctx->pipe = new_p;
  3653. /* RES_THEN, RES_DO etc are "sticky" -
  3654. * they remain set for pipes inside if/while.
  3655. * This is used to control execution.
  3656. * RES_FOR and RES_IN are NOT sticky (needed to support
  3657. * cases where variable or value happens to match a keyword):
  3658. */
  3659. #if ENABLE_HUSH_LOOPS
  3660. if (ctx->ctx_res_w == RES_FOR
  3661. || ctx->ctx_res_w == RES_IN)
  3662. ctx->ctx_res_w = RES_NONE;
  3663. #endif
  3664. #if ENABLE_HUSH_CASE
  3665. if (ctx->ctx_res_w == RES_MATCH)
  3666. ctx->ctx_res_w = RES_CASE_BODY;
  3667. if (ctx->ctx_res_w == RES_CASE)
  3668. ctx->ctx_res_w = RES_CASE_IN;
  3669. #endif
  3670. ctx->command = NULL; /* trick done_command below */
  3671. /* Create the memory for command, roughly:
  3672. * ctx->pipe->cmds = new struct command;
  3673. * ctx->command = &ctx->pipe->cmds[0];
  3674. */
  3675. done_command(ctx);
  3676. //debug_print_tree(ctx->list_head, 10);
  3677. }
  3678. debug_printf_parse("done_pipe return\n");
  3679. }
  3680. static void initialize_context(struct parse_context *ctx)
  3681. {
  3682. memset(ctx, 0, sizeof(*ctx));
  3683. if (MAYBE_ASSIGNMENT != 0)
  3684. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3685. ctx->pipe = ctx->list_head = new_pipe();
  3686. /* Create the memory for command, roughly:
  3687. * ctx->pipe->cmds = new struct command;
  3688. * ctx->command = &ctx->pipe->cmds[0];
  3689. */
  3690. done_command(ctx);
  3691. }
  3692. /* If a reserved word is found and processed, parse context is modified
  3693. * and 1 is returned.
  3694. */
  3695. #if HAS_KEYWORDS
  3696. struct reserved_combo {
  3697. char literal[6];
  3698. unsigned char res;
  3699. unsigned char assignment_flag;
  3700. uint32_t flag;
  3701. };
  3702. enum {
  3703. FLAG_END = (1 << RES_NONE ),
  3704. # if ENABLE_HUSH_IF
  3705. FLAG_IF = (1 << RES_IF ),
  3706. FLAG_THEN = (1 << RES_THEN ),
  3707. FLAG_ELIF = (1 << RES_ELIF ),
  3708. FLAG_ELSE = (1 << RES_ELSE ),
  3709. FLAG_FI = (1 << RES_FI ),
  3710. # endif
  3711. # if ENABLE_HUSH_LOOPS
  3712. FLAG_FOR = (1 << RES_FOR ),
  3713. FLAG_WHILE = (1 << RES_WHILE),
  3714. FLAG_UNTIL = (1 << RES_UNTIL),
  3715. FLAG_DO = (1 << RES_DO ),
  3716. FLAG_DONE = (1 << RES_DONE ),
  3717. FLAG_IN = (1 << RES_IN ),
  3718. # endif
  3719. # if ENABLE_HUSH_CASE
  3720. FLAG_MATCH = (1 << RES_MATCH),
  3721. FLAG_ESAC = (1 << RES_ESAC ),
  3722. # endif
  3723. FLAG_START = (1 << RES_XXXX ),
  3724. };
  3725. static const struct reserved_combo* match_reserved_word(o_string *word)
  3726. {
  3727. /* Mostly a list of accepted follow-up reserved words.
  3728. * FLAG_END means we are done with the sequence, and are ready
  3729. * to turn the compound list into a command.
  3730. * FLAG_START means the word must start a new compound list.
  3731. */
  3732. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3733. # if ENABLE_HUSH_IF
  3734. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3735. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3736. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3737. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3738. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3739. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3740. # endif
  3741. # if ENABLE_HUSH_LOOPS
  3742. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3743. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3744. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3745. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3746. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3747. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3748. # endif
  3749. # if ENABLE_HUSH_CASE
  3750. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3751. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3752. # endif
  3753. };
  3754. const struct reserved_combo *r;
  3755. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3756. if (strcmp(word->data, r->literal) == 0)
  3757. return r;
  3758. }
  3759. return NULL;
  3760. }
  3761. /* Return NULL: not a keyword, else: keyword
  3762. */
  3763. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3764. {
  3765. # if ENABLE_HUSH_CASE
  3766. static const struct reserved_combo reserved_match = {
  3767. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3768. };
  3769. # endif
  3770. const struct reserved_combo *r;
  3771. if (ctx->word.has_quoted_part)
  3772. return 0;
  3773. r = match_reserved_word(&ctx->word);
  3774. if (!r)
  3775. return r; /* NULL */
  3776. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3777. # if ENABLE_HUSH_CASE
  3778. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3779. /* "case word IN ..." - IN part starts first MATCH part */
  3780. r = &reserved_match;
  3781. } else
  3782. # endif
  3783. if (r->flag == 0) { /* '!' */
  3784. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3785. syntax_error("! ! command");
  3786. ctx->ctx_res_w = RES_SNTX;
  3787. }
  3788. ctx->ctx_inverted = 1;
  3789. return r;
  3790. }
  3791. if (r->flag & FLAG_START) {
  3792. struct parse_context *old;
  3793. old = xmemdup(ctx, sizeof(*ctx));
  3794. debug_printf_parse("push stack %p\n", old);
  3795. initialize_context(ctx);
  3796. ctx->stack = old;
  3797. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3798. syntax_error_at(ctx->word.data);
  3799. ctx->ctx_res_w = RES_SNTX;
  3800. return r;
  3801. } else {
  3802. /* "{...} fi" is ok. "{...} if" is not
  3803. * Example:
  3804. * if { echo foo; } then { echo bar; } fi */
  3805. if (ctx->command->group)
  3806. done_pipe(ctx, PIPE_SEQ);
  3807. }
  3808. ctx->ctx_res_w = r->res;
  3809. ctx->old_flag = r->flag;
  3810. ctx->is_assignment = r->assignment_flag;
  3811. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3812. if (ctx->old_flag & FLAG_END) {
  3813. struct parse_context *old;
  3814. done_pipe(ctx, PIPE_SEQ);
  3815. debug_printf_parse("pop stack %p\n", ctx->stack);
  3816. old = ctx->stack;
  3817. old->command->group = ctx->list_head;
  3818. old->command->cmd_type = CMD_NORMAL;
  3819. # if !BB_MMU
  3820. /* At this point, the compound command's string is in
  3821. * ctx->as_string... except for the leading keyword!
  3822. * Consider this example: "echo a | if true; then echo a; fi"
  3823. * ctx->as_string will contain "true; then echo a; fi",
  3824. * with "if " remaining in old->as_string!
  3825. */
  3826. {
  3827. char *str;
  3828. int len = old->as_string.length;
  3829. /* Concatenate halves */
  3830. o_addstr(&old->as_string, ctx->as_string.data);
  3831. o_free(&ctx->as_string);
  3832. /* Find where leading keyword starts in first half */
  3833. str = old->as_string.data + len;
  3834. if (str > old->as_string.data)
  3835. str--; /* skip whitespace after keyword */
  3836. while (str > old->as_string.data && isalpha(str[-1]))
  3837. str--;
  3838. /* Ugh, we're done with this horrid hack */
  3839. old->command->group_as_string = xstrdup(str);
  3840. debug_printf_parse("pop, remembering as:'%s'\n",
  3841. old->command->group_as_string);
  3842. }
  3843. # endif
  3844. *ctx = *old; /* physical copy */
  3845. free(old);
  3846. }
  3847. return r;
  3848. }
  3849. #endif /* HAS_KEYWORDS */
  3850. /* Word is complete, look at it and update parsing context.
  3851. * Normal return is 0. Syntax errors return 1.
  3852. * Note: on return, word is reset, but not o_free'd!
  3853. */
  3854. static int done_word(struct parse_context *ctx)
  3855. {
  3856. struct command *command = ctx->command;
  3857. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3858. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3859. debug_printf_parse("done_word return 0: true null, ignored\n");
  3860. return 0;
  3861. }
  3862. if (ctx->pending_redirect) {
  3863. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3864. * only if run as "bash", not "sh" */
  3865. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3866. * "2.7 Redirection
  3867. * If the redirection operator is "<<" or "<<-", the word
  3868. * that follows the redirection operator shall be
  3869. * subjected to quote removal; it is unspecified whether
  3870. * any of the other expansions occur. For the other
  3871. * redirection operators, the word that follows the
  3872. * redirection operator shall be subjected to tilde
  3873. * expansion, parameter expansion, command substitution,
  3874. * arithmetic expansion, and quote removal.
  3875. * Pathname expansion shall not be performed
  3876. * on the word by a non-interactive shell; an interactive
  3877. * shell may perform it, but shall do so only when
  3878. * the expansion would result in one word."
  3879. */
  3880. //bash does not do parameter/command substitution or arithmetic expansion
  3881. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3882. // as written:
  3883. // <<EOF$t
  3884. // <<EOF$((1))
  3885. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3886. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3887. /* Cater for >\file case:
  3888. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3889. * Same with heredocs:
  3890. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3891. */
  3892. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3893. unbackslash(ctx->pending_redirect->rd_filename);
  3894. /* Is it <<"HEREDOC"? */
  3895. if (ctx->word.has_quoted_part) {
  3896. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3897. }
  3898. }
  3899. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3900. ctx->pending_redirect = NULL;
  3901. } else {
  3902. #if HAS_KEYWORDS
  3903. # if ENABLE_HUSH_CASE
  3904. if (ctx->ctx_dsemicolon
  3905. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3906. ) {
  3907. /* already done when ctx_dsemicolon was set to 1: */
  3908. /* ctx->ctx_res_w = RES_MATCH; */
  3909. ctx->ctx_dsemicolon = 0;
  3910. } else
  3911. # endif
  3912. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3913. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3914. && strcmp(ctx->word.data, "]]") == 0
  3915. ) {
  3916. /* allow "[[ ]] >file" etc */
  3917. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3918. } else
  3919. # endif
  3920. if (!command->argv /* if it's the first word... */
  3921. # if ENABLE_HUSH_LOOPS
  3922. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3923. && ctx->ctx_res_w != RES_IN
  3924. # endif
  3925. # if ENABLE_HUSH_CASE
  3926. && ctx->ctx_res_w != RES_CASE
  3927. # endif
  3928. ) {
  3929. const struct reserved_combo *reserved;
  3930. reserved = reserved_word(ctx);
  3931. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3932. if (reserved) {
  3933. # if ENABLE_HUSH_LINENO_VAR
  3934. /* Case:
  3935. * "while ...; do
  3936. * cmd ..."
  3937. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3938. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3939. */
  3940. if (0
  3941. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3942. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3943. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3944. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3945. ) {
  3946. done_pipe(ctx, PIPE_SEQ);
  3947. }
  3948. # endif
  3949. o_reset_to_empty_unquoted(&ctx->word);
  3950. debug_printf_parse("done_word return %d\n",
  3951. (ctx->ctx_res_w == RES_SNTX));
  3952. return (ctx->ctx_res_w == RES_SNTX);
  3953. }
  3954. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3955. if (strcmp(ctx->word.data, "[[") == 0) {
  3956. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3957. } else
  3958. # endif
  3959. # if defined(CMD_SINGLEWORD_NOGLOB)
  3960. if (0
  3961. /* In bash, local/export/readonly are special, args
  3962. * are assignments and therefore expansion of them
  3963. * should be "one-word" expansion:
  3964. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3965. * compare with:
  3966. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3967. * ls: cannot access i=a: No such file or directory
  3968. * ls: cannot access b: No such file or directory
  3969. * Note: bash 3.2.33(1) does this only if export word
  3970. * itself is not quoted:
  3971. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3972. * aaa bbb
  3973. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3974. * aaa
  3975. */
  3976. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3977. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3978. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3979. ) {
  3980. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3981. }
  3982. # else
  3983. { /* empty block to pair "if ... else" */ }
  3984. # endif
  3985. }
  3986. #endif /* HAS_KEYWORDS */
  3987. if (command->group) {
  3988. /* "{ echo foo; } echo bar" - bad */
  3989. syntax_error_at(ctx->word.data);
  3990. debug_printf_parse("done_word return 1: syntax error, "
  3991. "groups and arglists don't mix\n");
  3992. return 1;
  3993. }
  3994. /* If this word wasn't an assignment, next ones definitely
  3995. * can't be assignments. Even if they look like ones. */
  3996. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3997. && ctx->is_assignment != WORD_IS_KEYWORD
  3998. ) {
  3999. ctx->is_assignment = NOT_ASSIGNMENT;
  4000. } else {
  4001. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  4002. command->assignment_cnt++;
  4003. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  4004. }
  4005. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  4006. ctx->is_assignment = MAYBE_ASSIGNMENT;
  4007. }
  4008. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  4009. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  4010. debug_print_strings("word appended to argv", command->argv);
  4011. }
  4012. #if ENABLE_HUSH_LOOPS
  4013. if (ctx->ctx_res_w == RES_FOR) {
  4014. if (ctx->word.has_quoted_part
  4015. || endofname(command->argv[0])[0] != '\0'
  4016. ) {
  4017. /* bash says just "not a valid identifier" */
  4018. syntax_error("bad variable name in for");
  4019. return 1;
  4020. }
  4021. /* Force FOR to have just one word (variable name) */
  4022. /* NB: basically, this makes hush see "for v in ..."
  4023. * syntax as if it is "for v; in ...". FOR and IN become
  4024. * two pipe structs in parse tree. */
  4025. done_pipe(ctx, PIPE_SEQ);
  4026. }
  4027. #endif
  4028. #if ENABLE_HUSH_CASE
  4029. /* Force CASE to have just one word */
  4030. if (ctx->ctx_res_w == RES_CASE) {
  4031. done_pipe(ctx, PIPE_SEQ);
  4032. }
  4033. #endif
  4034. o_reset_to_empty_unquoted(&ctx->word);
  4035. debug_printf_parse("done_word return 0\n");
  4036. return 0;
  4037. }
  4038. /* Peek ahead in the input to find out if we have a "&n" construct,
  4039. * as in "2>&1", that represents duplicating a file descriptor.
  4040. * Return:
  4041. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4042. * REDIRFD_SYNTAX_ERR if syntax error,
  4043. * REDIRFD_TO_FILE if no & was seen,
  4044. * or the number found.
  4045. */
  4046. #if BB_MMU
  4047. #define parse_redir_right_fd(as_string, input) \
  4048. parse_redir_right_fd(input)
  4049. #endif
  4050. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4051. {
  4052. int ch, d, ok;
  4053. ch = i_peek(input);
  4054. if (ch != '&')
  4055. return REDIRFD_TO_FILE;
  4056. ch = i_getch(input); /* get the & */
  4057. nommu_addchr(as_string, ch);
  4058. ch = i_peek(input);
  4059. if (ch == '-') {
  4060. ch = i_getch(input);
  4061. nommu_addchr(as_string, ch);
  4062. return REDIRFD_CLOSE;
  4063. }
  4064. d = 0;
  4065. ok = 0;
  4066. while (ch != EOF && isdigit(ch)) {
  4067. d = d*10 + (ch-'0');
  4068. ok = 1;
  4069. ch = i_getch(input);
  4070. nommu_addchr(as_string, ch);
  4071. ch = i_peek(input);
  4072. }
  4073. if (ok) return d;
  4074. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4075. bb_simple_error_msg("ambiguous redirect");
  4076. return REDIRFD_SYNTAX_ERR;
  4077. }
  4078. /* Return code is 0 normal, 1 if a syntax error is detected
  4079. */
  4080. static int parse_redirect(struct parse_context *ctx,
  4081. int fd,
  4082. redir_type style,
  4083. struct in_str *input)
  4084. {
  4085. struct command *command = ctx->command;
  4086. struct redir_struct *redir;
  4087. struct redir_struct **redirp;
  4088. int dup_num;
  4089. dup_num = REDIRFD_TO_FILE;
  4090. if (style != REDIRECT_HEREDOC) {
  4091. /* Check for a '>&1' type redirect */
  4092. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4093. if (dup_num == REDIRFD_SYNTAX_ERR)
  4094. return 1;
  4095. } else {
  4096. int ch = i_peek_and_eat_bkslash_nl(input);
  4097. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4098. if (dup_num) { /* <<-... */
  4099. ch = i_getch(input);
  4100. nommu_addchr(&ctx->as_string, ch);
  4101. ch = i_peek(input);
  4102. }
  4103. }
  4104. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4105. int ch = i_peek_and_eat_bkslash_nl(input);
  4106. if (ch == '|') {
  4107. /* >|FILE redirect ("clobbering" >).
  4108. * Since we do not support "set -o noclobber" yet,
  4109. * >| and > are the same for now. Just eat |.
  4110. */
  4111. ch = i_getch(input);
  4112. nommu_addchr(&ctx->as_string, ch);
  4113. }
  4114. }
  4115. /* Create a new redir_struct and append it to the linked list */
  4116. redirp = &command->redirects;
  4117. while ((redir = *redirp) != NULL) {
  4118. redirp = &(redir->next);
  4119. }
  4120. *redirp = redir = xzalloc(sizeof(*redir));
  4121. /* redir->next = NULL; */
  4122. /* redir->rd_filename = NULL; */
  4123. redir->rd_type = style;
  4124. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4125. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4126. redir_table[style].descrip);
  4127. redir->rd_dup = dup_num;
  4128. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4129. /* Erik had a check here that the file descriptor in question
  4130. * is legit; I postpone that to "run time"
  4131. * A "-" representation of "close me" shows up as a -3 here */
  4132. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4133. redir->rd_fd, redir->rd_dup);
  4134. } else {
  4135. #if 0 /* Instead we emit error message at run time */
  4136. if (ctx->pending_redirect) {
  4137. /* For example, "cmd > <file" */
  4138. syntax_error("invalid redirect");
  4139. }
  4140. #endif
  4141. /* Set ctx->pending_redirect, so we know what to do at the
  4142. * end of the next parsed word. */
  4143. ctx->pending_redirect = redir;
  4144. }
  4145. return 0;
  4146. }
  4147. /* If a redirect is immediately preceded by a number, that number is
  4148. * supposed to tell which file descriptor to redirect. This routine
  4149. * looks for such preceding numbers. In an ideal world this routine
  4150. * needs to handle all the following classes of redirects...
  4151. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4152. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4153. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4154. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4155. *
  4156. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4157. * "2.7 Redirection
  4158. * ... If n is quoted, the number shall not be recognized as part of
  4159. * the redirection expression. For example:
  4160. * echo \2>a
  4161. * writes the character 2 into file a"
  4162. * We are getting it right by setting ->has_quoted_part on any \<char>
  4163. *
  4164. * A -1 return means no valid number was found,
  4165. * the caller should use the appropriate default for this redirection.
  4166. */
  4167. static int redirect_opt_num(o_string *o)
  4168. {
  4169. int num;
  4170. if (o->data == NULL)
  4171. return -1;
  4172. num = bb_strtou(o->data, NULL, 10);
  4173. if (errno || num < 0)
  4174. return -1;
  4175. o_reset_to_empty_unquoted(o);
  4176. return num;
  4177. }
  4178. #if BB_MMU
  4179. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4180. fetch_till_str(input, word, skip_tabs)
  4181. #endif
  4182. static char *fetch_till_str(o_string *as_string,
  4183. struct in_str *input,
  4184. const char *word,
  4185. int heredoc_flags)
  4186. {
  4187. o_string heredoc = NULL_O_STRING;
  4188. unsigned past_EOL;
  4189. int prev = 0; /* not \ */
  4190. int ch;
  4191. /* Starting with "" is necessary for this case:
  4192. * cat <<EOF
  4193. *
  4194. * xxx
  4195. * EOF
  4196. */
  4197. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4198. goto jump_in;
  4199. while (1) {
  4200. ch = i_getch(input);
  4201. if (ch != EOF)
  4202. nommu_addchr(as_string, ch);
  4203. if (ch == '\n' || ch == EOF) {
  4204. check_heredoc_end:
  4205. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4206. /* End-of-line, and not a line continuation */
  4207. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4208. heredoc.data[past_EOL] = '\0';
  4209. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4210. return heredoc.data;
  4211. }
  4212. if (ch == '\n') {
  4213. /* This is a new line.
  4214. * Remember position and backslash-escaping status.
  4215. */
  4216. o_addchr(&heredoc, ch);
  4217. prev = ch;
  4218. jump_in:
  4219. past_EOL = heredoc.length;
  4220. /* Get 1st char of next line, possibly skipping leading tabs */
  4221. do {
  4222. ch = i_getch(input);
  4223. if (ch != EOF)
  4224. nommu_addchr(as_string, ch);
  4225. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4226. /* If this immediately ended the line,
  4227. * go back to end-of-line checks.
  4228. */
  4229. if (ch == '\n')
  4230. goto check_heredoc_end;
  4231. }
  4232. } else {
  4233. /* Backslash-line continuation in an unquoted
  4234. * heredoc. This does not need special handling
  4235. * for heredoc body (unquoted heredocs are
  4236. * expanded on "execution" and that would take
  4237. * care of this case too), but not the case
  4238. * of line continuation *in terminator*:
  4239. * cat <<EOF
  4240. * Ok1
  4241. * EO\
  4242. * F
  4243. */
  4244. heredoc.data[--heredoc.length] = '\0';
  4245. prev = 0; /* not '\' */
  4246. continue;
  4247. }
  4248. }
  4249. if (ch == EOF) {
  4250. o_free(&heredoc);
  4251. return NULL; /* error */
  4252. }
  4253. o_addchr(&heredoc, ch);
  4254. nommu_addchr(as_string, ch);
  4255. if (prev == '\\' && ch == '\\')
  4256. /* Correctly handle foo\\<eol> (not a line cont.) */
  4257. prev = 0; /* not '\' */
  4258. else
  4259. prev = ch;
  4260. }
  4261. }
  4262. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4263. * and load them all. There should be exactly heredoc_cnt of them.
  4264. */
  4265. #if BB_MMU
  4266. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4267. fetch_heredocs(pi, heredoc_cnt, input)
  4268. #endif
  4269. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4270. {
  4271. while (pi && heredoc_cnt) {
  4272. int i;
  4273. struct command *cmd = pi->cmds;
  4274. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4275. pi->num_cmds,
  4276. cmd->argv ? cmd->argv[0] : "NONE"
  4277. );
  4278. for (i = 0; i < pi->num_cmds; i++) {
  4279. struct redir_struct *redir = cmd->redirects;
  4280. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4281. i, cmd->argv ? cmd->argv[0] : "NONE");
  4282. while (redir) {
  4283. if (redir->rd_type == REDIRECT_HEREDOC) {
  4284. char *p;
  4285. redir->rd_type = REDIRECT_HEREDOC2;
  4286. /* redir->rd_dup is (ab)used to indicate <<- */
  4287. p = fetch_till_str(as_string, input,
  4288. redir->rd_filename, redir->rd_dup);
  4289. if (!p) {
  4290. syntax_error("unexpected EOF in here document");
  4291. return -1;
  4292. }
  4293. free(redir->rd_filename);
  4294. redir->rd_filename = p;
  4295. heredoc_cnt--;
  4296. }
  4297. redir = redir->next;
  4298. }
  4299. if (cmd->group) {
  4300. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4301. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4302. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4303. if (heredoc_cnt < 0)
  4304. return heredoc_cnt; /* error */
  4305. }
  4306. cmd++;
  4307. }
  4308. pi = pi->next;
  4309. }
  4310. return heredoc_cnt;
  4311. }
  4312. static int run_list(struct pipe *pi);
  4313. #if BB_MMU
  4314. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4315. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4316. #endif
  4317. static struct pipe *parse_stream(char **pstring,
  4318. int *heredoc_cnt_ptr,
  4319. struct in_str *input,
  4320. int end_trigger);
  4321. /* Returns number of heredocs not yet consumed,
  4322. * or -1 on error.
  4323. */
  4324. static int parse_group(struct parse_context *ctx,
  4325. struct in_str *input, int ch)
  4326. {
  4327. /* ctx->word contains characters seen prior to ( or {.
  4328. * Typically it's empty, but for function defs,
  4329. * it contains function name (without '()'). */
  4330. #if BB_MMU
  4331. # define as_string NULL
  4332. #else
  4333. char *as_string = NULL;
  4334. #endif
  4335. struct pipe *pipe_list;
  4336. int heredoc_cnt = 0;
  4337. int endch;
  4338. struct command *command = ctx->command;
  4339. debug_printf_parse("parse_group entered\n");
  4340. #if ENABLE_HUSH_FUNCTIONS
  4341. if (ch == '(' && !ctx->word.has_quoted_part) {
  4342. if (ctx->word.length)
  4343. if (done_word(ctx))
  4344. return -1;
  4345. if (!command->argv)
  4346. goto skip; /* (... */
  4347. if (command->argv[1]) { /* word word ... (... */
  4348. syntax_error_unexpected_ch('(');
  4349. return -1;
  4350. }
  4351. /* it is "word(..." or "word (..." */
  4352. do
  4353. ch = i_getch(input);
  4354. while (ch == ' ' || ch == '\t');
  4355. if (ch != ')') {
  4356. syntax_error_unexpected_ch(ch);
  4357. return -1;
  4358. }
  4359. nommu_addchr(&ctx->as_string, ch);
  4360. do
  4361. ch = i_getch(input);
  4362. while (ch == ' ' || ch == '\t' || ch == '\n');
  4363. if (ch != '{' && ch != '(') {
  4364. syntax_error_unexpected_ch(ch);
  4365. return -1;
  4366. }
  4367. nommu_addchr(&ctx->as_string, ch);
  4368. command->cmd_type = CMD_FUNCDEF;
  4369. goto skip;
  4370. }
  4371. #endif
  4372. #if 0 /* Prevented by caller */
  4373. if (command->argv /* word [word]{... */
  4374. || ctx->word.length /* word{... */
  4375. || ctx->word.has_quoted_part /* ""{... */
  4376. ) {
  4377. syntax_error(NULL);
  4378. debug_printf_parse("parse_group return -1: "
  4379. "syntax error, groups and arglists don't mix\n");
  4380. return -1;
  4381. }
  4382. #endif
  4383. IF_HUSH_FUNCTIONS(skip:)
  4384. endch = '}';
  4385. if (ch == '(') {
  4386. endch = ')';
  4387. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4388. command->cmd_type = CMD_SUBSHELL;
  4389. } else {
  4390. /* bash does not allow "{echo...", requires whitespace */
  4391. ch = i_peek(input);
  4392. if (ch != ' ' && ch != '\t' && ch != '\n'
  4393. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4394. ) {
  4395. syntax_error_unexpected_ch(ch);
  4396. return -1;
  4397. }
  4398. if (ch != '(') {
  4399. ch = i_getch(input);
  4400. nommu_addchr(&ctx->as_string, ch);
  4401. }
  4402. }
  4403. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4404. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4405. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4406. #if !BB_MMU
  4407. if (as_string)
  4408. o_addstr(&ctx->as_string, as_string);
  4409. #endif
  4410. /* empty ()/{} or parse error? */
  4411. if (!pipe_list || pipe_list == ERR_PTR) {
  4412. /* parse_stream already emitted error msg */
  4413. if (!BB_MMU)
  4414. free(as_string);
  4415. debug_printf_parse("parse_group return -1: "
  4416. "parse_stream returned %p\n", pipe_list);
  4417. return -1;
  4418. }
  4419. #if !BB_MMU
  4420. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4421. command->group_as_string = as_string;
  4422. debug_printf_parse("end of group, remembering as:'%s'\n",
  4423. command->group_as_string);
  4424. #endif
  4425. #if ENABLE_HUSH_FUNCTIONS
  4426. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4427. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4428. struct command *cmd2;
  4429. cmd2 = xzalloc(sizeof(*cmd2));
  4430. cmd2->cmd_type = CMD_SUBSHELL;
  4431. cmd2->group = pipe_list;
  4432. # if !BB_MMU
  4433. //UNTESTED!
  4434. cmd2->group_as_string = command->group_as_string;
  4435. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4436. # endif
  4437. pipe_list = new_pipe();
  4438. pipe_list->cmds = cmd2;
  4439. pipe_list->num_cmds = 1;
  4440. }
  4441. #endif
  4442. command->group = pipe_list;
  4443. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4444. return heredoc_cnt;
  4445. /* command remains "open", available for possible redirects */
  4446. #undef as_string
  4447. }
  4448. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4449. /* Subroutines for copying $(...) and `...` things */
  4450. /* '...' */
  4451. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4452. {
  4453. while (1) {
  4454. int ch = i_getch(input);
  4455. if (ch == EOF) {
  4456. syntax_error_unterm_ch('\'');
  4457. return 0;
  4458. }
  4459. if (ch == '\'')
  4460. return 1;
  4461. o_addchr(dest, ch);
  4462. }
  4463. }
  4464. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4465. {
  4466. while (1) {
  4467. int ch = i_getch(input);
  4468. if (ch == EOF) {
  4469. syntax_error_unterm_ch('\'');
  4470. return 0;
  4471. }
  4472. if (ch == '\'')
  4473. return 1;
  4474. o_addqchr(dest, ch);
  4475. }
  4476. }
  4477. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4478. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4479. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4480. {
  4481. while (1) {
  4482. int ch = i_getch(input);
  4483. if (ch == EOF) {
  4484. syntax_error_unterm_ch('"');
  4485. return 0;
  4486. }
  4487. if (ch == '"')
  4488. return 1;
  4489. if (ch == '\\') { /* \x. Copy both chars. */
  4490. o_addchr(dest, ch);
  4491. ch = i_getch(input);
  4492. }
  4493. o_addchr(dest, ch);
  4494. if (ch == '`') {
  4495. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4496. return 0;
  4497. o_addchr(dest, ch);
  4498. continue;
  4499. }
  4500. //if (ch == '$') ...
  4501. }
  4502. }
  4503. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4504. * \` quoting.
  4505. * "Within the backquoted style of command substitution, backslash
  4506. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4507. * The search for the matching backquote shall be satisfied by the first
  4508. * backquote found without a preceding backslash; during this search,
  4509. * if a non-escaped backquote is encountered within a shell comment,
  4510. * a here-document, an embedded command substitution of the $(command)
  4511. * form, or a quoted string, undefined results occur. A single-quoted
  4512. * or double-quoted string that begins, but does not end, within the
  4513. * "`...`" sequence produces undefined results."
  4514. * Example Output
  4515. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4516. */
  4517. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4518. {
  4519. while (1) {
  4520. int ch = i_getch(input);
  4521. if (ch == '`')
  4522. return 1;
  4523. if (ch == '\\') {
  4524. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4525. ch = i_getch(input);
  4526. if (ch != '`'
  4527. && ch != '$'
  4528. && ch != '\\'
  4529. && (!in_dquote || ch != '"')
  4530. ) {
  4531. o_addchr(dest, '\\');
  4532. }
  4533. }
  4534. if (ch == EOF) {
  4535. syntax_error_unterm_ch('`');
  4536. return 0;
  4537. }
  4538. o_addchr(dest, ch);
  4539. }
  4540. }
  4541. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4542. * quoting and nested ()s.
  4543. * "With the $(command) style of command substitution, all characters
  4544. * following the open parenthesis to the matching closing parenthesis
  4545. * constitute the command. Any valid shell script can be used for command,
  4546. * except a script consisting solely of redirections which produces
  4547. * unspecified results."
  4548. * Example Output
  4549. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4550. * echo $(echo 'TEST)' BEST) TEST) BEST
  4551. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4552. *
  4553. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4554. * can contain arbitrary constructs, just like $(cmd).
  4555. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4556. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4557. */
  4558. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4559. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4560. {
  4561. int ch;
  4562. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4563. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4564. char end_char2 = end_ch >> 8;
  4565. # endif
  4566. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4567. # if ENABLE_HUSH_INTERACTIVE
  4568. G.promptmode = 1; /* PS2 */
  4569. # endif
  4570. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4571. while (1) {
  4572. ch = i_getch(input);
  4573. if (ch == EOF) {
  4574. syntax_error_unterm_ch(end_ch);
  4575. return 0;
  4576. }
  4577. if (ch == end_ch
  4578. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4579. || ch == end_char2
  4580. # endif
  4581. ) {
  4582. if (!dbl)
  4583. break;
  4584. /* we look for closing )) of $((EXPR)) */
  4585. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4586. i_getch(input); /* eat second ')' */
  4587. break;
  4588. }
  4589. }
  4590. o_addchr(dest, ch);
  4591. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4592. if (ch == '(' || ch == '{') {
  4593. ch = (ch == '(' ? ')' : '}');
  4594. if (!add_till_closing_bracket(dest, input, ch))
  4595. return 0;
  4596. o_addchr(dest, ch);
  4597. continue;
  4598. }
  4599. if (ch == '\'') {
  4600. if (!add_till_single_quote(dest, input))
  4601. return 0;
  4602. o_addchr(dest, ch);
  4603. continue;
  4604. }
  4605. if (ch == '"') {
  4606. if (!add_till_double_quote(dest, input))
  4607. return 0;
  4608. o_addchr(dest, ch);
  4609. continue;
  4610. }
  4611. if (ch == '`') {
  4612. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4613. return 0;
  4614. o_addchr(dest, ch);
  4615. continue;
  4616. }
  4617. if (ch == '\\') {
  4618. /* \x. Copy verbatim. Important for \(, \) */
  4619. ch = i_getch(input);
  4620. if (ch == EOF) {
  4621. syntax_error_unterm_ch(end_ch);
  4622. return 0;
  4623. }
  4624. # if 0
  4625. if (ch == '\n') {
  4626. /* "backslash+newline", ignore both */
  4627. o_delchr(dest); /* undo insertion of '\' */
  4628. continue;
  4629. }
  4630. # endif
  4631. o_addchr(dest, ch);
  4632. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4633. continue;
  4634. }
  4635. }
  4636. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4637. return ch;
  4638. }
  4639. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4640. #if BASH_DOLLAR_SQUOTE
  4641. /* Return code: 1 for "found and parsed", 0 for "seen something else" */
  4642. # if BB_MMU
  4643. #define parse_dollar_squote(as_string, dest, input) \
  4644. parse_dollar_squote(dest, input)
  4645. #define as_string NULL
  4646. # endif
  4647. static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
  4648. {
  4649. int start;
  4650. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4651. debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
  4652. if (ch != '\'')
  4653. return 0;
  4654. dest->has_quoted_part = 1;
  4655. start = dest->length;
  4656. ch = i_getch(input); /* eat ' */
  4657. nommu_addchr(as_string, ch);
  4658. while (1) {
  4659. ch = i_getch(input);
  4660. nommu_addchr(as_string, ch);
  4661. if (ch == EOF) {
  4662. syntax_error_unterm_ch('\'');
  4663. return 0;
  4664. }
  4665. if (ch == '\'')
  4666. break;
  4667. if (ch == SPECIAL_VAR_SYMBOL) {
  4668. /* Convert raw ^C to corresponding special variable reference */
  4669. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4670. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4671. /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
  4672. } else if (ch == '\\') {
  4673. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  4674. ch = i_getch(input);
  4675. nommu_addchr(as_string, ch);
  4676. if (strchr(C_escapes, ch)) {
  4677. char buf[4];
  4678. char *p = buf;
  4679. int cnt = 2;
  4680. buf[0] = ch;
  4681. if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
  4682. do {
  4683. ch = i_peek(input);
  4684. if ((unsigned char)(ch - '0') > 7)
  4685. break;
  4686. *++p = ch = i_getch(input);
  4687. nommu_addchr(as_string, ch);
  4688. } while (--cnt != 0);
  4689. } else if (ch == 'x') { /* \xHH */
  4690. do {
  4691. ch = i_peek(input);
  4692. if (!isxdigit(ch))
  4693. break;
  4694. *++p = ch = i_getch(input);
  4695. nommu_addchr(as_string, ch);
  4696. } while (--cnt != 0);
  4697. if (cnt == 2) { /* \x but next char is "bad" */
  4698. ch = 'x';
  4699. goto unrecognized;
  4700. }
  4701. } /* else simple seq like \\ or \t */
  4702. *++p = '\0';
  4703. p = buf;
  4704. ch = bb_process_escape_sequence((void*)&p);
  4705. //bb_error_msg("buf:'%s' ch:%x", buf, ch);
  4706. if (ch == '\0')
  4707. continue; /* bash compat: $'...\0...' emits nothing */
  4708. } else { /* unrecognized "\z": encode both chars unless ' or " */
  4709. if (ch != '\'' && ch != '"') {
  4710. unrecognized:
  4711. o_addqchr(dest, '\\');
  4712. }
  4713. }
  4714. } /* if (\...) */
  4715. o_addqchr(dest, ch);
  4716. }
  4717. if (dest->length == start) {
  4718. /* $'', $'\0', $'\000\x00' and the like */
  4719. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4720. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4721. }
  4722. return 1;
  4723. # undef as_string
  4724. }
  4725. #else
  4726. # define parse_dollar_squote(as_string, dest, input) 0
  4727. #endif /* BASH_DOLLAR_SQUOTE */
  4728. /* Return code: 0 for OK, 1 for syntax error */
  4729. #if BB_MMU
  4730. #define parse_dollar(as_string, dest, input, quote_mask) \
  4731. parse_dollar(dest, input, quote_mask)
  4732. #define as_string NULL
  4733. #endif
  4734. static int parse_dollar(o_string *as_string,
  4735. o_string *dest,
  4736. struct in_str *input, unsigned char quote_mask)
  4737. {
  4738. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4739. debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
  4740. if (isalpha(ch)) {
  4741. make_var:
  4742. ch = i_getch(input);
  4743. nommu_addchr(as_string, ch);
  4744. /*make_var1:*/
  4745. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4746. while (1) {
  4747. debug_printf_parse(": '%c'\n", ch);
  4748. o_addchr(dest, ch | quote_mask);
  4749. quote_mask = 0;
  4750. ch = i_peek_and_eat_bkslash_nl(input);
  4751. if (!isalnum(ch) && ch != '_') {
  4752. /* End of variable name reached */
  4753. break;
  4754. }
  4755. ch = i_getch(input);
  4756. nommu_addchr(as_string, ch);
  4757. }
  4758. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4759. } else if (isdigit(ch)) {
  4760. make_one_char_var:
  4761. ch = i_getch(input);
  4762. nommu_addchr(as_string, ch);
  4763. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4764. debug_printf_parse(": '%c'\n", ch);
  4765. o_addchr(dest, ch | quote_mask);
  4766. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4767. } else switch (ch) {
  4768. case '$': /* pid */
  4769. case '!': /* last bg pid */
  4770. case '?': /* last exit code */
  4771. case '#': /* number of args */
  4772. case '*': /* args */
  4773. case '@': /* args */
  4774. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4775. goto make_one_char_var;
  4776. case '{': {
  4777. char len_single_ch;
  4778. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4779. ch = i_getch(input); /* eat '{' */
  4780. nommu_addchr(as_string, ch);
  4781. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4782. /* It should be ${?}, or ${#var},
  4783. * or even ${?+subst} - operator acting on a special variable,
  4784. * or the beginning of variable name.
  4785. */
  4786. if (ch == EOF
  4787. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4788. ) {
  4789. bad_dollar_syntax:
  4790. syntax_error_unterm_str("${name}");
  4791. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4792. return 0;
  4793. }
  4794. nommu_addchr(as_string, ch);
  4795. len_single_ch = ch;
  4796. ch |= quote_mask;
  4797. /* It's possible to just call add_till_closing_bracket() at this point.
  4798. * However, this regresses some of our testsuite cases
  4799. * which check invalid constructs like ${%}.
  4800. * Oh well... let's check that the var name part is fine... */
  4801. if (isdigit(len_single_ch)
  4802. || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
  4803. ) {
  4804. /* Execution engine uses plain xatoi_positive()
  4805. * to interpret ${NNN} and {#NNN},
  4806. * check syntax here in the parser.
  4807. * (bash does not support expressions in ${#NN},
  4808. * e.g. ${#$var} and {#1:+WORD} are not supported).
  4809. */
  4810. unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
  4811. while (1) {
  4812. o_addchr(dest, ch);
  4813. debug_printf_parse(": '%c'\n", ch);
  4814. ch = i_getch_and_eat_bkslash_nl(input);
  4815. nommu_addchr(as_string, ch);
  4816. if (ch == '}')
  4817. break;
  4818. if (--cnt == 0)
  4819. goto bad_dollar_syntax;
  4820. if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
  4821. /* ${NN<op>...} is valid */
  4822. goto eat_until_closing;
  4823. if (!isdigit(ch))
  4824. goto bad_dollar_syntax;
  4825. }
  4826. } else
  4827. while (1) {
  4828. unsigned pos;
  4829. o_addchr(dest, ch);
  4830. debug_printf_parse(": '%c'\n", ch);
  4831. ch = i_getch(input);
  4832. nommu_addchr(as_string, ch);
  4833. if (ch == '}')
  4834. break;
  4835. if (!isalnum(ch) && ch != '_') {
  4836. unsigned end_ch;
  4837. unsigned char last_ch;
  4838. /* handle parameter expansions
  4839. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4840. */
  4841. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4842. if (len_single_ch != '#'
  4843. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4844. || i_peek(input) != '}'
  4845. ) {
  4846. goto bad_dollar_syntax;
  4847. }
  4848. /* else: it's "length of C" ${#C} op,
  4849. * where C is a single char
  4850. * special var name, e.g. ${#!}.
  4851. */
  4852. }
  4853. eat_until_closing:
  4854. /* Eat everything until closing '}' (or ':') */
  4855. end_ch = '}';
  4856. if (BASH_SUBSTR
  4857. && ch == ':'
  4858. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4859. ) {
  4860. /* It's ${var:N[:M]} thing */
  4861. end_ch = '}' * 0x100 + ':';
  4862. }
  4863. if (BASH_PATTERN_SUBST
  4864. && ch == '/'
  4865. ) {
  4866. /* It's ${var/[/]pattern[/repl]} thing */
  4867. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4868. i_getch(input);
  4869. nommu_addchr(as_string, '/');
  4870. ch = '\\';
  4871. }
  4872. end_ch = '}' * 0x100 + '/';
  4873. }
  4874. o_addchr(dest, ch);
  4875. /* The pattern can't be empty.
  4876. * IOW: if the first char after "${v//" is a slash,
  4877. * it does not terminate the pattern - it's the first char of the pattern:
  4878. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4879. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4880. */
  4881. if (i_peek(input) == '/') {
  4882. o_addchr(dest, i_getch(input));
  4883. }
  4884. again:
  4885. if (!BB_MMU)
  4886. pos = dest->length;
  4887. #if ENABLE_HUSH_DOLLAR_OPS
  4888. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4889. if (last_ch == 0) /* error? */
  4890. return 0;
  4891. #else
  4892. # error Simple code to only allow ${var} is not implemented
  4893. #endif
  4894. if (as_string) {
  4895. o_addstr(as_string, dest->data + pos);
  4896. o_addchr(as_string, last_ch);
  4897. }
  4898. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4899. && (end_ch & 0xff00)
  4900. ) {
  4901. /* close the first block: */
  4902. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4903. /* while parsing N from ${var:N[:M]}
  4904. * or pattern from ${var/[/]pattern[/repl]} */
  4905. if ((end_ch & 0xff) == last_ch) {
  4906. /* got ':' or '/'- parse the rest */
  4907. end_ch = '}';
  4908. goto again;
  4909. }
  4910. /* got '}' */
  4911. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4912. /* it's ${var:N} - emulate :999999999 */
  4913. o_addstr(dest, "999999999");
  4914. } /* else: it's ${var/[/]pattern} */
  4915. }
  4916. break;
  4917. }
  4918. len_single_ch = 0; /* it can't be ${#C} op */
  4919. }
  4920. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4921. break;
  4922. }
  4923. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4924. case '(': {
  4925. unsigned pos;
  4926. ch = i_getch(input);
  4927. nommu_addchr(as_string, ch);
  4928. # if ENABLE_FEATURE_SH_MATH
  4929. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4930. ch = i_getch(input);
  4931. nommu_addchr(as_string, ch);
  4932. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4933. o_addchr(dest, quote_mask | '+');
  4934. if (!BB_MMU)
  4935. pos = dest->length;
  4936. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4937. return 0; /* error */
  4938. if (as_string) {
  4939. o_addstr(as_string, dest->data + pos);
  4940. o_addchr(as_string, ')');
  4941. o_addchr(as_string, ')');
  4942. }
  4943. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4944. break;
  4945. }
  4946. # endif
  4947. # if ENABLE_HUSH_TICK
  4948. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4949. o_addchr(dest, quote_mask | '`');
  4950. if (!BB_MMU)
  4951. pos = dest->length;
  4952. if (!add_till_closing_bracket(dest, input, ')'))
  4953. return 0; /* error */
  4954. if (as_string) {
  4955. o_addstr(as_string, dest->data + pos);
  4956. o_addchr(as_string, ')');
  4957. }
  4958. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4959. # endif
  4960. break;
  4961. }
  4962. #endif
  4963. case '_':
  4964. goto make_var;
  4965. #if 0
  4966. /* TODO: $_: */
  4967. /* $_ Shell or shell script name; or last argument of last command
  4968. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4969. * but in command's env, set to full pathname used to invoke it */
  4970. ch = i_getch(input);
  4971. nommu_addchr(as_string, ch);
  4972. ch = i_peek_and_eat_bkslash_nl(input);
  4973. if (isalnum(ch)) { /* it's $_name or $_123 */
  4974. ch = '_';
  4975. goto make_var1;
  4976. }
  4977. /* else: it's $_ */
  4978. #endif
  4979. default:
  4980. o_addQchr(dest, '$');
  4981. }
  4982. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4983. return 1;
  4984. #undef as_string
  4985. }
  4986. #if BB_MMU
  4987. #define encode_string(as_string, dest, input, dquote_end) \
  4988. encode_string(dest, input, dquote_end)
  4989. #define as_string NULL
  4990. #endif
  4991. static int encode_string(o_string *as_string,
  4992. o_string *dest,
  4993. struct in_str *input,
  4994. int dquote_end)
  4995. {
  4996. int ch;
  4997. int next;
  4998. again:
  4999. ch = i_getch(input);
  5000. if (ch != EOF)
  5001. nommu_addchr(as_string, ch);
  5002. if (ch == dquote_end) { /* may be only '"' or EOF */
  5003. debug_printf_parse("encode_string return 1 (ok)\n");
  5004. return 1;
  5005. }
  5006. /* note: can't move it above ch == dquote_end check! */
  5007. if (ch == EOF) {
  5008. syntax_error_unterm_ch('"');
  5009. return 0; /* error */
  5010. }
  5011. next = '\0';
  5012. if (ch != '\n') {
  5013. next = i_peek(input);
  5014. }
  5015. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  5016. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5017. if (ch == '\\') {
  5018. if (next == EOF) {
  5019. /* Testcase: in interactive shell a file with
  5020. * echo "unterminated string\<eof>
  5021. * is sourced.
  5022. */
  5023. syntax_error_unterm_ch('"');
  5024. return 0; /* error */
  5025. }
  5026. /* bash:
  5027. * "The backslash retains its special meaning [in "..."]
  5028. * only when followed by one of the following characters:
  5029. * $, `, ", \, or <newline>. A double quote may be quoted
  5030. * within double quotes by preceding it with a backslash."
  5031. * NB: in (unquoted) heredoc, above does not apply to ",
  5032. * therefore we check for it by "next == dquote_end" cond.
  5033. */
  5034. if (next == dquote_end || strchr("$`\\\n", next)) {
  5035. ch = i_getch(input); /* eat next */
  5036. if (ch == '\n')
  5037. goto again; /* skip \<newline> */
  5038. } /* else: ch remains == '\\', and we double it below: */
  5039. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  5040. nommu_addchr(as_string, ch);
  5041. goto again;
  5042. }
  5043. if (ch == '$') {
  5044. //if (parse_dollar_squote(as_string, dest, input))
  5045. // goto again;
  5046. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  5047. debug_printf_parse("encode_string return 0: "
  5048. "parse_dollar returned 0 (error)\n");
  5049. return 0;
  5050. }
  5051. goto again;
  5052. }
  5053. #if ENABLE_HUSH_TICK
  5054. if (ch == '`') {
  5055. //unsigned pos = dest->length;
  5056. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5057. o_addchr(dest, 0x80 | '`');
  5058. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  5059. return 0; /* error */
  5060. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5061. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5062. goto again;
  5063. }
  5064. #endif
  5065. o_addQchr(dest, ch);
  5066. if (ch == SPECIAL_VAR_SYMBOL) {
  5067. /* Convert "^C" to corresponding special variable reference */
  5068. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  5069. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5070. }
  5071. goto again;
  5072. #undef as_string
  5073. }
  5074. /*
  5075. * Scan input until EOF or end_trigger char.
  5076. * Return a list of pipes to execute, or NULL on EOF
  5077. * or if end_trigger character is met.
  5078. * On syntax error, exit if shell is not interactive,
  5079. * reset parsing machinery and start parsing anew,
  5080. * or return ERR_PTR.
  5081. */
  5082. static struct pipe *parse_stream(char **pstring,
  5083. int *heredoc_cnt_ptr,
  5084. struct in_str *input,
  5085. int end_trigger)
  5086. {
  5087. struct parse_context ctx;
  5088. int heredoc_cnt;
  5089. /* Single-quote triggers a bypass of the main loop until its mate is
  5090. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  5091. */
  5092. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  5093. end_trigger ? end_trigger : 'X');
  5094. debug_enter();
  5095. initialize_context(&ctx);
  5096. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  5097. * Preventing this:
  5098. */
  5099. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  5100. /* We used to separate words on $IFS here. This was wrong.
  5101. * $IFS is used only for word splitting when $var is expanded,
  5102. * here we should use blank chars as separators, not $IFS
  5103. */
  5104. heredoc_cnt = 0;
  5105. while (1) {
  5106. const char *is_blank;
  5107. const char *is_special;
  5108. int ch;
  5109. int next;
  5110. int redir_fd;
  5111. redir_type redir_style;
  5112. ch = i_getch(input);
  5113. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5114. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5115. if (ch == EOF) {
  5116. struct pipe *pi;
  5117. if (heredoc_cnt) {
  5118. syntax_error_unterm_str("here document");
  5119. goto parse_error_exitcode1;
  5120. }
  5121. if (end_trigger == ')') {
  5122. syntax_error_unterm_ch('(');
  5123. goto parse_error_exitcode1;
  5124. }
  5125. if (end_trigger == '}') {
  5126. syntax_error_unterm_ch('{');
  5127. goto parse_error_exitcode1;
  5128. }
  5129. if (done_word(&ctx)) {
  5130. goto parse_error_exitcode1;
  5131. }
  5132. o_free_and_set_NULL(&ctx.word);
  5133. done_pipe(&ctx, PIPE_SEQ);
  5134. pi = ctx.list_head;
  5135. /* If we got nothing... */
  5136. /* (this makes bare "&" cmd a no-op.
  5137. * bash says: "syntax error near unexpected token '&'") */
  5138. if (pi->num_cmds == 0
  5139. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5140. ) {
  5141. free_pipe_list(pi);
  5142. pi = NULL;
  5143. }
  5144. #if !BB_MMU
  5145. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5146. if (pstring)
  5147. *pstring = ctx.as_string.data;
  5148. else
  5149. o_free(&ctx.as_string);
  5150. #endif
  5151. // heredoc_cnt must be 0 here anyway
  5152. //if (heredoc_cnt_ptr)
  5153. // *heredoc_cnt_ptr = heredoc_cnt;
  5154. debug_leave();
  5155. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5156. debug_printf_parse("parse_stream return %p\n", pi);
  5157. return pi;
  5158. }
  5159. /* Handle "'" and "\" first, as they won't play nice with
  5160. * i_peek_and_eat_bkslash_nl() anyway:
  5161. * echo z\\
  5162. * and
  5163. * echo '\
  5164. * '
  5165. * would break.
  5166. */
  5167. if (ch == '\\') {
  5168. ch = i_getch(input);
  5169. if (ch == '\n')
  5170. continue; /* drop \<newline>, get next char */
  5171. nommu_addchr(&ctx.as_string, '\\');
  5172. if (ch == SPECIAL_VAR_SYMBOL) {
  5173. nommu_addchr(&ctx.as_string, ch);
  5174. /* Convert \^C to corresponding special variable reference */
  5175. goto case_SPECIAL_VAR_SYMBOL;
  5176. }
  5177. o_addchr(&ctx.word, '\\');
  5178. if (ch == EOF) {
  5179. /* Testcase: eval 'echo Ok\' */
  5180. /* bash-4.3.43 was removing backslash,
  5181. * but 4.4.19 retains it, most other shells too
  5182. */
  5183. continue; /* get next char */
  5184. }
  5185. /* Example: echo Hello \2>file
  5186. * we need to know that word 2 is quoted
  5187. */
  5188. ctx.word.has_quoted_part = 1;
  5189. nommu_addchr(&ctx.as_string, ch);
  5190. o_addchr(&ctx.word, ch);
  5191. continue; /* get next char */
  5192. }
  5193. nommu_addchr(&ctx.as_string, ch);
  5194. if (ch == '\'') {
  5195. ctx.word.has_quoted_part = 1;
  5196. next = i_getch(input);
  5197. if (next == '\'' && !ctx.pending_redirect)
  5198. goto insert_empty_quoted_str_marker;
  5199. ch = next;
  5200. while (1) {
  5201. if (ch == EOF) {
  5202. syntax_error_unterm_ch('\'');
  5203. goto parse_error_exitcode1;
  5204. }
  5205. nommu_addchr(&ctx.as_string, ch);
  5206. if (ch == '\'')
  5207. break;
  5208. if (ch == SPECIAL_VAR_SYMBOL) {
  5209. /* Convert raw ^C to corresponding special variable reference */
  5210. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5211. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5212. }
  5213. o_addqchr(&ctx.word, ch);
  5214. ch = i_getch(input);
  5215. }
  5216. continue; /* get next char */
  5217. }
  5218. next = '\0';
  5219. if (ch != '\n')
  5220. next = i_peek_and_eat_bkslash_nl(input);
  5221. is_special = "{}<>&|();#" /* special outside of "str" */
  5222. "$\"" IF_HUSH_TICK("`") /* always special */
  5223. SPECIAL_VAR_SYMBOL_STR;
  5224. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5225. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5226. /* In [[ ]], {}<>&|() are not special */
  5227. is_special += 8;
  5228. } else
  5229. #endif
  5230. /* Are { and } special here? */
  5231. if (ctx.command->argv /* word [word]{... - non-special */
  5232. || ctx.word.length /* word{... - non-special */
  5233. || ctx.word.has_quoted_part /* ""{... - non-special */
  5234. || (next != ';' /* }; - special */
  5235. && next != ')' /* }) - special */
  5236. && next != '(' /* {( - special */
  5237. && next != '&' /* }& and }&& ... - special */
  5238. && next != '|' /* }|| ... - special */
  5239. && !strchr(defifs, next) /* {word - non-special */
  5240. )
  5241. ) {
  5242. /* They are not special, skip "{}" */
  5243. is_special += 2;
  5244. }
  5245. is_special = strchr(is_special, ch);
  5246. is_blank = strchr(defifs, ch);
  5247. if (!is_special && !is_blank) { /* ordinary char */
  5248. ordinary_char:
  5249. o_addQchr(&ctx.word, ch);
  5250. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5251. || ctx.is_assignment == WORD_IS_KEYWORD)
  5252. && ch == '='
  5253. && endofname(ctx.word.data)[0] == '='
  5254. ) {
  5255. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5256. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5257. }
  5258. continue;
  5259. }
  5260. if (is_blank) {
  5261. #if ENABLE_HUSH_LINENO_VAR
  5262. /* Case:
  5263. * "while ...; do<whitespace><newline>
  5264. * cmd ..."
  5265. * would think that "cmd" starts in <whitespace> -
  5266. * i.e., at the previous line.
  5267. * We need to skip all whitespace before newlines.
  5268. */
  5269. while (ch != '\n') {
  5270. next = i_peek(input);
  5271. if (next != ' ' && next != '\t' && next != '\n')
  5272. break; /* next char is not ws */
  5273. ch = i_getch(input);
  5274. }
  5275. /* ch == last eaten whitespace char */
  5276. #endif
  5277. if (done_word(&ctx)) {
  5278. goto parse_error_exitcode1;
  5279. }
  5280. if (ch == '\n') {
  5281. /* Is this a case when newline is simply ignored?
  5282. * Some examples:
  5283. * "cmd | <newline> cmd ..."
  5284. * "case ... in <newline> word) ..."
  5285. */
  5286. if (IS_NULL_CMD(ctx.command)
  5287. && ctx.word.length == 0
  5288. && !ctx.word.has_quoted_part
  5289. && heredoc_cnt == 0
  5290. ) {
  5291. /* This newline can be ignored. But...
  5292. * Without check #1, interactive shell
  5293. * ignores even bare <newline>,
  5294. * and shows the continuation prompt:
  5295. * ps1_prompt$ <enter>
  5296. * ps2> _ <=== wrong, should be ps1
  5297. * Without check #2, "cmd & <newline>"
  5298. * is similarly mistreated.
  5299. * (BTW, this makes "cmd & cmd"
  5300. * and "cmd && cmd" non-orthogonal.
  5301. * Really, ask yourself, why
  5302. * "cmd && <newline>" doesn't start
  5303. * cmd but waits for more input?
  5304. * The only reason is that it might be
  5305. * a "cmd1 && <nl> cmd2 &" construct,
  5306. * cmd1 may need to run in BG).
  5307. */
  5308. struct pipe *pi = ctx.list_head;
  5309. if (pi->num_cmds != 0 /* check #1 */
  5310. && pi->followup != PIPE_BG /* check #2 */
  5311. ) {
  5312. continue;
  5313. }
  5314. }
  5315. /* Treat newline as a command separator. */
  5316. done_pipe(&ctx, PIPE_SEQ);
  5317. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5318. if (heredoc_cnt) {
  5319. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5320. if (heredoc_cnt != 0)
  5321. goto parse_error_exitcode1;
  5322. }
  5323. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5324. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5325. ch = ';';
  5326. /* note: if (is_blank) continue;
  5327. * will still trigger for us */
  5328. }
  5329. }
  5330. /* "cmd}" or "cmd }..." without semicolon or &:
  5331. * } is an ordinary char in this case, even inside { cmd; }
  5332. * Pathological example: { ""}; } should exec "}" cmd
  5333. */
  5334. if (ch == '}') {
  5335. if (ctx.word.length != 0 /* word} */
  5336. || ctx.word.has_quoted_part /* ""} */
  5337. ) {
  5338. goto ordinary_char;
  5339. }
  5340. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5341. /* Generally, there should be semicolon: "cmd; }"
  5342. * However, bash allows to omit it if "cmd" is
  5343. * a group. Examples:
  5344. * { { echo 1; } }
  5345. * {(echo 1)}
  5346. * { echo 0 >&2 | { echo 1; } }
  5347. * { while false; do :; done }
  5348. * { case a in b) ;; esac }
  5349. */
  5350. if (ctx.command->group)
  5351. goto term_group;
  5352. goto ordinary_char;
  5353. }
  5354. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5355. /* Can't be an end of {cmd}, skip the check */
  5356. goto skip_end_trigger;
  5357. /* else: } does terminate a group */
  5358. }
  5359. term_group:
  5360. if (end_trigger && end_trigger == ch
  5361. && (ch != ';' || heredoc_cnt == 0)
  5362. #if ENABLE_HUSH_CASE
  5363. && (ch != ')'
  5364. || ctx.ctx_res_w != RES_MATCH
  5365. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5366. )
  5367. #endif
  5368. ) {
  5369. if (done_word(&ctx)) {
  5370. goto parse_error_exitcode1;
  5371. }
  5372. done_pipe(&ctx, PIPE_SEQ);
  5373. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5374. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5375. /* Do we sit outside of any if's, loops or case's? */
  5376. if (!HAS_KEYWORDS
  5377. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5378. ) {
  5379. o_free_and_set_NULL(&ctx.word);
  5380. #if !BB_MMU
  5381. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5382. if (pstring)
  5383. *pstring = ctx.as_string.data;
  5384. else
  5385. o_free(&ctx.as_string);
  5386. #endif
  5387. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5388. /* Example: bare "{ }", "()" */
  5389. G.last_exitcode = 2; /* bash compat */
  5390. syntax_error_unexpected_ch(ch);
  5391. goto parse_error;
  5392. }
  5393. if (heredoc_cnt_ptr)
  5394. *heredoc_cnt_ptr = heredoc_cnt;
  5395. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5396. debug_printf_parse("parse_stream return %p: "
  5397. "end_trigger char found\n",
  5398. ctx.list_head);
  5399. debug_leave();
  5400. return ctx.list_head;
  5401. }
  5402. }
  5403. if (is_blank)
  5404. continue;
  5405. /* Catch <, > before deciding whether this word is
  5406. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5407. switch (ch) {
  5408. case '>':
  5409. redir_fd = redirect_opt_num(&ctx.word);
  5410. if (done_word(&ctx)) {
  5411. goto parse_error_exitcode1;
  5412. }
  5413. redir_style = REDIRECT_OVERWRITE;
  5414. if (next == '>') {
  5415. redir_style = REDIRECT_APPEND;
  5416. ch = i_getch(input);
  5417. nommu_addchr(&ctx.as_string, ch);
  5418. }
  5419. #if 0
  5420. else if (next == '(') {
  5421. syntax_error(">(process) not supported");
  5422. goto parse_error_exitcode1;
  5423. }
  5424. #endif
  5425. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5426. goto parse_error_exitcode1;
  5427. continue; /* get next char */
  5428. case '<':
  5429. redir_fd = redirect_opt_num(&ctx.word);
  5430. if (done_word(&ctx)) {
  5431. goto parse_error_exitcode1;
  5432. }
  5433. redir_style = REDIRECT_INPUT;
  5434. if (next == '<') {
  5435. redir_style = REDIRECT_HEREDOC;
  5436. heredoc_cnt++;
  5437. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5438. ch = i_getch(input);
  5439. nommu_addchr(&ctx.as_string, ch);
  5440. } else if (next == '>') {
  5441. redir_style = REDIRECT_IO;
  5442. ch = i_getch(input);
  5443. nommu_addchr(&ctx.as_string, ch);
  5444. }
  5445. #if 0
  5446. else if (next == '(') {
  5447. syntax_error("<(process) not supported");
  5448. goto parse_error_exitcode1;
  5449. }
  5450. #endif
  5451. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5452. goto parse_error_exitcode1;
  5453. continue; /* get next char */
  5454. case '#':
  5455. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5456. /* skip "#comment" */
  5457. /* note: we do not add it to &ctx.as_string */
  5458. /* TODO: in bash:
  5459. * comment inside $() goes to the next \n, even inside quoted string (!):
  5460. * cmd "$(cmd2 #comment)" - syntax error
  5461. * cmd "`cmd2 #comment`" - ok
  5462. * We accept both (comment ends where command subst ends, in both cases).
  5463. */
  5464. while (1) {
  5465. ch = i_peek(input);
  5466. if (ch == '\n') {
  5467. nommu_addchr(&ctx.as_string, '\n');
  5468. break;
  5469. }
  5470. ch = i_getch(input);
  5471. if (ch == EOF)
  5472. break;
  5473. }
  5474. continue; /* get next char */
  5475. }
  5476. break;
  5477. }
  5478. skip_end_trigger:
  5479. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5480. /* check that we are not in word in "a=1 2>word b=1": */
  5481. && !ctx.pending_redirect
  5482. ) {
  5483. /* ch is a special char and thus this word
  5484. * cannot be an assignment */
  5485. ctx.is_assignment = NOT_ASSIGNMENT;
  5486. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5487. }
  5488. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5489. switch (ch) {
  5490. case_SPECIAL_VAR_SYMBOL:
  5491. case SPECIAL_VAR_SYMBOL:
  5492. /* Convert raw ^C to corresponding special variable reference */
  5493. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5494. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5495. /* fall through */
  5496. case '#':
  5497. /* non-comment #: "echo a#b" etc */
  5498. o_addchr(&ctx.word, ch);
  5499. continue; /* get next char */
  5500. case '$':
  5501. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5502. continue; /* get next char */
  5503. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5504. debug_printf_parse("parse_stream parse error: "
  5505. "parse_dollar returned 0 (error)\n");
  5506. goto parse_error_exitcode1;
  5507. }
  5508. continue; /* get next char */
  5509. case '"':
  5510. ctx.word.has_quoted_part = 1;
  5511. if (next == '"' && !ctx.pending_redirect) {
  5512. i_getch(input); /* eat second " */
  5513. insert_empty_quoted_str_marker:
  5514. nommu_addchr(&ctx.as_string, next);
  5515. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5516. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5517. continue; /* get next char */
  5518. }
  5519. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5520. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5521. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5522. goto parse_error_exitcode1;
  5523. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5524. continue; /* get next char */
  5525. #if ENABLE_HUSH_TICK
  5526. case '`': {
  5527. USE_FOR_NOMMU(unsigned pos;)
  5528. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5529. o_addchr(&ctx.word, '`');
  5530. USE_FOR_NOMMU(pos = ctx.word.length;)
  5531. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5532. goto parse_error_exitcode1;
  5533. # if !BB_MMU
  5534. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5535. o_addchr(&ctx.as_string, '`');
  5536. # endif
  5537. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5538. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5539. continue; /* get next char */
  5540. }
  5541. #endif
  5542. case ';':
  5543. #if ENABLE_HUSH_CASE
  5544. case_semi:
  5545. #endif
  5546. if (done_word(&ctx)) {
  5547. goto parse_error_exitcode1;
  5548. }
  5549. done_pipe(&ctx, PIPE_SEQ);
  5550. #if ENABLE_HUSH_CASE
  5551. /* Eat multiple semicolons, detect
  5552. * whether it means something special */
  5553. while (1) {
  5554. ch = i_peek_and_eat_bkslash_nl(input);
  5555. if (ch != ';')
  5556. break;
  5557. ch = i_getch(input);
  5558. nommu_addchr(&ctx.as_string, ch);
  5559. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5560. ctx.ctx_dsemicolon = 1;
  5561. ctx.ctx_res_w = RES_MATCH;
  5562. break;
  5563. }
  5564. }
  5565. #endif
  5566. new_cmd:
  5567. /* We just finished a cmd. New one may start
  5568. * with an assignment */
  5569. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5570. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5571. continue; /* get next char */
  5572. case '&':
  5573. if (done_word(&ctx)) {
  5574. goto parse_error_exitcode1;
  5575. }
  5576. if (next == '&') {
  5577. ch = i_getch(input);
  5578. nommu_addchr(&ctx.as_string, ch);
  5579. done_pipe(&ctx, PIPE_AND);
  5580. } else {
  5581. done_pipe(&ctx, PIPE_BG);
  5582. }
  5583. goto new_cmd;
  5584. case '|':
  5585. if (done_word(&ctx)) {
  5586. goto parse_error_exitcode1;
  5587. }
  5588. #if ENABLE_HUSH_CASE
  5589. if (ctx.ctx_res_w == RES_MATCH)
  5590. break; /* we are in case's "word | word)" */
  5591. #endif
  5592. if (next == '|') { /* || */
  5593. ch = i_getch(input);
  5594. nommu_addchr(&ctx.as_string, ch);
  5595. done_pipe(&ctx, PIPE_OR);
  5596. } else {
  5597. /* we could pick up a file descriptor choice here
  5598. * with redirect_opt_num(), but bash doesn't do it.
  5599. * "echo foo 2| cat" yields "foo 2". */
  5600. done_command(&ctx);
  5601. }
  5602. goto new_cmd;
  5603. case '(':
  5604. #if ENABLE_HUSH_CASE
  5605. /* "case... in [(]word)..." - skip '(' */
  5606. if (ctx.ctx_res_w == RES_MATCH
  5607. && ctx.command->argv == NULL /* not (word|(... */
  5608. && ctx.word.length == 0 /* not word(... */
  5609. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5610. ) {
  5611. continue; /* get next char */
  5612. }
  5613. #endif
  5614. /* fall through */
  5615. case '{': {
  5616. int n = parse_group(&ctx, input, ch);
  5617. if (n < 0) {
  5618. goto parse_error_exitcode1;
  5619. }
  5620. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5621. heredoc_cnt += n;
  5622. goto new_cmd;
  5623. }
  5624. case ')':
  5625. #if ENABLE_HUSH_CASE
  5626. if (ctx.ctx_res_w == RES_MATCH)
  5627. goto case_semi;
  5628. #endif
  5629. case '}':
  5630. /* proper use of this character is caught by end_trigger:
  5631. * if we see {, we call parse_group(..., end_trigger='}')
  5632. * and it will match } earlier (not here). */
  5633. G.last_exitcode = 2;
  5634. syntax_error_unexpected_ch(ch);
  5635. goto parse_error;
  5636. default:
  5637. if (HUSH_DEBUG)
  5638. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5639. }
  5640. } /* while (1) */
  5641. parse_error_exitcode1:
  5642. G.last_exitcode = 1;
  5643. parse_error:
  5644. {
  5645. struct parse_context *pctx;
  5646. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5647. /* Clean up allocated tree.
  5648. * Sample for finding leaks on syntax error recovery path.
  5649. * Run it from interactive shell, watch pmap `pidof hush`.
  5650. * while if false; then false; fi; do break; fi
  5651. * Samples to catch leaks at execution:
  5652. * while if (true | { true;}); then echo ok; fi; do break; done
  5653. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5654. */
  5655. pctx = &ctx;
  5656. do {
  5657. /* Update pipe/command counts,
  5658. * otherwise freeing may miss some */
  5659. done_pipe(pctx, PIPE_SEQ);
  5660. debug_printf_clean("freeing list %p from ctx %p\n",
  5661. pctx->list_head, pctx);
  5662. debug_print_tree(pctx->list_head, 0);
  5663. free_pipe_list(pctx->list_head);
  5664. debug_printf_clean("freed list %p\n", pctx->list_head);
  5665. #if !BB_MMU
  5666. o_free(&pctx->as_string);
  5667. #endif
  5668. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5669. if (pctx != &ctx) {
  5670. free(pctx);
  5671. }
  5672. IF_HAS_KEYWORDS(pctx = p2;)
  5673. } while (HAS_KEYWORDS && pctx);
  5674. o_free(&ctx.word);
  5675. #if !BB_MMU
  5676. if (pstring)
  5677. *pstring = NULL;
  5678. #endif
  5679. debug_leave();
  5680. return ERR_PTR;
  5681. }
  5682. }
  5683. /*** Execution routines ***/
  5684. /* Expansion can recurse, need forward decls: */
  5685. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5686. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5687. expand_string_to_string(str)
  5688. #endif
  5689. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5690. #if ENABLE_HUSH_TICK
  5691. static int process_command_subs(o_string *dest, const char *s);
  5692. #endif
  5693. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5694. /* expand_strvec_to_strvec() takes a list of strings, expands
  5695. * all variable references within and returns a pointer to
  5696. * a list of expanded strings, possibly with larger number
  5697. * of strings. (Think VAR="a b"; echo $VAR).
  5698. * This new list is allocated as a single malloc block.
  5699. * NULL-terminated list of char* pointers is at the beginning of it,
  5700. * followed by strings themselves.
  5701. * Caller can deallocate entire list by single free(list). */
  5702. /* A horde of its helpers come first: */
  5703. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5704. {
  5705. while (--len >= 0) {
  5706. char c = *str++;
  5707. #if ENABLE_HUSH_BRACE_EXPANSION
  5708. if (c == '{' || c == '}') {
  5709. /* { -> \{, } -> \} */
  5710. o_addchr(o, '\\');
  5711. /* And now we want to add { or } and continue:
  5712. * o_addchr(o, c);
  5713. * continue;
  5714. * luckily, just falling through achieves this.
  5715. */
  5716. }
  5717. #endif
  5718. o_addchr(o, c);
  5719. if (c == '\\') {
  5720. /* \z -> \\\z; \<eol> -> \\<eol> */
  5721. o_addchr(o, '\\');
  5722. if (len) {
  5723. len--;
  5724. o_addchr(o, '\\');
  5725. o_addchr(o, *str++);
  5726. }
  5727. }
  5728. }
  5729. }
  5730. /* Store given string, finalizing the word and starting new one whenever
  5731. * we encounter IFS char(s). This is used for expanding variable values.
  5732. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5733. * Return in output->ended_in_ifs:
  5734. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5735. */
  5736. static int expand_on_ifs(o_string *output, int n, const char *str)
  5737. {
  5738. int last_is_ifs = 0;
  5739. while (1) {
  5740. int word_len;
  5741. if (!*str) /* EOL - do not finalize word */
  5742. break;
  5743. word_len = strcspn(str, G.ifs);
  5744. if (word_len) {
  5745. /* We have WORD_LEN leading non-IFS chars */
  5746. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5747. o_addblock(output, str, word_len);
  5748. } else {
  5749. /* Protect backslashes against globbing up :)
  5750. * Example: "v='\*'; echo b$v" prints "b\*"
  5751. * (and does not try to glob on "*")
  5752. */
  5753. o_addblock_duplicate_backslash(output, str, word_len);
  5754. /*/ Why can't we do it easier? */
  5755. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5756. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5757. }
  5758. last_is_ifs = 0;
  5759. str += word_len;
  5760. if (!*str) /* EOL - do not finalize word */
  5761. break;
  5762. }
  5763. /* We know str here points to at least one IFS char */
  5764. last_is_ifs = 1;
  5765. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5766. if (!*str) /* EOL - do not finalize word */
  5767. break;
  5768. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5769. && strchr(G.ifs, *str) /* the second check would fail */
  5770. ) {
  5771. /* This is a non-whitespace $IFS char */
  5772. /* Skip it and IFS whitespace chars, start new word */
  5773. str++;
  5774. str += strspn(str, G.ifs_whitespace);
  5775. goto new_word;
  5776. }
  5777. /* Start new word... but not always! */
  5778. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5779. if (output->has_quoted_part
  5780. /*
  5781. * Case "v=' a'; echo $v":
  5782. * here nothing precedes the space in $v expansion,
  5783. * therefore we should not finish the word
  5784. * (IOW: if there *is* word to finalize, only then do it):
  5785. * It's okay if this accesses the byte before first argv[]:
  5786. * past call to o_save_ptr() cleared it to zero byte
  5787. * (grep for -prev-ifs-check-).
  5788. */
  5789. || output->data[output->length - 1]
  5790. ) {
  5791. new_word:
  5792. o_addchr(output, '\0');
  5793. debug_print_list("expand_on_ifs", output, n);
  5794. n = o_save_ptr(output, n);
  5795. }
  5796. }
  5797. output->ended_in_ifs = last_is_ifs;
  5798. debug_print_list("expand_on_ifs[1]", output, n);
  5799. return n;
  5800. }
  5801. /* Helper to expand $((...)) and heredoc body. These act as if
  5802. * they are in double quotes, with the exception that they are not :).
  5803. * Just the rules are similar: "expand only $var and `cmd`"
  5804. *
  5805. * Returns malloced string.
  5806. * As an optimization, we return NULL if expansion is not needed.
  5807. */
  5808. static char *encode_then_expand_string(const char *str)
  5809. {
  5810. char *exp_str;
  5811. struct in_str input;
  5812. o_string dest = NULL_O_STRING;
  5813. const char *cp;
  5814. cp = str;
  5815. for (;;) {
  5816. if (!*cp) return NULL; /* string has no special chars */
  5817. if (*cp == '$') break;
  5818. if (*cp == '\\') break;
  5819. #if ENABLE_HUSH_TICK
  5820. if (*cp == '`') break;
  5821. #endif
  5822. cp++;
  5823. }
  5824. /* We need to expand. Example:
  5825. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5826. */
  5827. setup_string_in_str(&input, str);
  5828. encode_string(NULL, &dest, &input, EOF);
  5829. //TODO: error check (encode_string returns 0 on error)?
  5830. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5831. exp_str = expand_string_to_string(dest.data,
  5832. EXP_FLAG_ESC_GLOB_CHARS,
  5833. /*unbackslash:*/ 1
  5834. );
  5835. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5836. o_free(&dest);
  5837. return exp_str;
  5838. }
  5839. static const char *first_special_char_in_vararg(const char *cp)
  5840. {
  5841. for (;;) {
  5842. if (!*cp) return NULL; /* string has no special chars */
  5843. if (*cp == '$') return cp;
  5844. if (*cp == '\\') return cp;
  5845. if (*cp == '\'') return cp;
  5846. if (*cp == '"') return cp;
  5847. #if ENABLE_HUSH_TICK
  5848. if (*cp == '`') return cp;
  5849. #endif
  5850. /* dquoted "${x:+ARG}" should not glob, therefore
  5851. * '*' et al require some non-literal processing: */
  5852. if (*cp == '*') return cp;
  5853. if (*cp == '?') return cp;
  5854. if (*cp == '[') return cp;
  5855. cp++;
  5856. }
  5857. }
  5858. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5859. * These can contain single- and double-quoted strings,
  5860. * and treated as if the ARG string is initially unquoted. IOW:
  5861. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5862. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5863. * (word splitting and globbing of the ${var...} result).
  5864. */
  5865. #if !BASH_PATTERN_SUBST
  5866. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5867. encode_then_expand_vararg(str, handle_squotes)
  5868. #endif
  5869. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5870. {
  5871. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5872. const int do_unbackslash = 0;
  5873. #endif
  5874. char *exp_str;
  5875. struct in_str input;
  5876. o_string dest = NULL_O_STRING;
  5877. if (!first_special_char_in_vararg(str)) {
  5878. /* string has no special chars */
  5879. return NULL;
  5880. }
  5881. setup_string_in_str(&input, str);
  5882. dest.data = xzalloc(1); /* start as "", not as NULL */
  5883. exp_str = NULL;
  5884. for (;;) {
  5885. int ch;
  5886. ch = i_getch(&input);
  5887. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5888. __func__, ch, ch, !!dest.o_expflags);
  5889. if (!dest.o_expflags) {
  5890. if (ch == EOF)
  5891. break;
  5892. if (handle_squotes && ch == '\'') {
  5893. if (!add_till_single_quote_dquoted(&dest, &input))
  5894. goto ret; /* error */
  5895. continue;
  5896. }
  5897. }
  5898. if (ch == EOF) {
  5899. syntax_error_unterm_ch('"');
  5900. goto ret; /* error */
  5901. }
  5902. if (ch == '"') {
  5903. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5904. continue;
  5905. }
  5906. if (ch == '\\') {
  5907. ch = i_getch(&input);
  5908. if (ch == EOF) {
  5909. //example? error message? syntax_error_unterm_ch('"');
  5910. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5911. goto ret;
  5912. }
  5913. o_addqchr(&dest, ch);
  5914. continue;
  5915. }
  5916. if (ch == '$') {
  5917. if (parse_dollar_squote(NULL, &dest, &input))
  5918. continue;
  5919. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5920. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5921. goto ret;
  5922. }
  5923. continue;
  5924. }
  5925. #if ENABLE_HUSH_TICK
  5926. if (ch == '`') {
  5927. //unsigned pos = dest->length;
  5928. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5929. o_addchr(&dest, 0x80 | '`');
  5930. if (!add_till_backquote(&dest, &input,
  5931. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5932. )
  5933. ) {
  5934. goto ret; /* error */
  5935. }
  5936. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5937. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5938. continue;
  5939. }
  5940. #endif
  5941. o_addQchr(&dest, ch);
  5942. } /* for (;;) */
  5943. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5944. exp_str = expand_string_to_string(dest.data,
  5945. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5946. do_unbackslash
  5947. );
  5948. ret:
  5949. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5950. o_free(&dest);
  5951. return exp_str;
  5952. }
  5953. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5954. */
  5955. static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
  5956. char *str, int dquoted)
  5957. {
  5958. struct in_str input;
  5959. o_string dest = NULL_O_STRING;
  5960. if (!first_special_char_in_vararg(str)
  5961. && '\0' == str[strcspn(str, G.ifs)]
  5962. ) {
  5963. /* string has no special chars
  5964. * && string has no $IFS chars
  5965. */
  5966. if (dquoted) {
  5967. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5968. * set -- "${notexist-}"; echo $#
  5969. */
  5970. output->has_quoted_part = 1;
  5971. }
  5972. return expand_vars_to_list(output, n, str);
  5973. }
  5974. setup_string_in_str(&input, str);
  5975. for (;;) {
  5976. int ch;
  5977. ch = i_getch(&input);
  5978. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5979. __func__, ch, ch, dest.o_expflags);
  5980. if (!dest.o_expflags) {
  5981. if (ch == EOF)
  5982. break;
  5983. if (!dquoted && strchr(G.ifs, ch)) {
  5984. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5985. * do not assume we are at the start of the word (PREFIX above).
  5986. */
  5987. if (dest.data) {
  5988. n = expand_vars_to_list(output, n, dest.data);
  5989. o_free_and_set_NULL(&dest);
  5990. o_addchr(output, '\0');
  5991. n = o_save_ptr(output, n); /* create next word */
  5992. } else
  5993. if (output->length != o_get_last_ptr(output, n)
  5994. || output->has_quoted_part
  5995. ) {
  5996. /* For these cases:
  5997. * f() { for i; do echo "|$i|"; done; }; x=x
  5998. * f a${x:+ }b # 1st condition
  5999. * |a|
  6000. * |b|
  6001. * f ""${x:+ }b # 2nd condition
  6002. * ||
  6003. * |b|
  6004. */
  6005. o_addchr(output, '\0');
  6006. n = o_save_ptr(output, n); /* create next word */
  6007. }
  6008. continue;
  6009. }
  6010. if (!dquoted && ch == '\'') {
  6011. if (!add_till_single_quote_dquoted(&dest, &input))
  6012. goto ret; /* error */
  6013. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6014. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6015. continue;
  6016. }
  6017. }
  6018. if (ch == EOF) {
  6019. syntax_error_unterm_ch('"');
  6020. goto ret; /* error */
  6021. }
  6022. if (ch == '"') {
  6023. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  6024. if (dest.o_expflags) {
  6025. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6026. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6027. }
  6028. continue;
  6029. }
  6030. if (ch == '\\') {
  6031. ch = i_getch(&input);
  6032. if (ch == EOF) {
  6033. //example? error message? syntax_error_unterm_ch('"');
  6034. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  6035. goto ret;
  6036. }
  6037. o_addqchr(&dest, ch);
  6038. continue;
  6039. }
  6040. if (ch == '$') {
  6041. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6042. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6043. goto ret;
  6044. }
  6045. continue;
  6046. }
  6047. #if ENABLE_HUSH_TICK
  6048. if (ch == '`') {
  6049. //unsigned pos = dest->length;
  6050. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6051. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6052. if (!add_till_backquote(&dest, &input,
  6053. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6054. )
  6055. ) {
  6056. goto ret; /* error */
  6057. }
  6058. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6059. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6060. continue;
  6061. }
  6062. #endif
  6063. if (dquoted) {
  6064. /* Always glob-protect if in dquotes:
  6065. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6066. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6067. */
  6068. o_addqchr(&dest, ch);
  6069. } else {
  6070. /* Glob-protect only if char is quoted:
  6071. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6072. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6073. */
  6074. o_addQchr(&dest, ch);
  6075. }
  6076. } /* for (;;) */
  6077. if (dest.data) {
  6078. n = expand_vars_to_list(output, n, dest.data);
  6079. }
  6080. ret:
  6081. o_free(&dest);
  6082. return n;
  6083. }
  6084. #if ENABLE_FEATURE_SH_MATH
  6085. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6086. {
  6087. arith_state_t math_state;
  6088. arith_t res;
  6089. char *exp_str;
  6090. math_state.lookupvar = get_local_var_value;
  6091. math_state.setvar = set_local_var_from_halves;
  6092. //math_state.endofname = endofname;
  6093. exp_str = encode_then_expand_string(arg);
  6094. res = arith(&math_state, exp_str ? exp_str : arg);
  6095. free(exp_str);
  6096. if (errmsg_p)
  6097. *errmsg_p = math_state.errmsg;
  6098. if (math_state.errmsg)
  6099. msg_and_die_if_script(math_state.errmsg);
  6100. return res;
  6101. }
  6102. #endif
  6103. #if BASH_PATTERN_SUBST
  6104. /* ${var/[/]pattern[/repl]} helpers */
  6105. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6106. {
  6107. int first_escaped = (pattern[0] == '\\' && pattern[1]);
  6108. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6109. * as literal too (as it is semi-common, and easy to accomodate
  6110. * by just using str + 1).
  6111. */
  6112. int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
  6113. if ((pattern + first_escaped * 2)[sz] == '\0') {
  6114. /* Optimization for trivial patterns.
  6115. * Testcase for very slow replace (performs about 22k replaces):
  6116. * x=::::::::::::::::::::::
  6117. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6118. * echo "${x//:/|}"
  6119. */
  6120. *size = sz + first_escaped;
  6121. return strstr(val, pattern + first_escaped);
  6122. }
  6123. while (1) {
  6124. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6125. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6126. if (end) {
  6127. *size = end - val;
  6128. return val;
  6129. }
  6130. if (*val == '\0')
  6131. return NULL;
  6132. /* Optimization: if "*pat" did not match the start of "string",
  6133. * we know that "tring", "ring" etc will not match too:
  6134. */
  6135. if (pattern[0] == '*')
  6136. return NULL;
  6137. val++;
  6138. }
  6139. }
  6140. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6141. {
  6142. char *result = NULL;
  6143. unsigned res_len = 0;
  6144. unsigned repl_len = strlen(repl);
  6145. /* Null pattern never matches, including if "var" is empty */
  6146. if (!pattern[0])
  6147. return result; /* NULL, no replaces happened */
  6148. while (1) {
  6149. int size;
  6150. char *s = strstr_pattern(val, pattern, &size);
  6151. if (!s)
  6152. break;
  6153. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6154. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6155. res_len += (s - val) + repl_len;
  6156. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6157. val = s + size;
  6158. if (exp_op == '/')
  6159. break;
  6160. }
  6161. if (*val && result) {
  6162. result = xrealloc(result, res_len + strlen(val) + 1);
  6163. strcpy(result + res_len, val);
  6164. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6165. }
  6166. debug_printf_varexp("result:'%s'\n", result);
  6167. return result;
  6168. }
  6169. #endif /* BASH_PATTERN_SUBST */
  6170. static int append_str_maybe_ifs_split(o_string *output, int n,
  6171. int first_ch, const char *val)
  6172. {
  6173. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6174. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6175. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6176. if (val && val[0])
  6177. n = expand_on_ifs(output, n, val);
  6178. } else { /* quoted "$VAR" */
  6179. output->has_quoted_part = 1;
  6180. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6181. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6182. if (val && val[0])
  6183. o_addQstr(output, val);
  6184. }
  6185. return n;
  6186. }
  6187. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6188. */
  6189. static NOINLINE int expand_one_var(o_string *output, int n,
  6190. int first_ch, char *arg, char **pp)
  6191. {
  6192. const char *val;
  6193. char *to_be_freed;
  6194. char *p;
  6195. char *var;
  6196. char exp_op;
  6197. char exp_save = exp_save; /* for compiler */
  6198. char *exp_saveptr; /* points to expansion operator */
  6199. char *exp_word = exp_word; /* for compiler */
  6200. char arg0;
  6201. val = NULL;
  6202. to_be_freed = NULL;
  6203. p = *pp;
  6204. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6205. var = arg;
  6206. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6207. arg0 = arg[0];
  6208. arg[0] = (arg0 & 0x7f);
  6209. exp_op = 0;
  6210. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6211. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6212. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6213. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6214. ) {
  6215. /* It must be length operator: ${#var} */
  6216. var++;
  6217. exp_op = 'L';
  6218. } else {
  6219. /* Maybe handle parameter expansion */
  6220. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6221. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6222. ) {
  6223. /* ${?:0}, ${#[:]%0} etc */
  6224. exp_saveptr = var + 1;
  6225. } else {
  6226. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6227. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6228. }
  6229. exp_op = exp_save = *exp_saveptr;
  6230. if (exp_op) {
  6231. exp_word = exp_saveptr + 1;
  6232. if (exp_op == ':') {
  6233. exp_op = *exp_word++;
  6234. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6235. if (BASH_SUBSTR
  6236. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6237. ) {
  6238. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6239. exp_op = ':';
  6240. exp_word--;
  6241. }
  6242. }
  6243. *exp_saveptr = '\0';
  6244. } /* else: it's not an expansion op, but bare ${var} */
  6245. }
  6246. /* Look up the variable in question */
  6247. if (isdigit(var[0])) {
  6248. /* parse_dollar should have vetted var for us */
  6249. int nn = xatoi_positive(var);
  6250. if (nn < G.global_argc)
  6251. val = G.global_argv[nn];
  6252. /* else val remains NULL: $N with too big N */
  6253. } else {
  6254. switch (var[0]) {
  6255. case '$': /* pid */
  6256. val = utoa(G.root_pid);
  6257. break;
  6258. case '!': /* bg pid */
  6259. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6260. break;
  6261. case '?': /* exitcode */
  6262. val = utoa(G.last_exitcode);
  6263. break;
  6264. case '#': /* argc */
  6265. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6266. break;
  6267. case '-': { /* active options */
  6268. /* Check set_mode() to see what option chars we support */
  6269. char *cp;
  6270. val = cp = G.optstring_buf;
  6271. if (G.o_opt[OPT_O_ERREXIT])
  6272. *cp++ = 'e';
  6273. if (G_interactive_fd)
  6274. *cp++ = 'i';
  6275. if (G_x_mode)
  6276. *cp++ = 'x';
  6277. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6278. * commands read but are not executed,
  6279. * so $- can not execute too, 'n' is never seen in $-.
  6280. */
  6281. if (G.opt_c)
  6282. *cp++ = 'c';
  6283. if (G.opt_s)
  6284. *cp++ = 's';
  6285. *cp = '\0';
  6286. break;
  6287. }
  6288. default:
  6289. val = get_local_var_value(var);
  6290. }
  6291. }
  6292. /* Handle any expansions */
  6293. if (exp_op == 'L') {
  6294. reinit_unicode_for_hush();
  6295. debug_printf_expand("expand: length(%s)=", val);
  6296. val = utoa(val ? unicode_strlen(val) : 0);
  6297. debug_printf_expand("%s\n", val);
  6298. } else if (exp_op) {
  6299. if (exp_op == '%' || exp_op == '#') {
  6300. /* Standard-mandated substring removal ops:
  6301. * ${parameter%word} - remove smallest suffix pattern
  6302. * ${parameter%%word} - remove largest suffix pattern
  6303. * ${parameter#word} - remove smallest prefix pattern
  6304. * ${parameter##word} - remove largest prefix pattern
  6305. *
  6306. * Word is expanded to produce a glob pattern.
  6307. * Then var's value is matched to it and matching part removed.
  6308. */
  6309. /* bash compat: if x is "" and no shrinking of it is possible,
  6310. * inner ${...} is not evaluated. Example:
  6311. * unset b; : ${a%${b=B}}; echo $b
  6312. * assignment b=B only happens if $a is not "".
  6313. */
  6314. if (val && val[0]) {
  6315. char *t;
  6316. char *exp_exp_word;
  6317. char *loc;
  6318. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6319. if (exp_op == *exp_word) /* ## or %% */
  6320. exp_word++;
  6321. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6322. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6323. if (exp_exp_word)
  6324. exp_word = exp_exp_word;
  6325. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6326. /*
  6327. * HACK ALERT. We depend here on the fact that
  6328. * G.global_argv and results of utoa and get_local_var_value
  6329. * are actually in writable memory:
  6330. * scan_and_match momentarily stores NULs there.
  6331. */
  6332. t = (char*)val;
  6333. loc = scan_and_match(t, exp_word, scan_flags);
  6334. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6335. free(exp_exp_word);
  6336. if (loc) { /* match was found */
  6337. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6338. val = loc; /* take right part */
  6339. else /* %[%] */
  6340. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6341. }
  6342. }
  6343. }
  6344. #if BASH_PATTERN_SUBST
  6345. else if (exp_op == '/' || exp_op == '\\') {
  6346. /* It's ${var/[/]pattern[/repl]} thing.
  6347. * Note that in encoded form it has TWO parts:
  6348. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6349. * and if // is used, it is encoded as \:
  6350. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6351. */
  6352. /* bash compat: if var is "", both pattern and repl
  6353. * are still evaluated, if it is unset, then not:
  6354. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6355. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6356. */
  6357. if (val /*&& val[0]*/) {
  6358. /* pattern uses non-standard expansion.
  6359. * repl should be unbackslashed and globbed
  6360. * by the usual expansion rules:
  6361. * >az >bz
  6362. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6363. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6364. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6365. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6366. * (note that a*z _pattern_ is never globbed!)
  6367. */
  6368. char *pattern, *repl, *t;
  6369. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6370. if (!pattern)
  6371. pattern = xstrdup(exp_word);
  6372. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6373. *p++ = SPECIAL_VAR_SYMBOL;
  6374. exp_word = p;
  6375. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6376. *p = '\0';
  6377. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6378. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6379. /* HACK ALERT. We depend here on the fact that
  6380. * G.global_argv and results of utoa and get_local_var_value
  6381. * are actually in writable memory:
  6382. * replace_pattern momentarily stores NULs there. */
  6383. t = (char*)val;
  6384. to_be_freed = replace_pattern(t,
  6385. pattern,
  6386. (repl ? repl : exp_word),
  6387. exp_op);
  6388. if (to_be_freed) /* at least one replace happened */
  6389. val = to_be_freed;
  6390. free(pattern);
  6391. free(repl);
  6392. } else {
  6393. /* Unset variable always gives nothing */
  6394. // a=; echo ${a/*/w} # "w"
  6395. // unset a; echo ${a/*/w} # ""
  6396. /* Just skip "replace" part */
  6397. *p++ = SPECIAL_VAR_SYMBOL;
  6398. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6399. *p = '\0';
  6400. }
  6401. }
  6402. #endif /* BASH_PATTERN_SUBST */
  6403. else if (exp_op == ':') {
  6404. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6405. /* It's ${var:N[:M]} bashism.
  6406. * Note that in encoded form it has TWO parts:
  6407. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6408. */
  6409. arith_t beg, len;
  6410. unsigned vallen;
  6411. const char *errmsg;
  6412. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6413. if (errmsg)
  6414. goto empty_result;
  6415. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6416. *p++ = SPECIAL_VAR_SYMBOL;
  6417. exp_word = p;
  6418. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6419. *p = '\0';
  6420. vallen = val ? strlen(val) : 0;
  6421. if (beg < 0) {
  6422. /* negative beg counts from the end */
  6423. beg = (arith_t)vallen + beg;
  6424. }
  6425. /* If expansion will be empty, do not even evaluate len */
  6426. if (!val || beg < 0 || beg > vallen) {
  6427. /* Why > vallen, not >=? bash:
  6428. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6429. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6430. */
  6431. goto empty_result;
  6432. }
  6433. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6434. if (errmsg)
  6435. goto empty_result;
  6436. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6437. debug_printf_varexp("from val:'%s'\n", val);
  6438. if (len < 0) {
  6439. /* in bash, len=-n means strlen()-n */
  6440. len = (arith_t)vallen - beg + len;
  6441. if (len < 0) /* bash compat */
  6442. msg_and_die_if_script("%s: substring expression < 0", var);
  6443. }
  6444. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6445. empty_result:
  6446. val = NULL;
  6447. } else {
  6448. /* Paranoia. What if user entered 9999999999999
  6449. * which fits in arith_t but not int? */
  6450. if (len > INT_MAX)
  6451. len = INT_MAX;
  6452. val = to_be_freed = xstrndup(val + beg, len);
  6453. }
  6454. debug_printf_varexp("val:'%s'\n", val);
  6455. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6456. msg_and_die_if_script("malformed ${%s:...}", var);
  6457. val = NULL;
  6458. #endif
  6459. } else { /* one of "-=+?" */
  6460. /* Standard-mandated substitution ops:
  6461. * ${var?word} - indicate error if unset
  6462. * If var is unset, word (or a message indicating it is unset
  6463. * if word is null) is written to standard error
  6464. * and the shell exits with a non-zero exit status.
  6465. * Otherwise, the value of var is substituted.
  6466. * ${var-word} - use default value
  6467. * If var is unset, word is substituted.
  6468. * ${var=word} - assign and use default value
  6469. * If var is unset, word is assigned to var.
  6470. * In all cases, final value of var is substituted.
  6471. * ${var+word} - use alternative value
  6472. * If var is unset, null is substituted.
  6473. * Otherwise, word is substituted.
  6474. *
  6475. * Word is subjected to tilde expansion, parameter expansion,
  6476. * command substitution, and arithmetic expansion.
  6477. * If word is not needed, it is not expanded.
  6478. *
  6479. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6480. * but also treat null var as if it is unset.
  6481. *
  6482. * Word-splitting and single quote behavior:
  6483. *
  6484. * $ f() { for i; do echo "|$i|"; done; }
  6485. *
  6486. * $ x=; f ${x:?'x y' z}; echo $?
  6487. * bash: x: x y z # neither f nor "echo $?" executes
  6488. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6489. * $ x=; f "${x:?'x y' z}"
  6490. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6491. *
  6492. * $ x=; f ${x:='x y' z}
  6493. * |x|
  6494. * |y|
  6495. * |z|
  6496. * $ x=; f "${x:='x y' z}"
  6497. * |'x y' z|
  6498. *
  6499. * $ x=x; f ${x:+'x y' z}
  6500. * |x y|
  6501. * |z|
  6502. * $ x=x; f "${x:+'x y' z}"
  6503. * |'x y' z|
  6504. *
  6505. * $ x=; f ${x:-'x y' z}
  6506. * |x y|
  6507. * |z|
  6508. * $ x=; f "${x:-'x y' z}"
  6509. * |'x y' z|
  6510. */
  6511. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6512. if (exp_op == '+')
  6513. use_word = !use_word;
  6514. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6515. (exp_save == ':') ? "true" : "false", use_word);
  6516. if (use_word) {
  6517. if (exp_op == '+' || exp_op == '-') {
  6518. /* ${var+word} - use alternative value */
  6519. /* ${var-word} - use default value */
  6520. n = encode_then_append_var_plusminus(output, n, exp_word,
  6521. /*dquoted:*/ (arg0 & 0x80)
  6522. );
  6523. val = NULL;
  6524. } else {
  6525. /* ${var?word} - indicate error if unset */
  6526. /* ${var=word} - assign and use default value */
  6527. to_be_freed = encode_then_expand_vararg(exp_word,
  6528. /*handle_squotes:*/ !(arg0 & 0x80),
  6529. /*unbackslash:*/ 0
  6530. );
  6531. if (to_be_freed)
  6532. exp_word = to_be_freed;
  6533. if (exp_op == '?') {
  6534. /* mimic bash message */
  6535. msg_and_die_if_script("%s: %s",
  6536. var,
  6537. exp_word[0]
  6538. ? exp_word
  6539. : "parameter null or not set"
  6540. /* ash has more specific messages, a-la: */
  6541. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6542. );
  6543. //TODO: how interactive bash aborts expansion mid-command?
  6544. //It aborts the entire line, returns to prompt:
  6545. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6546. // bash: x: x y z
  6547. // $
  6548. // ("echo YO" is not executed, neither the f function call)
  6549. } else {
  6550. val = exp_word;
  6551. }
  6552. if (exp_op == '=') {
  6553. /* ${var=[word]} or ${var:=[word]} */
  6554. if (isdigit(var[0]) || var[0] == '#') {
  6555. /* mimic bash message */
  6556. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6557. val = NULL;
  6558. } else {
  6559. char *new_var = xasprintf("%s=%s", var, val);
  6560. set_local_var0(new_var);
  6561. }
  6562. }
  6563. }
  6564. }
  6565. } /* one of "-=+?" */
  6566. *exp_saveptr = exp_save;
  6567. } /* if (exp_op) */
  6568. arg[0] = arg0;
  6569. *pp = p;
  6570. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6571. free(to_be_freed);
  6572. return n;
  6573. }
  6574. /* Expand all variable references in given string, adding words to list[]
  6575. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6576. * to be filled). This routine is extremely tricky: has to deal with
  6577. * variables/parameters with whitespace, $* and $@, and constructs like
  6578. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6579. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6580. {
  6581. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6582. * expansion of right-hand side of assignment == 1-element expand.
  6583. */
  6584. char cant_be_null = 0; /* only bit 0x80 matters */
  6585. char *p;
  6586. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6587. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6588. debug_print_list("expand_vars_to_list[0]", output, n);
  6589. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6590. char first_ch;
  6591. #if ENABLE_FEATURE_SH_MATH
  6592. char arith_buf[sizeof(arith_t)*3 + 2];
  6593. #endif
  6594. if (output->ended_in_ifs) {
  6595. o_addchr(output, '\0');
  6596. n = o_save_ptr(output, n);
  6597. output->ended_in_ifs = 0;
  6598. }
  6599. o_addblock(output, arg, p - arg);
  6600. debug_print_list("expand_vars_to_list[1]", output, n);
  6601. arg = ++p;
  6602. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6603. /* Fetch special var name (if it is indeed one of them)
  6604. * and quote bit, force the bit on if singleword expansion -
  6605. * important for not getting v=$@ expand to many words. */
  6606. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6607. /* Is this variable quoted and thus expansion can't be null?
  6608. * "$@" is special. Even if quoted, it can still
  6609. * expand to nothing (not even an empty string),
  6610. * thus it is excluded. */
  6611. if ((first_ch & 0x7f) != '@')
  6612. cant_be_null |= first_ch;
  6613. switch (first_ch & 0x7f) {
  6614. /* Highest bit in first_ch indicates that var is double-quoted */
  6615. case '*':
  6616. case '@': {
  6617. int i;
  6618. if (!G.global_argv[1])
  6619. break;
  6620. i = 1;
  6621. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6622. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6623. while (G.global_argv[i]) {
  6624. n = expand_on_ifs(output, n, G.global_argv[i]);
  6625. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6626. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6627. /* this argv[] is not empty and not last:
  6628. * put terminating NUL, start new word */
  6629. o_addchr(output, '\0');
  6630. debug_print_list("expand_vars_to_list[2]", output, n);
  6631. n = o_save_ptr(output, n);
  6632. debug_print_list("expand_vars_to_list[3]", output, n);
  6633. }
  6634. }
  6635. } else
  6636. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6637. * and in this case should treat it like '$*' - see 'else...' below */
  6638. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6639. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6640. ) {
  6641. while (1) {
  6642. o_addQstr(output, G.global_argv[i]);
  6643. if (++i >= G.global_argc)
  6644. break;
  6645. o_addchr(output, '\0');
  6646. debug_print_list("expand_vars_to_list[4]", output, n);
  6647. n = o_save_ptr(output, n);
  6648. }
  6649. } else { /* quoted $* (or v="$@" case): add as one word */
  6650. while (1) {
  6651. o_addQstr(output, G.global_argv[i]);
  6652. if (!G.global_argv[++i])
  6653. break;
  6654. if (G.ifs[0])
  6655. o_addchr(output, G.ifs[0]);
  6656. }
  6657. output->has_quoted_part = 1;
  6658. }
  6659. break;
  6660. }
  6661. case SPECIAL_VAR_SYMBOL: {
  6662. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6663. /* "Empty variable", used to make "" etc to not disappear */
  6664. output->has_quoted_part = 1;
  6665. cant_be_null = 0x80;
  6666. arg++;
  6667. break;
  6668. }
  6669. case SPECIAL_VAR_QUOTED_SVS:
  6670. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6671. /* "^C variable", represents literal ^C char (possible in scripts) */
  6672. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6673. arg++;
  6674. break;
  6675. #if ENABLE_HUSH_TICK
  6676. case '`': {
  6677. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6678. o_string subst_result = NULL_O_STRING;
  6679. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6680. arg++;
  6681. /* Can't just stuff it into output o_string,
  6682. * expanded result may need to be globbed
  6683. * and $IFS-split */
  6684. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6685. G.last_exitcode = process_command_subs(&subst_result, arg);
  6686. G.expand_exitcode = G.last_exitcode;
  6687. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6688. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6689. o_free(&subst_result);
  6690. break;
  6691. }
  6692. #endif
  6693. #if ENABLE_FEATURE_SH_MATH
  6694. case '+': {
  6695. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6696. arith_t res;
  6697. arg++; /* skip '+' */
  6698. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6699. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6700. res = expand_and_evaluate_arith(arg, NULL);
  6701. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6702. sprintf(arith_buf, ARITH_FMT, res);
  6703. if (res < 0
  6704. && first_ch == (char)('+'|0x80)
  6705. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6706. ) {
  6707. /* Quoted negative ariths, like filename[0"$((-9))"],
  6708. * should not be interpreted as glob ranges.
  6709. * Convert leading '-' to '\-':
  6710. */
  6711. o_grow_by(output, 1);
  6712. output->data[output->length++] = '\\';
  6713. }
  6714. o_addstr(output, arith_buf);
  6715. break;
  6716. }
  6717. #endif
  6718. default:
  6719. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6720. n = expand_one_var(output, n, first_ch, arg, &p);
  6721. break;
  6722. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6723. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6724. * Do the check to avoid writing to a const string. */
  6725. if (*p != SPECIAL_VAR_SYMBOL)
  6726. *p = SPECIAL_VAR_SYMBOL;
  6727. arg = ++p;
  6728. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6729. if (*arg) {
  6730. /* handle trailing string */
  6731. if (output->ended_in_ifs) {
  6732. o_addchr(output, '\0');
  6733. n = o_save_ptr(output, n);
  6734. }
  6735. debug_print_list("expand_vars_to_list[a]", output, n);
  6736. /* this part is literal, and it was already pre-quoted
  6737. * if needed (much earlier), do not use o_addQstr here!
  6738. */
  6739. o_addstr(output, arg);
  6740. debug_print_list("expand_vars_to_list[b]", output, n);
  6741. } else
  6742. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6743. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6744. && !output->has_quoted_part
  6745. ) {
  6746. n--;
  6747. /* allow to reuse list[n] later without re-growth */
  6748. output->has_empty_slot = 1;
  6749. }
  6750. return n;
  6751. }
  6752. static char **expand_variables(char **argv, unsigned expflags)
  6753. {
  6754. int n;
  6755. char **list;
  6756. o_string output = NULL_O_STRING;
  6757. output.o_expflags = expflags;
  6758. n = 0;
  6759. for (;;) {
  6760. /* go to next list[n] */
  6761. output.ended_in_ifs = 0;
  6762. n = o_save_ptr(&output, n);
  6763. if (!*argv)
  6764. break;
  6765. /* expand argv[i] */
  6766. n = expand_vars_to_list(&output, n, *argv++);
  6767. /* if (!output->has_empty_slot) -- need this?? */
  6768. o_addchr(&output, '\0');
  6769. }
  6770. debug_print_list("expand_variables", &output, n);
  6771. /* output.data (malloced in one block) gets returned in "list" */
  6772. list = o_finalize_list(&output, n);
  6773. debug_print_strings("expand_variables[1]", list);
  6774. return list;
  6775. }
  6776. static char **expand_strvec_to_strvec(char **argv)
  6777. {
  6778. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6779. }
  6780. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6781. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6782. {
  6783. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6784. }
  6785. #endif
  6786. /* Used for expansion of right hand of assignments,
  6787. * $((...)), heredocs, variable expansion parts.
  6788. *
  6789. * NB: should NOT do globbing!
  6790. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6791. */
  6792. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6793. {
  6794. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6795. const int do_unbackslash = 1;
  6796. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6797. #endif
  6798. char *argv[2], **list;
  6799. debug_printf_expand("string_to_string<='%s'\n", str);
  6800. /* This is generally an optimization, but it also
  6801. * handles "", which otherwise trips over !list[0] check below.
  6802. * (is this ever happens that we actually get str="" here?)
  6803. */
  6804. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6805. //TODO: Can use on strings with \ too, just unbackslash() them?
  6806. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6807. return xstrdup(str);
  6808. }
  6809. argv[0] = (char*)str;
  6810. argv[1] = NULL;
  6811. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6812. if (!list[0]) {
  6813. /* Example where it happens:
  6814. * x=; echo ${x:-"$@"}
  6815. */
  6816. ((char*)list)[0] = '\0';
  6817. } else {
  6818. if (HUSH_DEBUG)
  6819. if (list[1])
  6820. bb_simple_error_msg_and_die("BUG in varexp2");
  6821. /* actually, just move string 2*sizeof(char*) bytes back */
  6822. overlapping_strcpy((char*)list, list[0]);
  6823. if (do_unbackslash)
  6824. unbackslash((char*)list);
  6825. }
  6826. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6827. return (char*)list;
  6828. }
  6829. #if 0
  6830. static char* expand_strvec_to_string(char **argv)
  6831. {
  6832. char **list;
  6833. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6834. /* Convert all NULs to spaces */
  6835. if (list[0]) {
  6836. int n = 1;
  6837. while (list[n]) {
  6838. if (HUSH_DEBUG)
  6839. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6840. bb_error_msg_and_die("BUG in varexp3");
  6841. /* bash uses ' ' regardless of $IFS contents */
  6842. list[n][-1] = ' ';
  6843. n++;
  6844. }
  6845. }
  6846. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6847. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6848. return (char*)list;
  6849. }
  6850. #endif
  6851. static char **expand_assignments(char **argv, int count)
  6852. {
  6853. int i;
  6854. char **p;
  6855. G.expanded_assignments = p = NULL;
  6856. /* Expand assignments into one string each */
  6857. for (i = 0; i < count; i++) {
  6858. p = add_string_to_strings(p,
  6859. expand_string_to_string(argv[i],
  6860. EXP_FLAG_ESC_GLOB_CHARS,
  6861. /*unbackslash:*/ 1
  6862. )
  6863. );
  6864. G.expanded_assignments = p;
  6865. }
  6866. G.expanded_assignments = NULL;
  6867. return p;
  6868. }
  6869. static void switch_off_special_sigs(unsigned mask)
  6870. {
  6871. unsigned sig = 0;
  6872. while ((mask >>= 1) != 0) {
  6873. sig++;
  6874. if (!(mask & 1))
  6875. continue;
  6876. #if ENABLE_HUSH_TRAP
  6877. if (G_traps) {
  6878. if (G_traps[sig] && !G_traps[sig][0])
  6879. /* trap is '', has to remain SIG_IGN */
  6880. continue;
  6881. free(G_traps[sig]);
  6882. G_traps[sig] = NULL;
  6883. }
  6884. #endif
  6885. /* We are here only if no trap or trap was not '' */
  6886. install_sighandler(sig, SIG_DFL);
  6887. }
  6888. }
  6889. #if BB_MMU
  6890. /* never called */
  6891. void re_execute_shell(char ***to_free, const char *s,
  6892. char *g_argv0, char **g_argv,
  6893. char **builtin_argv) NORETURN;
  6894. static void reset_traps_to_defaults(void)
  6895. {
  6896. /* This function is always called in a child shell
  6897. * after fork (not vfork, NOMMU doesn't use this function).
  6898. */
  6899. IF_HUSH_TRAP(unsigned sig;)
  6900. unsigned mask;
  6901. /* Child shells are not interactive.
  6902. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6903. * Testcase: (while :; do :; done) + ^Z should background.
  6904. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6905. */
  6906. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6907. if (!G_traps && !mask)
  6908. return; /* already no traps and no special sigs */
  6909. /* Switch off special sigs */
  6910. switch_off_special_sigs(mask);
  6911. # if ENABLE_HUSH_JOB
  6912. G_fatal_sig_mask = 0;
  6913. # endif
  6914. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6915. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6916. * remain set in G.special_sig_mask */
  6917. # if ENABLE_HUSH_TRAP
  6918. if (!G_traps)
  6919. return;
  6920. /* Reset all sigs to default except ones with empty traps */
  6921. for (sig = 0; sig < NSIG; sig++) {
  6922. if (!G_traps[sig])
  6923. continue; /* no trap: nothing to do */
  6924. if (!G_traps[sig][0])
  6925. continue; /* empty trap: has to remain SIG_IGN */
  6926. /* sig has non-empty trap, reset it: */
  6927. free(G_traps[sig]);
  6928. G_traps[sig] = NULL;
  6929. /* There is no signal for trap 0 (EXIT) */
  6930. if (sig == 0)
  6931. continue;
  6932. install_sighandler(sig, pick_sighandler(sig));
  6933. }
  6934. # endif
  6935. }
  6936. #else /* !BB_MMU */
  6937. static void re_execute_shell(char ***to_free, const char *s,
  6938. char *g_argv0, char **g_argv,
  6939. char **builtin_argv) NORETURN;
  6940. static void re_execute_shell(char ***to_free, const char *s,
  6941. char *g_argv0, char **g_argv,
  6942. char **builtin_argv)
  6943. {
  6944. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6945. /* delims + 2 * (number of bytes in printed hex numbers) */
  6946. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6947. char *heredoc_argv[4];
  6948. struct variable *cur;
  6949. # if ENABLE_HUSH_FUNCTIONS
  6950. struct function *funcp;
  6951. # endif
  6952. char **argv, **pp;
  6953. unsigned cnt;
  6954. unsigned long long empty_trap_mask;
  6955. if (!g_argv0) { /* heredoc */
  6956. argv = heredoc_argv;
  6957. argv[0] = (char *) G.argv0_for_re_execing;
  6958. argv[1] = (char *) "-<";
  6959. argv[2] = (char *) s;
  6960. argv[3] = NULL;
  6961. pp = &argv[3]; /* used as pointer to empty environment */
  6962. goto do_exec;
  6963. }
  6964. cnt = 0;
  6965. pp = builtin_argv;
  6966. if (pp) while (*pp++)
  6967. cnt++;
  6968. empty_trap_mask = 0;
  6969. if (G_traps) {
  6970. int sig;
  6971. for (sig = 1; sig < NSIG; sig++) {
  6972. if (G_traps[sig] && !G_traps[sig][0])
  6973. empty_trap_mask |= 1LL << sig;
  6974. }
  6975. }
  6976. sprintf(param_buf, NOMMU_HACK_FMT
  6977. , (unsigned) G.root_pid
  6978. , (unsigned) G.root_ppid
  6979. , (unsigned) G.last_bg_pid
  6980. , (unsigned) G.last_exitcode
  6981. , cnt
  6982. , empty_trap_mask
  6983. IF_HUSH_LOOPS(, G.depth_of_loop)
  6984. );
  6985. # undef NOMMU_HACK_FMT
  6986. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6987. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6988. */
  6989. cnt += 6;
  6990. for (cur = G.top_var; cur; cur = cur->next) {
  6991. if (!cur->flg_export || cur->flg_read_only)
  6992. cnt += 2;
  6993. }
  6994. # if ENABLE_HUSH_FUNCTIONS
  6995. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6996. cnt += 3;
  6997. # endif
  6998. pp = g_argv;
  6999. while (*pp++)
  7000. cnt++;
  7001. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  7002. *pp++ = (char *) G.argv0_for_re_execing;
  7003. *pp++ = param_buf;
  7004. for (cur = G.top_var; cur; cur = cur->next) {
  7005. if (strcmp(cur->varstr, hush_version_str) == 0)
  7006. continue;
  7007. if (cur->flg_read_only) {
  7008. *pp++ = (char *) "-R";
  7009. *pp++ = cur->varstr;
  7010. } else if (!cur->flg_export) {
  7011. *pp++ = (char *) "-V";
  7012. *pp++ = cur->varstr;
  7013. }
  7014. }
  7015. # if ENABLE_HUSH_FUNCTIONS
  7016. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7017. *pp++ = (char *) "-F";
  7018. *pp++ = funcp->name;
  7019. *pp++ = funcp->body_as_string;
  7020. }
  7021. # endif
  7022. /* We can pass activated traps here. Say, -Tnn:trap_string
  7023. *
  7024. * However, POSIX says that subshells reset signals with traps
  7025. * to SIG_DFL.
  7026. * I tested bash-3.2 and it not only does that with true subshells
  7027. * of the form ( list ), but with any forked children shells.
  7028. * I set trap "echo W" WINCH; and then tried:
  7029. *
  7030. * { echo 1; sleep 20; echo 2; } &
  7031. * while true; do echo 1; sleep 20; echo 2; break; done &
  7032. * true | { echo 1; sleep 20; echo 2; } | cat
  7033. *
  7034. * In all these cases sending SIGWINCH to the child shell
  7035. * did not run the trap. If I add trap "echo V" WINCH;
  7036. * _inside_ group (just before echo 1), it works.
  7037. *
  7038. * I conclude it means we don't need to pass active traps here.
  7039. */
  7040. *pp++ = (char *) "-c";
  7041. *pp++ = (char *) s;
  7042. if (builtin_argv) {
  7043. while (*++builtin_argv)
  7044. *pp++ = *builtin_argv;
  7045. *pp++ = (char *) "";
  7046. }
  7047. *pp++ = g_argv0;
  7048. while (*g_argv)
  7049. *pp++ = *g_argv++;
  7050. /* *pp = NULL; - is already there */
  7051. pp = environ;
  7052. do_exec:
  7053. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7054. /* Don't propagate SIG_IGN to the child */
  7055. if (SPECIAL_JOBSTOP_SIGS != 0)
  7056. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7057. execve(bb_busybox_exec_path, argv, pp);
  7058. /* Fallback. Useful for init=/bin/hush usage etc */
  7059. if (argv[0][0] == '/')
  7060. execve(argv[0], argv, pp);
  7061. xfunc_error_retval = 127;
  7062. bb_simple_error_msg_and_die("can't re-execute the shell");
  7063. }
  7064. #endif /* !BB_MMU */
  7065. static int run_and_free_list(struct pipe *pi);
  7066. /* Executing from string: eval, sh -c '...'
  7067. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7068. * end_trigger controls how often we stop parsing
  7069. * NUL: parse all, execute, return
  7070. * ';': parse till ';' or newline, execute, repeat till EOF
  7071. */
  7072. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7073. {
  7074. /* Why we need empty flag?
  7075. * An obscure corner case "false; ``; echo $?":
  7076. * empty command in `` should still set $? to 0.
  7077. * But we can't just set $? to 0 at the start,
  7078. * this breaks "false; echo `echo $?`" case.
  7079. */
  7080. bool empty = 1;
  7081. while (1) {
  7082. struct pipe *pipe_list;
  7083. #if ENABLE_HUSH_INTERACTIVE
  7084. if (end_trigger == ';') {
  7085. G.promptmode = 0; /* PS1 */
  7086. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7087. }
  7088. #endif
  7089. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7090. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7091. /* If we are in "big" script
  7092. * (not in `cmd` or something similar)...
  7093. */
  7094. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7095. /* Discard cached input (rest of line) */
  7096. int ch = inp->last_char;
  7097. while (ch != EOF && ch != '\n') {
  7098. //bb_error_msg("Discarded:'%c'", ch);
  7099. ch = i_getch(inp);
  7100. }
  7101. /* Force prompt */
  7102. inp->p = NULL;
  7103. /* This stream isn't empty */
  7104. empty = 0;
  7105. continue;
  7106. }
  7107. if (!pipe_list && empty)
  7108. G.last_exitcode = 0;
  7109. break;
  7110. }
  7111. debug_print_tree(pipe_list, 0);
  7112. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7113. run_and_free_list(pipe_list);
  7114. empty = 0;
  7115. if (G_flag_return_in_progress == 1)
  7116. break;
  7117. }
  7118. }
  7119. static void parse_and_run_string(const char *s)
  7120. {
  7121. struct in_str input;
  7122. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7123. setup_string_in_str(&input, s);
  7124. parse_and_run_stream(&input, '\0');
  7125. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7126. }
  7127. static void parse_and_run_file(HFILE *fp)
  7128. {
  7129. struct in_str input;
  7130. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7131. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7132. setup_file_in_str(&input, fp);
  7133. parse_and_run_stream(&input, ';');
  7134. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7135. }
  7136. #if ENABLE_HUSH_TICK
  7137. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7138. {
  7139. pid_t pid;
  7140. int channel[2];
  7141. # if !BB_MMU
  7142. char **to_free = NULL;
  7143. # endif
  7144. xpipe(channel);
  7145. pid = BB_MMU ? xfork() : xvfork();
  7146. if (pid == 0) { /* child */
  7147. disable_restore_tty_pgrp_on_exit();
  7148. /* Process substitution is not considered to be usual
  7149. * 'command execution'.
  7150. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7151. */
  7152. bb_signals(0
  7153. + (1 << SIGTSTP)
  7154. + (1 << SIGTTIN)
  7155. + (1 << SIGTTOU)
  7156. , SIG_IGN);
  7157. close(channel[0]); /* NB: close _first_, then move fd! */
  7158. xmove_fd(channel[1], 1);
  7159. # if ENABLE_HUSH_TRAP
  7160. /* Awful hack for `trap` or $(trap).
  7161. *
  7162. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7163. * contains an example where "trap" is executed in a subshell:
  7164. *
  7165. * save_traps=$(trap)
  7166. * ...
  7167. * eval "$save_traps"
  7168. *
  7169. * Standard does not say that "trap" in subshell shall print
  7170. * parent shell's traps. It only says that its output
  7171. * must have suitable form, but then, in the above example
  7172. * (which is not supposed to be normative), it implies that.
  7173. *
  7174. * bash (and probably other shell) does implement it
  7175. * (traps are reset to defaults, but "trap" still shows them),
  7176. * but as a result, "trap" logic is hopelessly messed up:
  7177. *
  7178. * # trap
  7179. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7180. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7181. * # true | trap <--- trap is in subshell - no output (ditto)
  7182. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7183. * trap -- 'echo Ho' SIGWINCH
  7184. * # echo `(trap)` <--- in subshell in subshell - output
  7185. * trap -- 'echo Ho' SIGWINCH
  7186. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7187. * trap -- 'echo Ho' SIGWINCH
  7188. *
  7189. * The rules when to forget and when to not forget traps
  7190. * get really complex and nonsensical.
  7191. *
  7192. * Our solution: ONLY bare $(trap) or `trap` is special.
  7193. */
  7194. s = skip_whitespace(s);
  7195. if (is_prefixed_with(s, "trap")
  7196. && skip_whitespace(s + 4)[0] == '\0'
  7197. ) {
  7198. static const char *const argv[] ALIGN_PTR = { NULL, NULL };
  7199. builtin_trap((char**)argv);
  7200. fflush_all(); /* important */
  7201. _exit(0);
  7202. }
  7203. # endif
  7204. # if BB_MMU
  7205. /* Prevent it from trying to handle ctrl-z etc */
  7206. IF_HUSH_JOB(G.run_list_level = 1;)
  7207. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7208. reset_traps_to_defaults();
  7209. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7210. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7211. parse_and_run_string(s);
  7212. _exit(G.last_exitcode);
  7213. # else
  7214. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7215. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7216. * huge=`cat BIG` # was blocking here forever
  7217. * echo OK
  7218. */
  7219. re_execute_shell(&to_free,
  7220. s,
  7221. G.global_argv[0],
  7222. G.global_argv + 1,
  7223. NULL);
  7224. # endif
  7225. }
  7226. /* parent */
  7227. *pid_p = pid;
  7228. # if ENABLE_HUSH_FAST
  7229. G.count_SIGCHLD++;
  7230. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7231. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7232. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7233. # endif
  7234. enable_restore_tty_pgrp_on_exit();
  7235. # if !BB_MMU
  7236. free(to_free);
  7237. # endif
  7238. close(channel[1]);
  7239. return channel[0];
  7240. }
  7241. /* Return code is exit status of the process that is run. */
  7242. static int process_command_subs(o_string *dest, const char *s)
  7243. {
  7244. FILE *fp;
  7245. pid_t pid;
  7246. int status, ch, eol_cnt;
  7247. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7248. /* Now send results of command back into original context */
  7249. eol_cnt = 0;
  7250. while ((ch = getc(fp)) != EOF) {
  7251. if (ch == '\0')
  7252. continue;
  7253. if (ch == '\n') {
  7254. eol_cnt++;
  7255. continue;
  7256. }
  7257. while (eol_cnt) {
  7258. o_addchr(dest, '\n');
  7259. eol_cnt--;
  7260. }
  7261. o_addQchr(dest, ch);
  7262. }
  7263. debug_printf("done reading from `cmd` pipe, closing it\n");
  7264. fclose(fp);
  7265. /* We need to extract exitcode. Test case
  7266. * "true; echo `sleep 1; false` $?"
  7267. * should print 1 */
  7268. safe_waitpid(pid, &status, 0);
  7269. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7270. return WEXITSTATUS(status);
  7271. }
  7272. #endif /* ENABLE_HUSH_TICK */
  7273. static void setup_heredoc(struct redir_struct *redir)
  7274. {
  7275. struct fd_pair pair;
  7276. pid_t pid;
  7277. int len, written;
  7278. /* the _body_ of heredoc (misleading field name) */
  7279. const char *heredoc = redir->rd_filename;
  7280. char *expanded;
  7281. #if !BB_MMU
  7282. char **to_free;
  7283. #endif
  7284. expanded = NULL;
  7285. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7286. expanded = encode_then_expand_string(heredoc);
  7287. if (expanded)
  7288. heredoc = expanded;
  7289. }
  7290. len = strlen(heredoc);
  7291. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7292. xpiped_pair(pair);
  7293. xmove_fd(pair.rd, redir->rd_fd);
  7294. /* Try writing without forking. Newer kernels have
  7295. * dynamically growing pipes. Must use non-blocking write! */
  7296. ndelay_on(pair.wr);
  7297. while (1) {
  7298. written = write(pair.wr, heredoc, len);
  7299. if (written <= 0)
  7300. break;
  7301. len -= written;
  7302. if (len == 0) {
  7303. close(pair.wr);
  7304. free(expanded);
  7305. return;
  7306. }
  7307. heredoc += written;
  7308. }
  7309. ndelay_off(pair.wr);
  7310. /* Okay, pipe buffer was not big enough */
  7311. /* Note: we must not create a stray child (bastard? :)
  7312. * for the unsuspecting parent process. Child creates a grandchild
  7313. * and exits before parent execs the process which consumes heredoc
  7314. * (that exec happens after we return from this function) */
  7315. #if !BB_MMU
  7316. to_free = NULL;
  7317. #endif
  7318. pid = xvfork();
  7319. if (pid == 0) {
  7320. /* child */
  7321. disable_restore_tty_pgrp_on_exit();
  7322. pid = BB_MMU ? xfork() : xvfork();
  7323. if (pid != 0)
  7324. _exit(0);
  7325. /* grandchild */
  7326. close(redir->rd_fd); /* read side of the pipe */
  7327. #if BB_MMU
  7328. full_write(pair.wr, heredoc, len); /* may loop or block */
  7329. _exit(0);
  7330. #else
  7331. /* Delegate blocking writes to another process */
  7332. xmove_fd(pair.wr, STDOUT_FILENO);
  7333. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7334. #endif
  7335. }
  7336. /* parent */
  7337. #if ENABLE_HUSH_FAST
  7338. G.count_SIGCHLD++;
  7339. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7340. #endif
  7341. enable_restore_tty_pgrp_on_exit();
  7342. #if !BB_MMU
  7343. free(to_free);
  7344. #endif
  7345. close(pair.wr);
  7346. free(expanded);
  7347. wait(NULL); /* wait till child has died */
  7348. }
  7349. struct squirrel {
  7350. int orig_fd;
  7351. int moved_to;
  7352. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7353. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7354. };
  7355. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7356. {
  7357. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7358. sq[i].orig_fd = orig;
  7359. sq[i].moved_to = moved;
  7360. sq[i+1].orig_fd = -1; /* end marker */
  7361. return sq;
  7362. }
  7363. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7364. {
  7365. int moved_to;
  7366. int i;
  7367. i = 0;
  7368. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7369. /* If we collide with an already moved fd... */
  7370. if (fd == sq[i].moved_to) {
  7371. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7372. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7373. if (sq[i].moved_to < 0) /* what? */
  7374. xfunc_die();
  7375. return sq;
  7376. }
  7377. if (fd == sq[i].orig_fd) {
  7378. /* Example: echo Hello >/dev/null 1>&2 */
  7379. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7380. return sq;
  7381. }
  7382. }
  7383. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7384. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7385. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7386. if (moved_to < 0 && errno != EBADF)
  7387. xfunc_die();
  7388. return append_squirrel(sq, i, fd, moved_to);
  7389. }
  7390. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7391. {
  7392. int i;
  7393. i = 0;
  7394. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7395. /* If we collide with an already moved fd... */
  7396. if (fd == sq[i].orig_fd) {
  7397. /* Examples:
  7398. * "echo 3>FILE 3>&- 3>FILE"
  7399. * "echo 3>&- 3>FILE"
  7400. * No need for last redirect to insert
  7401. * another "need to close 3" indicator.
  7402. */
  7403. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7404. return sq;
  7405. }
  7406. }
  7407. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7408. return append_squirrel(sq, i, fd, -1);
  7409. }
  7410. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7411. * Move all conflicting internally used fds,
  7412. * and remember them so that we can restore them later.
  7413. */
  7414. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7415. {
  7416. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7417. avoid_fd = 9;
  7418. #if ENABLE_HUSH_INTERACTIVE
  7419. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7420. && fd == G_interactive_fd
  7421. ) {
  7422. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7423. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7424. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7425. return 1; /* "we closed fd" */
  7426. }
  7427. #endif
  7428. /* Are we called from setup_redirects(squirrel==NULL)
  7429. * in redirect in a [v]forked child?
  7430. */
  7431. if (sqp == NULL) {
  7432. /* No need to move script fds.
  7433. * For NOMMU case, it's actively wrong: we'd change ->fd
  7434. * fields in memory for the parent, but parent's fds
  7435. * aren't moved, it would use wrong fd!
  7436. * Reproducer: "cmd 3>FILE" in script.
  7437. * If we would call move_HFILEs_on_redirect(), child would:
  7438. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7439. * close(3) = 0
  7440. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7441. */
  7442. //bb_error_msg("sqp == NULL: [v]forked child");
  7443. return 0;
  7444. }
  7445. /* If this one of script's fds? */
  7446. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7447. return 1; /* yes. "we closed fd" (actually moved it) */
  7448. /* Are we called for "exec 3>FILE"? Came through
  7449. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7450. * This case used to fail for this script:
  7451. * exec 3>FILE
  7452. * echo Ok
  7453. * ...100000 more lines...
  7454. * echo Ok
  7455. * as follows:
  7456. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7457. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7458. * dup2(4, 3) = 3
  7459. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7460. * close(4) = 0
  7461. * write(1, "Ok\n", 3) = 3
  7462. * ... = 3
  7463. * write(1, "Ok\n", 3) = 3
  7464. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7465. * ^^^^^^^^ oops, wrong fd!!!
  7466. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7467. * it now works:
  7468. */
  7469. if (sqp == ERR_PTR) {
  7470. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7471. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7472. return 0;
  7473. }
  7474. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7475. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7476. return 0; /* "we did not close fd" */
  7477. }
  7478. static void restore_redirects(struct squirrel *sq)
  7479. {
  7480. if (sq) {
  7481. int i;
  7482. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7483. if (sq[i].moved_to >= 0) {
  7484. /* We simply die on error */
  7485. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7486. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7487. } else {
  7488. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7489. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7490. close(sq[i].orig_fd);
  7491. }
  7492. }
  7493. free(sq);
  7494. }
  7495. if (G.HFILE_stdin
  7496. && G.HFILE_stdin->fd > STDIN_FILENO
  7497. /* we compare > STDIN, not == STDIN, since hfgetc()
  7498. * closes fd and sets ->fd to -1 if EOF is reached.
  7499. * Testcase: echo 'pwd' | hush
  7500. */
  7501. ) {
  7502. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7503. * Redirect moves ->fd to e.g. 10,
  7504. * and it is not restored above (we do not restore script fds
  7505. * after redirects, we just use new, "moved" fds).
  7506. * However for stdin, get_user_input() -> read_line_input(),
  7507. * and read builtin, depend on fd == STDIN_FILENO.
  7508. */
  7509. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7510. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7511. G.HFILE_stdin->fd = STDIN_FILENO;
  7512. }
  7513. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7514. }
  7515. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7516. static void close_saved_fds_and_FILE_fds(void)
  7517. {
  7518. if (G_interactive_fd)
  7519. close(G_interactive_fd);
  7520. close_all_HFILE_list();
  7521. }
  7522. #endif
  7523. static int internally_opened_fd(int fd, struct squirrel *sq)
  7524. {
  7525. int i;
  7526. #if ENABLE_HUSH_INTERACTIVE
  7527. if (fd == G_interactive_fd)
  7528. return 1;
  7529. #endif
  7530. /* If this one of script's fds? */
  7531. if (fd_in_HFILEs(fd))
  7532. return 1;
  7533. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7534. if (fd == sq[i].moved_to)
  7535. return 1;
  7536. }
  7537. return 0;
  7538. }
  7539. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7540. * and stderr if they are redirected. */
  7541. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7542. {
  7543. struct redir_struct *redir;
  7544. for (redir = prog->redirects; redir; redir = redir->next) {
  7545. int newfd;
  7546. int closed;
  7547. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7548. /* "rd_fd<<HERE" case */
  7549. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7550. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7551. * of the heredoc */
  7552. debug_printf_redir("set heredoc '%s'\n",
  7553. redir->rd_filename);
  7554. setup_heredoc(redir);
  7555. continue;
  7556. }
  7557. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7558. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7559. char *p;
  7560. int mode;
  7561. if (redir->rd_filename == NULL) {
  7562. /* Examples:
  7563. * "cmd >" (no filename)
  7564. * "cmd > <file" (2nd redirect starts too early)
  7565. */
  7566. syntax_error("invalid redirect");
  7567. continue;
  7568. }
  7569. mode = redir_table[redir->rd_type].mode;
  7570. p = expand_string_to_string(redir->rd_filename,
  7571. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7572. newfd = open_or_warn(p, mode);
  7573. free(p);
  7574. if (newfd < 0) {
  7575. /* Error message from open_or_warn can be lost
  7576. * if stderr has been redirected, but bash
  7577. * and ash both lose it as well
  7578. * (though zsh doesn't!)
  7579. */
  7580. return 1;
  7581. }
  7582. if (newfd == redir->rd_fd && sqp) {
  7583. /* open() gave us precisely the fd we wanted.
  7584. * This means that this fd was not busy
  7585. * (not opened to anywhere).
  7586. * Remember to close it on restore:
  7587. */
  7588. *sqp = add_squirrel_closed(*sqp, newfd);
  7589. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7590. }
  7591. } else {
  7592. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7593. newfd = redir->rd_dup;
  7594. }
  7595. if (newfd == redir->rd_fd)
  7596. continue;
  7597. /* if "N>FILE": move newfd to redir->rd_fd */
  7598. /* if "N>&M": dup newfd to redir->rd_fd */
  7599. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7600. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7601. if (newfd == REDIRFD_CLOSE) {
  7602. /* "N>&-" means "close me" */
  7603. if (!closed) {
  7604. /* ^^^ optimization: saving may already
  7605. * have closed it. If not... */
  7606. close(redir->rd_fd);
  7607. }
  7608. /* Sometimes we do another close on restore, getting EBADF.
  7609. * Consider "echo 3>FILE 3>&-"
  7610. * first redirect remembers "need to close 3",
  7611. * and second redirect closes 3! Restore code then closes 3 again.
  7612. */
  7613. } else {
  7614. /* if newfd is a script fd or saved fd, simulate EBADF */
  7615. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7616. //errno = EBADF;
  7617. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7618. newfd = -1; /* same effect as code above */
  7619. }
  7620. xdup2(newfd, redir->rd_fd);
  7621. if (redir->rd_dup == REDIRFD_TO_FILE)
  7622. /* "rd_fd > FILE" */
  7623. close(newfd);
  7624. /* else: "rd_fd > rd_dup" */
  7625. }
  7626. }
  7627. return 0;
  7628. }
  7629. static char *find_in_path(const char *arg)
  7630. {
  7631. char *ret = NULL;
  7632. const char *PATH = get_local_var_value("PATH");
  7633. if (!PATH)
  7634. return NULL;
  7635. while (1) {
  7636. const char *end = strchrnul(PATH, ':');
  7637. int sz = end - PATH; /* must be int! */
  7638. free(ret);
  7639. if (sz != 0) {
  7640. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7641. } else {
  7642. /* We have xxx::yyyy in $PATH,
  7643. * it means "use current dir" */
  7644. ret = xstrdup(arg);
  7645. }
  7646. if (access(ret, F_OK) == 0)
  7647. break;
  7648. if (*end == '\0') {
  7649. free(ret);
  7650. return NULL;
  7651. }
  7652. PATH = end + 1;
  7653. }
  7654. return ret;
  7655. }
  7656. static const struct built_in_command *find_builtin_helper(const char *name,
  7657. const struct built_in_command *x,
  7658. const struct built_in_command *end)
  7659. {
  7660. while (x != end) {
  7661. if (strcmp(name, x->b_cmd) != 0) {
  7662. x++;
  7663. continue;
  7664. }
  7665. debug_printf_exec("found builtin '%s'\n", name);
  7666. return x;
  7667. }
  7668. return NULL;
  7669. }
  7670. static const struct built_in_command *find_builtin1(const char *name)
  7671. {
  7672. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7673. }
  7674. static const struct built_in_command *find_builtin(const char *name)
  7675. {
  7676. const struct built_in_command *x = find_builtin1(name);
  7677. if (x)
  7678. return x;
  7679. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7680. }
  7681. #if ENABLE_HUSH_JOB && ENABLE_FEATURE_TAB_COMPLETION
  7682. static const char * FAST_FUNC get_builtin_name(int i)
  7683. {
  7684. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7685. return bltins1[i].b_cmd;
  7686. }
  7687. i -= ARRAY_SIZE(bltins1);
  7688. if (i < ARRAY_SIZE(bltins2)) {
  7689. return bltins2[i].b_cmd;
  7690. }
  7691. return NULL;
  7692. }
  7693. #endif
  7694. static void remove_nested_vars(void)
  7695. {
  7696. struct variable *cur;
  7697. struct variable **cur_pp;
  7698. cur_pp = &G.top_var;
  7699. while ((cur = *cur_pp) != NULL) {
  7700. if (cur->var_nest_level <= G.var_nest_level) {
  7701. cur_pp = &cur->next;
  7702. continue;
  7703. }
  7704. /* Unexport */
  7705. if (cur->flg_export) {
  7706. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7707. bb_unsetenv(cur->varstr);
  7708. }
  7709. /* Remove from global list */
  7710. *cur_pp = cur->next;
  7711. /* Free */
  7712. if (!cur->max_len) {
  7713. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7714. free(cur->varstr);
  7715. }
  7716. free(cur);
  7717. }
  7718. }
  7719. static void enter_var_nest_level(void)
  7720. {
  7721. G.var_nest_level++;
  7722. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7723. /* Try: f() { echo -n .; f; }; f
  7724. * struct variable::var_nest_level is uint16_t,
  7725. * thus limiting recursion to < 2^16.
  7726. * In any case, with 8 Mbyte stack SEGV happens
  7727. * not too long after 2^16 recursions anyway.
  7728. */
  7729. if (G.var_nest_level > 0xff00)
  7730. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7731. }
  7732. static void leave_var_nest_level(void)
  7733. {
  7734. G.var_nest_level--;
  7735. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7736. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7737. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7738. remove_nested_vars();
  7739. }
  7740. #if ENABLE_HUSH_FUNCTIONS
  7741. static struct function **find_function_slot(const char *name)
  7742. {
  7743. struct function *funcp;
  7744. struct function **funcpp = &G.top_func;
  7745. while ((funcp = *funcpp) != NULL) {
  7746. if (strcmp(name, funcp->name) == 0) {
  7747. debug_printf_exec("found function '%s'\n", name);
  7748. break;
  7749. }
  7750. funcpp = &funcp->next;
  7751. }
  7752. return funcpp;
  7753. }
  7754. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7755. {
  7756. const struct function *funcp = *find_function_slot(name);
  7757. return funcp;
  7758. }
  7759. /* Note: takes ownership on name ptr */
  7760. static struct function *new_function(char *name)
  7761. {
  7762. struct function **funcpp = find_function_slot(name);
  7763. struct function *funcp = *funcpp;
  7764. if (funcp != NULL) {
  7765. struct command *cmd = funcp->parent_cmd;
  7766. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7767. if (!cmd) {
  7768. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7769. free(funcp->name);
  7770. /* Note: if !funcp->body, do not free body_as_string!
  7771. * This is a special case of "-F name body" function:
  7772. * body_as_string was not malloced! */
  7773. if (funcp->body) {
  7774. free_pipe_list(funcp->body);
  7775. # if !BB_MMU
  7776. free(funcp->body_as_string);
  7777. # endif
  7778. }
  7779. } else {
  7780. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7781. cmd->argv[0] = funcp->name;
  7782. cmd->group = funcp->body;
  7783. # if !BB_MMU
  7784. cmd->group_as_string = funcp->body_as_string;
  7785. # endif
  7786. }
  7787. } else {
  7788. debug_printf_exec("remembering new function '%s'\n", name);
  7789. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7790. /*funcp->next = NULL;*/
  7791. }
  7792. funcp->name = name;
  7793. return funcp;
  7794. }
  7795. # if ENABLE_HUSH_UNSET
  7796. static void unset_func(const char *name)
  7797. {
  7798. struct function **funcpp = find_function_slot(name);
  7799. struct function *funcp = *funcpp;
  7800. if (funcp != NULL) {
  7801. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7802. *funcpp = funcp->next;
  7803. /* funcp is unlinked now, deleting it.
  7804. * Note: if !funcp->body, the function was created by
  7805. * "-F name body", do not free ->body_as_string
  7806. * and ->name as they were not malloced. */
  7807. if (funcp->body) {
  7808. free_pipe_list(funcp->body);
  7809. free(funcp->name);
  7810. # if !BB_MMU
  7811. free(funcp->body_as_string);
  7812. # endif
  7813. }
  7814. free(funcp);
  7815. }
  7816. }
  7817. # endif
  7818. # if BB_MMU
  7819. #define exec_function(to_free, funcp, argv) \
  7820. exec_function(funcp, argv)
  7821. # endif
  7822. static void exec_function(char ***to_free,
  7823. const struct function *funcp,
  7824. char **argv) NORETURN;
  7825. static void exec_function(char ***to_free,
  7826. const struct function *funcp,
  7827. char **argv)
  7828. {
  7829. # if BB_MMU
  7830. int n;
  7831. argv[0] = G.global_argv[0];
  7832. G.global_argv = argv;
  7833. G.global_argc = n = 1 + string_array_len(argv + 1);
  7834. // Example when we are here: "cmd | func"
  7835. // func will run with saved-redirect fds open.
  7836. // $ f() { echo /proc/self/fd/*; }
  7837. // $ true | f
  7838. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7839. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7840. // Same in script:
  7841. // $ . ./SCRIPT
  7842. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7843. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7844. // They are CLOEXEC so external programs won't see them, but
  7845. // for "more correctness" we might want to close those extra fds here:
  7846. //? close_saved_fds_and_FILE_fds();
  7847. /* "we are in a function, ok to use return" */
  7848. G_flag_return_in_progress = -1;
  7849. enter_var_nest_level();
  7850. IF_HUSH_LOCAL(G.func_nest_level++;)
  7851. /* On MMU, funcp->body is always non-NULL */
  7852. n = run_list(funcp->body);
  7853. _exit(n);
  7854. # else
  7855. //? close_saved_fds_and_FILE_fds();
  7856. //TODO: check whether "true | func_with_return" works
  7857. re_execute_shell(to_free,
  7858. funcp->body_as_string,
  7859. G.global_argv[0],
  7860. argv + 1,
  7861. NULL);
  7862. # endif
  7863. }
  7864. static int run_function(const struct function *funcp, char **argv)
  7865. {
  7866. int rc;
  7867. save_arg_t sv;
  7868. smallint sv_flg;
  7869. save_and_replace_G_args(&sv, argv);
  7870. /* "We are in function, ok to use return" */
  7871. sv_flg = G_flag_return_in_progress;
  7872. G_flag_return_in_progress = -1;
  7873. /* Make "local" variables properly shadow previous ones */
  7874. IF_HUSH_LOCAL(enter_var_nest_level();)
  7875. IF_HUSH_LOCAL(G.func_nest_level++;)
  7876. /* On MMU, funcp->body is always non-NULL */
  7877. # if !BB_MMU
  7878. if (!funcp->body) {
  7879. /* Function defined by -F */
  7880. parse_and_run_string(funcp->body_as_string);
  7881. rc = G.last_exitcode;
  7882. } else
  7883. # endif
  7884. {
  7885. rc = run_list(funcp->body);
  7886. }
  7887. IF_HUSH_LOCAL(G.func_nest_level--;)
  7888. IF_HUSH_LOCAL(leave_var_nest_level();)
  7889. G_flag_return_in_progress = sv_flg;
  7890. # if ENABLE_HUSH_TRAP
  7891. debug_printf_exec("G.return_exitcode=-1\n");
  7892. G.return_exitcode = -1; /* invalidate stashed return value */
  7893. # endif
  7894. restore_G_args(&sv, argv);
  7895. return rc;
  7896. }
  7897. #endif /* ENABLE_HUSH_FUNCTIONS */
  7898. #if BB_MMU
  7899. #define exec_builtin(to_free, x, argv) \
  7900. exec_builtin(x, argv)
  7901. #else
  7902. #define exec_builtin(to_free, x, argv) \
  7903. exec_builtin(to_free, argv)
  7904. #endif
  7905. static void exec_builtin(char ***to_free,
  7906. const struct built_in_command *x,
  7907. char **argv) NORETURN;
  7908. static void exec_builtin(char ***to_free,
  7909. const struct built_in_command *x,
  7910. char **argv)
  7911. {
  7912. #if BB_MMU
  7913. int rcode;
  7914. //? close_saved_fds_and_FILE_fds();
  7915. rcode = x->b_function(argv);
  7916. fflush_all();
  7917. _exit(rcode);
  7918. #else
  7919. fflush_all();
  7920. /* On NOMMU, we must never block!
  7921. * Example: { sleep 99 | read line; } & echo Ok
  7922. */
  7923. re_execute_shell(to_free,
  7924. argv[0],
  7925. G.global_argv[0],
  7926. G.global_argv + 1,
  7927. argv);
  7928. #endif
  7929. }
  7930. static void execvp_or_die(char **argv) NORETURN;
  7931. static void execvp_or_die(char **argv)
  7932. {
  7933. int e;
  7934. debug_printf_exec("execing '%s'\n", argv[0]);
  7935. /* Don't propagate SIG_IGN to the child */
  7936. if (SPECIAL_JOBSTOP_SIGS != 0)
  7937. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7938. execvp(argv[0], argv);
  7939. e = 2;
  7940. if (errno == EACCES) e = 126;
  7941. if (errno == ENOENT) e = 127;
  7942. bb_perror_msg("can't execute '%s'", argv[0]);
  7943. _exit(e);
  7944. }
  7945. #if ENABLE_HUSH_MODE_X
  7946. static void x_mode_print_optionally_squoted(const char *str)
  7947. {
  7948. unsigned len;
  7949. const char *cp;
  7950. cp = str;
  7951. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7952. /* test a char with: bash -c 'set -x; echo "CH"' */
  7953. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7954. " " "\001\002\003\004\005\006\007"
  7955. "\010\011\012\013\014\015\016\017"
  7956. "\020\021\022\023\024\025\026\027"
  7957. "\030\031\032\033\034\035\036\037"
  7958. )
  7959. ] == '\0'
  7960. ) {
  7961. /* string has no special chars */
  7962. x_mode_addstr(str);
  7963. return;
  7964. }
  7965. cp = str;
  7966. for (;;) {
  7967. /* print '....' up to EOL or first squote */
  7968. len = (int)(strchrnul(cp, '\'') - cp);
  7969. if (len != 0) {
  7970. x_mode_addchr('\'');
  7971. x_mode_addblock(cp, len);
  7972. x_mode_addchr('\'');
  7973. cp += len;
  7974. }
  7975. if (*cp == '\0')
  7976. break;
  7977. /* string contains squote(s), print them as \' */
  7978. x_mode_addchr('\\');
  7979. x_mode_addchr('\'');
  7980. cp++;
  7981. }
  7982. }
  7983. static void dump_cmd_in_x_mode(char **argv)
  7984. {
  7985. if (G_x_mode && argv) {
  7986. unsigned n;
  7987. /* "+[+++...][ cmd...]\n\0" */
  7988. x_mode_prefix();
  7989. n = 0;
  7990. while (argv[n]) {
  7991. x_mode_addchr(' ');
  7992. if (argv[n][0] == '\0') {
  7993. x_mode_addchr('\'');
  7994. x_mode_addchr('\'');
  7995. } else {
  7996. x_mode_print_optionally_squoted(argv[n]);
  7997. }
  7998. n++;
  7999. }
  8000. x_mode_flush();
  8001. }
  8002. }
  8003. #else
  8004. # define dump_cmd_in_x_mode(argv) ((void)0)
  8005. #endif
  8006. #if ENABLE_HUSH_COMMAND
  8007. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  8008. {
  8009. char *to_free;
  8010. if (!opt_vV)
  8011. return;
  8012. to_free = NULL;
  8013. if (!explanation) {
  8014. char *path = getenv("PATH");
  8015. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  8016. if (!explanation)
  8017. _exit(1); /* PROG was not found */
  8018. if (opt_vV != 'V')
  8019. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  8020. }
  8021. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  8022. free(to_free);
  8023. fflush_all();
  8024. _exit(0);
  8025. }
  8026. #else
  8027. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  8028. #endif
  8029. #if BB_MMU
  8030. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  8031. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  8032. #define pseudo_exec(nommu_save, command, argv_expanded) \
  8033. pseudo_exec(command, argv_expanded)
  8034. #endif
  8035. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  8036. * Never returns.
  8037. * Don't exit() here. If you don't exec, use _exit instead.
  8038. * The at_exit handlers apparently confuse the calling process,
  8039. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  8040. */
  8041. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8042. char **argv, int assignment_cnt,
  8043. char **argv_expanded) NORETURN;
  8044. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8045. char **argv, int assignment_cnt,
  8046. char **argv_expanded)
  8047. {
  8048. const struct built_in_command *x;
  8049. struct variable **sv_shadowed;
  8050. char **new_env;
  8051. IF_HUSH_COMMAND(char opt_vV = 0;)
  8052. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8053. new_env = expand_assignments(argv, assignment_cnt);
  8054. dump_cmd_in_x_mode(new_env);
  8055. if (!argv[assignment_cnt]) {
  8056. /* Case when we are here: ... | var=val | ...
  8057. * (note that we do not exit early, i.e., do not optimize out
  8058. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8059. */
  8060. free_strings(new_env);
  8061. _exit_SUCCESS();
  8062. }
  8063. sv_shadowed = G.shadowed_vars_pp;
  8064. #if BB_MMU
  8065. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8066. #else
  8067. G.shadowed_vars_pp = &nommu_save->old_vars;
  8068. G.var_nest_level++;
  8069. #endif
  8070. set_vars_and_save_old(new_env);
  8071. G.shadowed_vars_pp = sv_shadowed;
  8072. if (argv_expanded) {
  8073. argv = argv_expanded;
  8074. } else {
  8075. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8076. #if !BB_MMU
  8077. nommu_save->argv = argv;
  8078. #endif
  8079. }
  8080. dump_cmd_in_x_mode(argv);
  8081. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8082. if (strchr(argv[0], '/') != NULL)
  8083. goto skip;
  8084. #endif
  8085. #if ENABLE_HUSH_FUNCTIONS
  8086. /* Check if the command matches any functions (this goes before bltins) */
  8087. funcp = find_function(argv[0]);
  8088. if (funcp)
  8089. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8090. #endif
  8091. #if ENABLE_HUSH_COMMAND
  8092. /* "command BAR": run BAR without looking it up among functions
  8093. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8094. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8095. */
  8096. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8097. char *p;
  8098. argv++;
  8099. p = *argv;
  8100. if (p[0] != '-' || !p[1])
  8101. continue; /* bash allows "command command command [-OPT] BAR" */
  8102. for (;;) {
  8103. p++;
  8104. switch (*p) {
  8105. case '\0':
  8106. argv++;
  8107. p = *argv;
  8108. if (p[0] != '-' || !p[1])
  8109. goto after_opts;
  8110. continue; /* next arg is also -opts, process it too */
  8111. case 'v':
  8112. case 'V':
  8113. opt_vV = *p;
  8114. continue;
  8115. default:
  8116. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8117. }
  8118. }
  8119. }
  8120. after_opts:
  8121. # if ENABLE_HUSH_FUNCTIONS
  8122. if (opt_vV && find_function(argv[0]))
  8123. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8124. # endif
  8125. #endif
  8126. /* Check if the command matches any of the builtins.
  8127. * Depending on context, this might be redundant. But it's
  8128. * easier to waste a few CPU cycles than it is to figure out
  8129. * if this is one of those cases.
  8130. */
  8131. /* Why "BB_MMU ? :" difference in logic? -
  8132. * On NOMMU, it is more expensive to re-execute shell
  8133. * just in order to run echo or test builtin.
  8134. * It's better to skip it here and run corresponding
  8135. * non-builtin later. */
  8136. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8137. if (x) {
  8138. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8139. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8140. }
  8141. #if ENABLE_FEATURE_SH_STANDALONE
  8142. /* Check if the command matches any busybox applets */
  8143. {
  8144. int a = find_applet_by_name(argv[0]);
  8145. if (a >= 0) {
  8146. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8147. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8148. if (APPLET_IS_NOEXEC(a)) {
  8149. /* Do not leak open fds from opened script files etc.
  8150. * Testcase: interactive "ls -l /proc/self/fd"
  8151. * should not show tty fd open.
  8152. */
  8153. close_saved_fds_and_FILE_fds();
  8154. //FIXME: should also close saved redir fds
  8155. //This casuses test failures in
  8156. //redir_children_should_not_see_saved_fd_2.tests
  8157. //redir_children_should_not_see_saved_fd_3.tests
  8158. //if you replace "busybox find" with just "find" in them
  8159. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8160. switch_off_special_sigs(G.special_sig_mask);
  8161. debug_printf_exec("running applet '%s'\n", argv[0]);
  8162. run_noexec_applet_and_exit(a, argv[0], argv);
  8163. }
  8164. # endif
  8165. /* Re-exec ourselves */
  8166. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8167. /* Don't propagate SIG_IGN to the child */
  8168. if (SPECIAL_JOBSTOP_SIGS != 0)
  8169. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8170. execv(bb_busybox_exec_path, argv);
  8171. /* If they called chroot or otherwise made the binary no longer
  8172. * executable, fall through */
  8173. }
  8174. }
  8175. #endif
  8176. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8177. skip:
  8178. #endif
  8179. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8180. execvp_or_die(argv);
  8181. }
  8182. /* Called after [v]fork() in run_pipe
  8183. */
  8184. static void pseudo_exec(nommu_save_t *nommu_save,
  8185. struct command *command,
  8186. char **argv_expanded) NORETURN;
  8187. static void pseudo_exec(nommu_save_t *nommu_save,
  8188. struct command *command,
  8189. char **argv_expanded)
  8190. {
  8191. #if ENABLE_HUSH_FUNCTIONS
  8192. if (command->cmd_type == CMD_FUNCDEF) {
  8193. /* Ignore funcdefs in pipes:
  8194. * true | f() { cmd }
  8195. */
  8196. _exit(0);
  8197. }
  8198. #endif
  8199. if (command->argv) {
  8200. pseudo_exec_argv(nommu_save, command->argv,
  8201. command->assignment_cnt, argv_expanded);
  8202. }
  8203. if (command->group) {
  8204. /* Cases when we are here:
  8205. * ( list )
  8206. * { list } &
  8207. * ... | ( list ) | ...
  8208. * ... | { list } | ...
  8209. */
  8210. #if BB_MMU
  8211. int rcode;
  8212. debug_printf_exec("pseudo_exec: run_list\n");
  8213. reset_traps_to_defaults();
  8214. rcode = run_list(command->group);
  8215. /* OK to leak memory by not calling free_pipe_list,
  8216. * since this process is about to exit */
  8217. _exit(rcode);
  8218. #else
  8219. re_execute_shell(&nommu_save->argv_from_re_execing,
  8220. command->group_as_string,
  8221. G.global_argv[0],
  8222. G.global_argv + 1,
  8223. NULL);
  8224. #endif
  8225. }
  8226. /* Case when we are here: ... | >file */
  8227. debug_printf_exec("pseudo_exec'ed null command\n");
  8228. _exit_SUCCESS();
  8229. }
  8230. #if ENABLE_HUSH_JOB
  8231. static const char *get_cmdtext(struct pipe *pi)
  8232. {
  8233. char **argv;
  8234. char *p;
  8235. int len;
  8236. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8237. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8238. * On subsequent bg argv is trashed, but we won't use it */
  8239. if (pi->cmdtext)
  8240. return pi->cmdtext;
  8241. argv = pi->cmds[0].argv;
  8242. if (!argv) {
  8243. pi->cmdtext = xzalloc(1);
  8244. return pi->cmdtext;
  8245. }
  8246. len = 0;
  8247. do {
  8248. len += strlen(*argv) + 1;
  8249. } while (*++argv);
  8250. p = xmalloc(len);
  8251. pi->cmdtext = p;
  8252. argv = pi->cmds[0].argv;
  8253. do {
  8254. p = stpcpy(p, *argv);
  8255. *p++ = ' ';
  8256. } while (*++argv);
  8257. p[-1] = '\0';
  8258. return pi->cmdtext;
  8259. }
  8260. static void remove_job_from_table(struct pipe *pi)
  8261. {
  8262. struct pipe *prev_pipe;
  8263. if (pi == G.job_list) {
  8264. G.job_list = pi->next;
  8265. } else {
  8266. prev_pipe = G.job_list;
  8267. while (prev_pipe->next != pi)
  8268. prev_pipe = prev_pipe->next;
  8269. prev_pipe->next = pi->next;
  8270. }
  8271. G.last_jobid = 0;
  8272. if (G.job_list)
  8273. G.last_jobid = G.job_list->jobid;
  8274. }
  8275. static void delete_finished_job(struct pipe *pi)
  8276. {
  8277. remove_job_from_table(pi);
  8278. free_pipe(pi);
  8279. }
  8280. static void clean_up_last_dead_job(void)
  8281. {
  8282. if (G.job_list && !G.job_list->alive_cmds)
  8283. delete_finished_job(G.job_list);
  8284. }
  8285. static void insert_job_into_table(struct pipe *pi)
  8286. {
  8287. struct pipe *job, **jobp;
  8288. int i;
  8289. clean_up_last_dead_job();
  8290. /* Find the end of the list, and find next job ID to use */
  8291. i = 0;
  8292. jobp = &G.job_list;
  8293. while ((job = *jobp) != NULL) {
  8294. if (job->jobid > i)
  8295. i = job->jobid;
  8296. jobp = &job->next;
  8297. }
  8298. pi->jobid = i + 1;
  8299. /* Create a new job struct at the end */
  8300. job = *jobp = xmemdup(pi, sizeof(*pi));
  8301. job->next = NULL;
  8302. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8303. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8304. for (i = 0; i < pi->num_cmds; i++) {
  8305. job->cmds[i].pid = pi->cmds[i].pid;
  8306. /* all other fields are not used and stay zero */
  8307. }
  8308. job->cmdtext = xstrdup(get_cmdtext(pi));
  8309. if (G_interactive_fd)
  8310. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8311. G.last_jobid = job->jobid;
  8312. }
  8313. #endif /* JOB */
  8314. static int job_exited_or_stopped(struct pipe *pi)
  8315. {
  8316. int rcode, i;
  8317. if (pi->alive_cmds != pi->stopped_cmds)
  8318. return -1;
  8319. /* All processes in fg pipe have exited or stopped */
  8320. rcode = 0;
  8321. i = pi->num_cmds;
  8322. while (--i >= 0) {
  8323. rcode = pi->cmds[i].cmd_exitcode;
  8324. /* usually last process gives overall exitstatus,
  8325. * but with "set -o pipefail", last *failed* process does */
  8326. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8327. break;
  8328. }
  8329. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8330. return rcode;
  8331. }
  8332. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8333. {
  8334. #if ENABLE_HUSH_JOB
  8335. struct pipe *pi;
  8336. #endif
  8337. int i, dead;
  8338. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8339. #if DEBUG_JOBS
  8340. if (WIFSTOPPED(status))
  8341. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8342. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8343. if (WIFSIGNALED(status))
  8344. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8345. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8346. if (WIFEXITED(status))
  8347. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8348. childpid, WEXITSTATUS(status));
  8349. #endif
  8350. /* Were we asked to wait for a fg pipe? */
  8351. if (fg_pipe) {
  8352. i = fg_pipe->num_cmds;
  8353. while (--i >= 0) {
  8354. int rcode;
  8355. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8356. if (fg_pipe->cmds[i].pid != childpid)
  8357. continue;
  8358. if (dead) {
  8359. int ex;
  8360. fg_pipe->cmds[i].pid = 0;
  8361. fg_pipe->alive_cmds--;
  8362. ex = WEXITSTATUS(status);
  8363. /* bash prints killer signal's name for *last*
  8364. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8365. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8366. */
  8367. if (WIFSIGNALED(status)) {
  8368. int sig = WTERMSIG(status);
  8369. #if ENABLE_HUSH_JOB
  8370. if (G.run_list_level == 1
  8371. /* ^^^^^ Do not print in nested contexts, example:
  8372. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8373. */
  8374. && i == fg_pipe->num_cmds-1
  8375. ) {
  8376. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8377. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8378. }
  8379. #endif
  8380. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8381. /* MIPS has 128 sigs (1..128), if sig==128,
  8382. * 128 + sig would result in exitcode 256 -> 0!
  8383. */
  8384. ex = 128 | sig;
  8385. }
  8386. fg_pipe->cmds[i].cmd_exitcode = ex;
  8387. } else {
  8388. fg_pipe->stopped_cmds++;
  8389. }
  8390. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8391. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8392. rcode = job_exited_or_stopped(fg_pipe);
  8393. if (rcode >= 0) {
  8394. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8395. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8396. * and "killall -STOP cat" */
  8397. if (G_interactive_fd) {
  8398. #if ENABLE_HUSH_JOB
  8399. if (fg_pipe->alive_cmds != 0)
  8400. insert_job_into_table(fg_pipe);
  8401. #endif
  8402. return rcode;
  8403. }
  8404. if (fg_pipe->alive_cmds == 0)
  8405. return rcode;
  8406. }
  8407. /* There are still running processes in the fg_pipe */
  8408. return -1;
  8409. }
  8410. /* It wasn't in fg_pipe, look for process in bg pipes */
  8411. }
  8412. #if ENABLE_HUSH_JOB
  8413. /* We were asked to wait for bg or orphaned children */
  8414. /* No need to remember exitcode in this case */
  8415. for (pi = G.job_list; pi; pi = pi->next) {
  8416. for (i = 0; i < pi->num_cmds; i++) {
  8417. if (pi->cmds[i].pid == childpid)
  8418. goto found_pi_and_prognum;
  8419. }
  8420. }
  8421. /* Happens when shell is used as init process (init=/bin/sh) */
  8422. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8423. return -1; /* this wasn't a process from fg_pipe */
  8424. found_pi_and_prognum:
  8425. if (dead) {
  8426. /* child exited */
  8427. int rcode = WEXITSTATUS(status);
  8428. if (WIFSIGNALED(status))
  8429. /* NB: not 128 + sig, MIPS has sig 128 */
  8430. rcode = 128 | WTERMSIG(status);
  8431. pi->cmds[i].cmd_exitcode = rcode;
  8432. if (G.last_bg_pid == pi->cmds[i].pid)
  8433. G.last_bg_pid_exitcode = rcode;
  8434. pi->cmds[i].pid = 0;
  8435. pi->alive_cmds--;
  8436. if (!pi->alive_cmds) {
  8437. # if ENABLE_HUSH_BASH_COMPAT
  8438. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8439. # endif
  8440. if (G_interactive_fd) {
  8441. printf(JOB_STATUS_FORMAT, pi->jobid,
  8442. "Done", pi->cmdtext);
  8443. delete_finished_job(pi);
  8444. } else {
  8445. /*
  8446. * bash deletes finished jobs from job table only in interactive mode,
  8447. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8448. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8449. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8450. * We only retain one "dead" job, if it's the single job on the list.
  8451. * This covers most of real-world scenarios where this is useful.
  8452. */
  8453. if (pi != G.job_list)
  8454. delete_finished_job(pi);
  8455. }
  8456. }
  8457. } else {
  8458. /* child stopped */
  8459. pi->stopped_cmds++;
  8460. }
  8461. #endif
  8462. return -1; /* this wasn't a process from fg_pipe */
  8463. }
  8464. /* Check to see if any processes have exited -- if they have,
  8465. * figure out why and see if a job has completed.
  8466. *
  8467. * If non-NULL fg_pipe: wait for its completion or stop.
  8468. * Return its exitcode or zero if stopped.
  8469. *
  8470. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8471. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8472. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8473. * or 0 if no children changed status.
  8474. *
  8475. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8476. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8477. * or 0 if no children changed status.
  8478. */
  8479. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8480. {
  8481. int attributes;
  8482. int status;
  8483. int rcode = 0;
  8484. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8485. attributes = WUNTRACED;
  8486. if (fg_pipe == NULL)
  8487. attributes |= WNOHANG;
  8488. errno = 0;
  8489. #if ENABLE_HUSH_FAST
  8490. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8491. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8492. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8493. /* There was neither fork nor SIGCHLD since last waitpid */
  8494. /* Avoid doing waitpid syscall if possible */
  8495. if (!G.we_have_children) {
  8496. errno = ECHILD;
  8497. return -1;
  8498. }
  8499. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8500. /* We have children, but they did not exit
  8501. * or stop yet (we saw no SIGCHLD) */
  8502. return 0;
  8503. }
  8504. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8505. }
  8506. #endif
  8507. /* Do we do this right?
  8508. * bash-3.00# sleep 20 | false
  8509. * <ctrl-Z pressed>
  8510. * [3]+ Stopped sleep 20 | false
  8511. * bash-3.00# echo $?
  8512. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8513. * [hush 1.14.0: yes we do it right]
  8514. */
  8515. while (1) {
  8516. pid_t childpid;
  8517. #if ENABLE_HUSH_FAST
  8518. int i;
  8519. i = G.count_SIGCHLD;
  8520. #endif
  8521. childpid = waitpid(-1, &status, attributes);
  8522. if (childpid <= 0) {
  8523. if (childpid && errno != ECHILD)
  8524. bb_simple_perror_msg("waitpid");
  8525. #if ENABLE_HUSH_FAST
  8526. else { /* Until next SIGCHLD, waitpid's are useless */
  8527. G.we_have_children = (childpid == 0);
  8528. G.handled_SIGCHLD = i;
  8529. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8530. }
  8531. #endif
  8532. /* ECHILD (no children), or 0 (no change in children status) */
  8533. rcode = childpid;
  8534. break;
  8535. }
  8536. rcode = process_wait_result(fg_pipe, childpid, status);
  8537. if (rcode >= 0) {
  8538. /* fg_pipe exited or stopped */
  8539. break;
  8540. }
  8541. if (childpid == waitfor_pid) { /* "wait PID" */
  8542. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8543. rcode = WEXITSTATUS(status);
  8544. if (WIFSIGNALED(status))
  8545. rcode = 128 | WTERMSIG(status);
  8546. if (WIFSTOPPED(status))
  8547. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8548. rcode = 128 | WSTOPSIG(status);
  8549. rcode++;
  8550. break; /* "wait PID" called us, give it exitcode+1 */
  8551. }
  8552. #if ENABLE_HUSH_BASH_COMPAT
  8553. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8554. && G.dead_job_exitcode >= 0 /* some job did finish */
  8555. ) {
  8556. debug_printf_exec("waitfor_pid:-1\n");
  8557. rcode = G.dead_job_exitcode + 1;
  8558. break;
  8559. }
  8560. #endif
  8561. /* This wasn't one of our processes, or */
  8562. /* fg_pipe still has running processes, do waitpid again */
  8563. } /* while (waitpid succeeds)... */
  8564. return rcode;
  8565. }
  8566. #if ENABLE_HUSH_JOB
  8567. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8568. {
  8569. pid_t p;
  8570. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8571. if (G_saved_tty_pgrp) {
  8572. /* Job finished, move the shell to the foreground */
  8573. p = getpgrp(); /* our process group id */
  8574. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8575. tcsetpgrp(G_interactive_fd, p);
  8576. }
  8577. return rcode;
  8578. }
  8579. #endif
  8580. /* Start all the jobs, but don't wait for anything to finish.
  8581. * See checkjobs().
  8582. *
  8583. * Return code is normally -1, when the caller has to wait for children
  8584. * to finish to determine the exit status of the pipe. If the pipe
  8585. * is a simple builtin command, however, the action is done by the
  8586. * time run_pipe returns, and the exit code is provided as the
  8587. * return value.
  8588. *
  8589. * Returns -1 only if started some children. IOW: we have to
  8590. * mask out retvals of builtins etc with 0xff!
  8591. *
  8592. * The only case when we do not need to [v]fork is when the pipe
  8593. * is single, non-backgrounded, non-subshell command. Examples:
  8594. * cmd ; ... { list } ; ...
  8595. * cmd && ... { list } && ...
  8596. * cmd || ... { list } || ...
  8597. * If it is, then we can run cmd as a builtin, NOFORK,
  8598. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8599. * with run_list. If it isn't one of these, we fork and exec cmd.
  8600. *
  8601. * Cases when we must fork:
  8602. * non-single: cmd | cmd
  8603. * backgrounded: cmd & { list } &
  8604. * subshell: ( list ) [&]
  8605. */
  8606. #if !ENABLE_HUSH_MODE_X
  8607. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8608. redirect_and_varexp_helper(command, sqp)
  8609. #endif
  8610. static int redirect_and_varexp_helper(
  8611. struct command *command,
  8612. struct squirrel **sqp,
  8613. char **argv_expanded)
  8614. {
  8615. /* Assignments occur before redirects. Try:
  8616. * a=`sleep 1` sleep 2 3>/qwe/rty
  8617. */
  8618. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8619. dump_cmd_in_x_mode(new_env);
  8620. dump_cmd_in_x_mode(argv_expanded);
  8621. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8622. set_vars_and_save_old(new_env);
  8623. return setup_redirects(command, sqp);
  8624. }
  8625. static NOINLINE int run_pipe(struct pipe *pi)
  8626. {
  8627. static const char *const null_ptr = NULL;
  8628. int cmd_no;
  8629. int next_infd;
  8630. struct command *command;
  8631. char **argv_expanded;
  8632. char **argv;
  8633. struct squirrel *squirrel = NULL;
  8634. int rcode;
  8635. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8636. debug_enter();
  8637. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8638. * Result should be 3 lines: q w e, qwe, q w e
  8639. */
  8640. if (G.ifs_whitespace != G.ifs)
  8641. free(G.ifs_whitespace);
  8642. G.ifs = get_local_var_value("IFS");
  8643. if (G.ifs) {
  8644. char *p;
  8645. G.ifs_whitespace = (char*)G.ifs;
  8646. p = skip_whitespace(G.ifs);
  8647. if (*p) {
  8648. /* Not all $IFS is whitespace */
  8649. char *d;
  8650. int len = p - G.ifs;
  8651. p = skip_non_whitespace(p);
  8652. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8653. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8654. while (*p) {
  8655. if (isspace(*p))
  8656. *d++ = *p;
  8657. p++;
  8658. }
  8659. *d = '\0';
  8660. }
  8661. } else {
  8662. G.ifs = defifs;
  8663. G.ifs_whitespace = (char*)G.ifs;
  8664. }
  8665. IF_HUSH_JOB(pi->pgrp = -1;)
  8666. pi->stopped_cmds = 0;
  8667. command = &pi->cmds[0];
  8668. argv_expanded = NULL;
  8669. if (pi->num_cmds != 1
  8670. || pi->followup == PIPE_BG
  8671. || command->cmd_type == CMD_SUBSHELL
  8672. ) {
  8673. goto must_fork;
  8674. }
  8675. pi->alive_cmds = 1;
  8676. debug_printf_exec(": group:%p argv:'%s'\n",
  8677. command->group, command->argv ? command->argv[0] : "NONE");
  8678. if (command->group) {
  8679. #if ENABLE_HUSH_FUNCTIONS
  8680. if (command->cmd_type == CMD_FUNCDEF) {
  8681. /* "executing" func () { list } */
  8682. struct function *funcp;
  8683. funcp = new_function(command->argv[0]);
  8684. /* funcp->name is already set to argv[0] */
  8685. funcp->body = command->group;
  8686. # if !BB_MMU
  8687. funcp->body_as_string = command->group_as_string;
  8688. command->group_as_string = NULL;
  8689. # endif
  8690. command->group = NULL;
  8691. command->argv[0] = NULL;
  8692. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8693. funcp->parent_cmd = command;
  8694. command->child_func = funcp;
  8695. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8696. debug_leave();
  8697. return EXIT_SUCCESS;
  8698. }
  8699. #endif
  8700. /* { list } */
  8701. debug_printf_exec("non-subshell group\n");
  8702. rcode = 1; /* exitcode if redir failed */
  8703. if (setup_redirects(command, &squirrel) == 0) {
  8704. debug_printf_exec(": run_list\n");
  8705. //FIXME: we need to pass squirrel down into run_list()
  8706. //for SH_STANDALONE case, or else this construct:
  8707. // { find /proc/self/fd; true; } >FILE; cmd2
  8708. //has no way of closing saved fd#1 for "find",
  8709. //and in SH_STANDALONE mode, "find" is not execed,
  8710. //therefore CLOEXEC on saved fd does not help.
  8711. rcode = run_list(command->group) & 0xff;
  8712. }
  8713. restore_redirects(squirrel);
  8714. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8715. debug_leave();
  8716. debug_printf_exec("run_pipe: return %d\n", rcode);
  8717. return rcode;
  8718. }
  8719. argv = command->argv ? command->argv : (char **) &null_ptr;
  8720. {
  8721. const struct built_in_command *x;
  8722. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8723. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8724. struct variable **sv_shadowed;
  8725. struct variable *old_vars;
  8726. #if ENABLE_HUSH_LINENO_VAR
  8727. G.execute_lineno = command->lineno;
  8728. #endif
  8729. if (argv[command->assignment_cnt] == NULL) {
  8730. /* Assignments, but no command.
  8731. * Ensure redirects take effect (that is, create files).
  8732. * Try "a=t >file"
  8733. */
  8734. unsigned i;
  8735. G.expand_exitcode = 0;
  8736. only_assignments:
  8737. rcode = setup_redirects(command, &squirrel);
  8738. restore_redirects(squirrel);
  8739. /* Set shell variables */
  8740. i = 0;
  8741. while (i < command->assignment_cnt) {
  8742. char *p = expand_string_to_string(argv[i],
  8743. EXP_FLAG_ESC_GLOB_CHARS,
  8744. /*unbackslash:*/ 1
  8745. );
  8746. #if ENABLE_HUSH_MODE_X
  8747. if (G_x_mode) {
  8748. char *eq;
  8749. if (i == 0)
  8750. x_mode_prefix();
  8751. x_mode_addchr(' ');
  8752. eq = strchrnul(p, '=');
  8753. if (*eq) eq++;
  8754. x_mode_addblock(p, (eq - p));
  8755. x_mode_print_optionally_squoted(eq);
  8756. x_mode_flush();
  8757. }
  8758. #endif
  8759. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8760. if (set_local_var0(p)) {
  8761. /* assignment to readonly var / putenv error? */
  8762. rcode = 1;
  8763. }
  8764. i++;
  8765. }
  8766. /* Redirect error sets $? to 1. Otherwise,
  8767. * if evaluating assignment value set $?, retain it.
  8768. * Else, clear $?:
  8769. * false; q=`exit 2`; echo $? - should print 2
  8770. * false; x=1; echo $? - should print 0
  8771. * Because of the 2nd case, we can't just use G.last_exitcode.
  8772. */
  8773. if (rcode == 0)
  8774. rcode = G.expand_exitcode;
  8775. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8776. debug_leave();
  8777. debug_printf_exec("run_pipe: return %d\n", rcode);
  8778. return rcode;
  8779. }
  8780. /* Expand the rest into (possibly) many strings each */
  8781. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8782. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8783. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8784. else
  8785. #endif
  8786. #if defined(CMD_SINGLEWORD_NOGLOB)
  8787. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8788. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8789. else
  8790. #endif
  8791. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8792. /* If someone gives us an empty string: `cmd with empty output` */
  8793. if (!argv_expanded[0]) {
  8794. free(argv_expanded);
  8795. /* `false` still has to set exitcode 1 */
  8796. G.expand_exitcode = G.last_exitcode;
  8797. goto only_assignments;
  8798. }
  8799. old_vars = NULL;
  8800. sv_shadowed = G.shadowed_vars_pp;
  8801. /* Check if argv[0] matches any functions (this goes before bltins) */
  8802. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8803. IF_HUSH_FUNCTIONS(x = NULL;)
  8804. IF_HUSH_FUNCTIONS(if (!funcp))
  8805. x = find_builtin(argv_expanded[0]);
  8806. if (x || funcp) {
  8807. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8808. debug_printf("exec with redirects only\n");
  8809. /*
  8810. * Variable assignments are executed, but then "forgotten":
  8811. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8812. * sleeps, but prints nothing.
  8813. */
  8814. enter_var_nest_level();
  8815. G.shadowed_vars_pp = &old_vars;
  8816. rcode = redirect_and_varexp_helper(command,
  8817. /*squirrel:*/ ERR_PTR,
  8818. argv_expanded
  8819. );
  8820. G.shadowed_vars_pp = sv_shadowed;
  8821. /* rcode=1 can be if redir file can't be opened */
  8822. goto clean_up_and_ret1;
  8823. }
  8824. /* Bump var nesting, or this will leak exported $a:
  8825. * a=b true; env | grep ^a=
  8826. */
  8827. enter_var_nest_level();
  8828. /* Collect all variables "shadowed" by helper
  8829. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8830. * into old_vars list:
  8831. */
  8832. G.shadowed_vars_pp = &old_vars;
  8833. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8834. if (rcode == 0) {
  8835. if (!funcp) {
  8836. /* Do not collect *to old_vars list* vars shadowed
  8837. * by e.g. "local VAR" builtin (collect them
  8838. * in the previously nested list instead):
  8839. * don't want them to be restored immediately
  8840. * after "local" completes.
  8841. */
  8842. G.shadowed_vars_pp = sv_shadowed;
  8843. debug_printf_exec(": builtin '%s' '%s'...\n",
  8844. x->b_cmd, argv_expanded[1]);
  8845. fflush_all();
  8846. rcode = x->b_function(argv_expanded) & 0xff;
  8847. fflush_all();
  8848. }
  8849. #if ENABLE_HUSH_FUNCTIONS
  8850. else {
  8851. debug_printf_exec(": function '%s' '%s'...\n",
  8852. funcp->name, argv_expanded[1]);
  8853. rcode = run_function(funcp, argv_expanded) & 0xff;
  8854. /*
  8855. * But do collect *to old_vars list* vars shadowed
  8856. * within function execution. To that end, restore
  8857. * this pointer _after_ function run:
  8858. */
  8859. G.shadowed_vars_pp = sv_shadowed;
  8860. }
  8861. #endif
  8862. }
  8863. } else
  8864. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8865. int n = find_applet_by_name(argv_expanded[0]);
  8866. if (n < 0 || !APPLET_IS_NOFORK(n))
  8867. goto must_fork;
  8868. enter_var_nest_level();
  8869. /* Collect all variables "shadowed" by helper into old_vars list */
  8870. G.shadowed_vars_pp = &old_vars;
  8871. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8872. G.shadowed_vars_pp = sv_shadowed;
  8873. if (rcode == 0) {
  8874. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8875. argv_expanded[0], argv_expanded[1]);
  8876. /*
  8877. * Note: signals (^C) can't interrupt here.
  8878. * We remember them and they will be acted upon
  8879. * after applet returns.
  8880. * This makes applets which can run for a long time
  8881. * and/or wait for user input ineligible for NOFORK:
  8882. * for example, "yes" or "rm" (rm -i waits for input).
  8883. */
  8884. rcode = run_nofork_applet(n, argv_expanded);
  8885. }
  8886. } else
  8887. goto must_fork;
  8888. restore_redirects(squirrel);
  8889. clean_up_and_ret1:
  8890. leave_var_nest_level();
  8891. add_vars(old_vars);
  8892. /*
  8893. * Try "usleep 99999999" + ^C + "echo $?"
  8894. * with FEATURE_SH_NOFORK=y.
  8895. */
  8896. if (!funcp) {
  8897. /* It was builtin or nofork.
  8898. * if this would be a real fork/execed program,
  8899. * it should have died if a fatal sig was received.
  8900. * But OTOH, there was no separate process,
  8901. * the sig was sent to _shell_, not to non-existing
  8902. * child.
  8903. * Let's just handle ^C only, this one is obvious:
  8904. * we aren't ok with exitcode 0 when ^C was pressed
  8905. * during builtin/nofork.
  8906. */
  8907. if (sigismember(&G.pending_set, SIGINT))
  8908. rcode = 128 | SIGINT;
  8909. }
  8910. free(argv_expanded);
  8911. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8912. debug_leave();
  8913. debug_printf_exec("run_pipe return %d\n", rcode);
  8914. return rcode;
  8915. }
  8916. must_fork:
  8917. /* NB: argv_expanded may already be created, and that
  8918. * might include `cmd` runs! Do not rerun it! We *must*
  8919. * use argv_expanded if it's non-NULL */
  8920. /* Going to fork a child per each pipe member */
  8921. pi->alive_cmds = 0;
  8922. next_infd = 0;
  8923. cmd_no = 0;
  8924. while (cmd_no < pi->num_cmds) {
  8925. struct fd_pair pipefds;
  8926. #if !BB_MMU
  8927. int sv_var_nest_level = G.var_nest_level;
  8928. volatile nommu_save_t nommu_save;
  8929. nommu_save.old_vars = NULL;
  8930. nommu_save.argv = NULL;
  8931. nommu_save.argv_from_re_execing = NULL;
  8932. #endif
  8933. command = &pi->cmds[cmd_no];
  8934. cmd_no++;
  8935. if (command->argv) {
  8936. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8937. command->argv[0], command->argv[1]);
  8938. } else {
  8939. debug_printf_exec(": pipe member with no argv\n");
  8940. }
  8941. /* pipes are inserted between pairs of commands */
  8942. pipefds.rd = 0;
  8943. pipefds.wr = 1;
  8944. if (cmd_no < pi->num_cmds)
  8945. xpiped_pair(pipefds);
  8946. #if ENABLE_HUSH_LINENO_VAR
  8947. G.execute_lineno = command->lineno;
  8948. #endif
  8949. command->pid = BB_MMU ? fork() : vfork();
  8950. if (!command->pid) { /* child */
  8951. #if ENABLE_HUSH_JOB
  8952. disable_restore_tty_pgrp_on_exit();
  8953. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8954. /* Every child adds itself to new process group
  8955. * with pgid == pid_of_first_child_in_pipe */
  8956. if (G.run_list_level == 1 && G_interactive_fd) {
  8957. pid_t pgrp;
  8958. pgrp = pi->pgrp;
  8959. if (pgrp < 0) /* true for 1st process only */
  8960. pgrp = getpid();
  8961. if (setpgid(0, pgrp) == 0
  8962. && pi->followup != PIPE_BG
  8963. && G_saved_tty_pgrp /* we have ctty */
  8964. ) {
  8965. /* We do it in *every* child, not just first,
  8966. * to avoid races */
  8967. tcsetpgrp(G_interactive_fd, pgrp);
  8968. }
  8969. }
  8970. #endif
  8971. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8972. /* 1st cmd in backgrounded pipe
  8973. * should have its stdin /dev/null'ed */
  8974. close(0);
  8975. if (open(bb_dev_null, O_RDONLY))
  8976. xopen("/", O_RDONLY);
  8977. } else {
  8978. xmove_fd(next_infd, 0);
  8979. }
  8980. xmove_fd(pipefds.wr, 1);
  8981. if (pipefds.rd > 1)
  8982. close(pipefds.rd);
  8983. /* Like bash, explicit redirects override pipes,
  8984. * and the pipe fd (fd#1) is available for dup'ing:
  8985. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8986. * of cmd1 goes into pipe.
  8987. */
  8988. if (setup_redirects(command, NULL)) {
  8989. /* Happens when redir file can't be opened:
  8990. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8991. * FOO
  8992. * hush: can't open '/qwe/rty': No such file or directory
  8993. * BAZ
  8994. * (echo BAR is not executed, it hits _exit(1) below)
  8995. */
  8996. _exit(1);
  8997. }
  8998. /* Stores to nommu_save list of env vars putenv'ed
  8999. * (NOMMU, on MMU we don't need that) */
  9000. /* cast away volatility... */
  9001. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  9002. /* pseudo_exec() does not return */
  9003. }
  9004. /* parent or error */
  9005. #if ENABLE_HUSH_FAST
  9006. G.count_SIGCHLD++;
  9007. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  9008. #endif
  9009. enable_restore_tty_pgrp_on_exit();
  9010. #if !BB_MMU
  9011. /* Clean up after vforked child */
  9012. free(nommu_save.argv);
  9013. free(nommu_save.argv_from_re_execing);
  9014. G.var_nest_level = sv_var_nest_level;
  9015. remove_nested_vars();
  9016. add_vars(nommu_save.old_vars);
  9017. #endif
  9018. free(argv_expanded);
  9019. argv_expanded = NULL;
  9020. if (command->pid < 0) { /* [v]fork failed */
  9021. /* Clearly indicate, was it fork or vfork */
  9022. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  9023. } else {
  9024. pi->alive_cmds++;
  9025. #if ENABLE_HUSH_JOB
  9026. /* Second and next children need to know pid of first one */
  9027. if (pi->pgrp < 0)
  9028. pi->pgrp = command->pid;
  9029. #endif
  9030. }
  9031. if (cmd_no > 1)
  9032. close(next_infd);
  9033. if (cmd_no < pi->num_cmds)
  9034. close(pipefds.wr);
  9035. /* Pass read (output) pipe end to next iteration */
  9036. next_infd = pipefds.rd;
  9037. }
  9038. if (!pi->alive_cmds) {
  9039. debug_leave();
  9040. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9041. return 1;
  9042. }
  9043. debug_leave();
  9044. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9045. return -1;
  9046. }
  9047. /* NB: called by pseudo_exec, and therefore must not modify any
  9048. * global data until exec/_exit (we can be a child after vfork!) */
  9049. static int run_list(struct pipe *pi)
  9050. {
  9051. #if ENABLE_HUSH_CASE
  9052. char *case_word = NULL;
  9053. #endif
  9054. #if ENABLE_HUSH_LOOPS
  9055. struct pipe *loop_top = NULL;
  9056. char **for_lcur = NULL;
  9057. char **for_list = NULL;
  9058. #endif
  9059. smallint last_followup;
  9060. smalluint rcode;
  9061. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9062. smalluint cond_code = 0;
  9063. #else
  9064. enum { cond_code = 0 };
  9065. #endif
  9066. #if HAS_KEYWORDS
  9067. smallint rword; /* RES_foo */
  9068. smallint last_rword; /* ditto */
  9069. #endif
  9070. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  9071. debug_enter();
  9072. #if ENABLE_HUSH_LOOPS
  9073. /* Check syntax for "for" */
  9074. {
  9075. struct pipe *cpipe;
  9076. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9077. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9078. continue;
  9079. /* current word is FOR or IN (BOLD in comments below) */
  9080. if (cpipe->next == NULL) {
  9081. syntax_error("malformed for");
  9082. debug_leave();
  9083. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9084. return 1;
  9085. }
  9086. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9087. if (cpipe->next->res_word == RES_DO)
  9088. continue;
  9089. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9090. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9091. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9092. ) {
  9093. syntax_error("malformed for");
  9094. debug_leave();
  9095. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9096. return 1;
  9097. }
  9098. }
  9099. }
  9100. #endif
  9101. /* Past this point, all code paths should jump to ret: label
  9102. * in order to return, no direct "return" statements please.
  9103. * This helps to ensure that no memory is leaked. */
  9104. #if ENABLE_HUSH_JOB
  9105. G.run_list_level++;
  9106. #endif
  9107. #if HAS_KEYWORDS
  9108. rword = RES_NONE;
  9109. last_rword = RES_XXXX;
  9110. #endif
  9111. last_followup = PIPE_SEQ;
  9112. rcode = G.last_exitcode;
  9113. /* Go through list of pipes, (maybe) executing them. */
  9114. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9115. int r;
  9116. int sv_errexit_depth;
  9117. if (G.flag_SIGINT)
  9118. break;
  9119. if (G_flag_return_in_progress == 1)
  9120. break;
  9121. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9122. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  9123. rword, cond_code, last_rword);
  9124. sv_errexit_depth = G.errexit_depth;
  9125. if (
  9126. #if ENABLE_HUSH_IF
  9127. rword == RES_IF || rword == RES_ELIF ||
  9128. #endif
  9129. pi->followup != PIPE_SEQ
  9130. ) {
  9131. G.errexit_depth++;
  9132. }
  9133. #if ENABLE_HUSH_LOOPS
  9134. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9135. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9136. ) {
  9137. /* start of a loop: remember where loop starts */
  9138. loop_top = pi;
  9139. G.depth_of_loop++;
  9140. }
  9141. #endif
  9142. /* Still in the same "if...", "then..." or "do..." branch? */
  9143. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9144. if ((rcode == 0 && last_followup == PIPE_OR)
  9145. || (rcode != 0 && last_followup == PIPE_AND)
  9146. ) {
  9147. /* It is "<true> || CMD" or "<false> && CMD"
  9148. * and we should not execute CMD */
  9149. debug_printf_exec("skipped cmd because of || or &&\n");
  9150. last_followup = pi->followup;
  9151. goto dont_check_jobs_but_continue;
  9152. }
  9153. }
  9154. last_followup = pi->followup;
  9155. IF_HAS_KEYWORDS(last_rword = rword;)
  9156. #if ENABLE_HUSH_IF
  9157. if (cond_code) {
  9158. if (rword == RES_THEN) {
  9159. /* if false; then ... fi has exitcode 0! */
  9160. G.last_exitcode = rcode = EXIT_SUCCESS;
  9161. /* "if <false> THEN cmd": skip cmd */
  9162. continue;
  9163. }
  9164. } else {
  9165. if (rword == RES_ELSE || rword == RES_ELIF) {
  9166. /* "if <true> then ... ELSE/ELIF cmd":
  9167. * skip cmd and all following ones */
  9168. break;
  9169. }
  9170. }
  9171. #endif
  9172. #if ENABLE_HUSH_LOOPS
  9173. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9174. if (!for_lcur) {
  9175. /* first loop through for */
  9176. static const char encoded_dollar_at[] ALIGN1 = {
  9177. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9178. }; /* encoded representation of "$@" */
  9179. static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
  9180. encoded_dollar_at, NULL
  9181. }; /* argv list with one element: "$@" */
  9182. char **vals;
  9183. G.last_exitcode = rcode = EXIT_SUCCESS;
  9184. vals = (char**)encoded_dollar_at_argv;
  9185. if (pi->next->res_word == RES_IN) {
  9186. /* if no variable values after "in" we skip "for" */
  9187. if (!pi->next->cmds[0].argv) {
  9188. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9189. break;
  9190. }
  9191. vals = pi->next->cmds[0].argv;
  9192. } /* else: "for var; do..." -> assume "$@" list */
  9193. /* create list of variable values */
  9194. debug_print_strings("for_list made from", vals);
  9195. for_list = expand_strvec_to_strvec(vals);
  9196. for_lcur = for_list;
  9197. debug_print_strings("for_list", for_list);
  9198. }
  9199. if (!*for_lcur) {
  9200. /* "for" loop is over, clean up */
  9201. free(for_list);
  9202. for_list = NULL;
  9203. for_lcur = NULL;
  9204. break;
  9205. }
  9206. /* Insert next value from for_lcur */
  9207. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9208. set_local_var_from_halves(pi->cmds[0].argv[0], *for_lcur++);
  9209. continue;
  9210. }
  9211. if (rword == RES_IN) {
  9212. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9213. }
  9214. if (rword == RES_DONE) {
  9215. continue; /* "done" has no cmds too */
  9216. }
  9217. #endif
  9218. #if ENABLE_HUSH_CASE
  9219. if (rword == RES_CASE) {
  9220. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9221. case_word = expand_string_to_string(pi->cmds->argv[0],
  9222. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9223. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9224. //unbackslash(case_word);
  9225. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9226. continue;
  9227. }
  9228. if (rword == RES_MATCH) {
  9229. char **argv;
  9230. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9231. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9232. break;
  9233. /* all prev words didn't match, does this one match? */
  9234. argv = pi->cmds->argv;
  9235. while (*argv) {
  9236. char *pattern;
  9237. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9238. pattern = expand_string_to_string(*argv,
  9239. EXP_FLAG_ESC_GLOB_CHARS,
  9240. /*unbackslash:*/ 0
  9241. );
  9242. /* TODO: which FNM_xxx flags to use? */
  9243. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9244. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9245. pattern, case_word, cond_code);
  9246. free(pattern);
  9247. if (cond_code == 0) {
  9248. /* match! we will execute this branch */
  9249. free(case_word);
  9250. case_word = NULL; /* make future "word)" stop */
  9251. break;
  9252. }
  9253. argv++;
  9254. }
  9255. continue;
  9256. }
  9257. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9258. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9259. if (cond_code != 0)
  9260. continue; /* not matched yet, skip this pipe */
  9261. }
  9262. if (rword == RES_ESAC) {
  9263. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9264. if (case_word) {
  9265. /* "case" did not match anything: still set $? (to 0) */
  9266. G.last_exitcode = rcode = EXIT_SUCCESS;
  9267. }
  9268. }
  9269. #endif
  9270. /* Just pressing <enter> in shell should check for jobs.
  9271. * OTOH, in non-interactive shell this is useless
  9272. * and only leads to extra job checks */
  9273. if (pi->num_cmds == 0) {
  9274. if (G_interactive_fd)
  9275. goto check_jobs_and_continue;
  9276. continue;
  9277. }
  9278. /* After analyzing all keywords and conditions, we decided
  9279. * to execute this pipe. NB: have to do checkjobs(NULL)
  9280. * after run_pipe to collect any background children,
  9281. * even if list execution is to be stopped. */
  9282. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9283. #if ENABLE_HUSH_LOOPS
  9284. G.flag_break_continue = 0;
  9285. #endif
  9286. rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
  9287. /* NB: rcode is a smalluint, r is int */
  9288. if (r != -1) {
  9289. /* We ran a builtin, function, or group.
  9290. * rcode is already known
  9291. * and we don't need to wait for anything. */
  9292. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9293. G.last_exitcode = rcode;
  9294. check_and_run_traps();
  9295. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9296. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9297. #endif
  9298. #if ENABLE_HUSH_LOOPS
  9299. /* Was it "break" or "continue"? */
  9300. if (G.flag_break_continue) {
  9301. smallint fbc = G.flag_break_continue;
  9302. /* We might fall into outer *loop*,
  9303. * don't want to break it too */
  9304. if (loop_top) {
  9305. G.depth_break_continue--;
  9306. if (G.depth_break_continue == 0)
  9307. G.flag_break_continue = 0;
  9308. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9309. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9310. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9311. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9312. break;
  9313. }
  9314. /* "continue": simulate end of loop */
  9315. rword = RES_DONE;
  9316. continue;
  9317. }
  9318. #endif
  9319. if (G_flag_return_in_progress == 1) {
  9320. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9321. break;
  9322. }
  9323. } else if (pi->followup == PIPE_BG) {
  9324. /* What does bash do with attempts to background builtins? */
  9325. /* even bash 3.2 doesn't do that well with nested bg:
  9326. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9327. * I'm NOT treating inner &'s as jobs */
  9328. #if ENABLE_HUSH_JOB
  9329. if (G.run_list_level == 1)
  9330. insert_job_into_table(pi);
  9331. #endif
  9332. /* Last command's pid goes to $! */
  9333. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9334. G.last_bg_pid_exitcode = 0;
  9335. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9336. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9337. rcode = EXIT_SUCCESS;
  9338. goto check_traps;
  9339. } else {
  9340. #if ENABLE_HUSH_JOB
  9341. if (G.run_list_level == 1 && G_interactive_fd) {
  9342. /* Waits for completion, then fg's main shell */
  9343. rcode = checkjobs_and_fg_shell(pi);
  9344. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9345. goto check_traps;
  9346. }
  9347. #endif
  9348. /* This one just waits for completion */
  9349. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9350. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9351. check_traps:
  9352. G.last_exitcode = rcode;
  9353. check_and_run_traps();
  9354. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9355. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9356. #endif
  9357. }
  9358. /* Handle "set -e" */
  9359. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9360. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9361. if (G.errexit_depth == 0)
  9362. hush_exit(rcode);
  9363. }
  9364. G.errexit_depth = sv_errexit_depth;
  9365. /* Analyze how result affects subsequent commands */
  9366. #if ENABLE_HUSH_IF
  9367. if (rword == RES_IF || rword == RES_ELIF)
  9368. cond_code = rcode;
  9369. #endif
  9370. check_jobs_and_continue:
  9371. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9372. dont_check_jobs_but_continue: ;
  9373. #if ENABLE_HUSH_LOOPS
  9374. /* Beware of "while false; true; do ..."! */
  9375. if (pi->next
  9376. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9377. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9378. ) {
  9379. if (rword == RES_WHILE) {
  9380. if (rcode) {
  9381. /* "while false; do...done" - exitcode 0 */
  9382. G.last_exitcode = rcode = EXIT_SUCCESS;
  9383. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9384. break;
  9385. }
  9386. }
  9387. if (rword == RES_UNTIL) {
  9388. if (!rcode) {
  9389. debug_printf_exec(": until expr is true: breaking\n");
  9390. break;
  9391. }
  9392. }
  9393. }
  9394. #endif
  9395. } /* for (pi) */
  9396. #if ENABLE_HUSH_JOB
  9397. G.run_list_level--;
  9398. #endif
  9399. #if ENABLE_HUSH_LOOPS
  9400. if (loop_top)
  9401. G.depth_of_loop--;
  9402. free(for_list);
  9403. #endif
  9404. #if ENABLE_HUSH_CASE
  9405. free(case_word);
  9406. #endif
  9407. debug_leave();
  9408. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9409. return rcode;
  9410. }
  9411. /* Select which version we will use */
  9412. static int run_and_free_list(struct pipe *pi)
  9413. {
  9414. int rcode = 0;
  9415. debug_printf_exec("run_and_free_list entered\n");
  9416. if (!G.o_opt[OPT_O_NOEXEC]) {
  9417. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9418. rcode = run_list(pi);
  9419. }
  9420. /* free_pipe_list has the side effect of clearing memory.
  9421. * In the long run that function can be merged with run_list,
  9422. * but doing that now would hobble the debugging effort. */
  9423. free_pipe_list(pi);
  9424. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9425. return rcode;
  9426. }
  9427. static void install_sighandlers(unsigned mask)
  9428. {
  9429. sighandler_t old_handler;
  9430. unsigned sig = 0;
  9431. while ((mask >>= 1) != 0) {
  9432. sig++;
  9433. if (!(mask & 1))
  9434. continue;
  9435. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9436. /* POSIX allows shell to re-enable SIGCHLD
  9437. * even if it was SIG_IGN on entry.
  9438. * Therefore we skip IGN check for it:
  9439. */
  9440. if (sig == SIGCHLD)
  9441. continue;
  9442. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9443. * Try:
  9444. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9445. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9446. */
  9447. if (sig == SIGHUP && G_interactive_fd)
  9448. continue;
  9449. /* Unless one of the above signals, is it SIG_IGN? */
  9450. if (old_handler == SIG_IGN) {
  9451. /* oops... restore back to IGN, and record this fact */
  9452. install_sighandler(sig, old_handler);
  9453. #if ENABLE_HUSH_TRAP
  9454. if (!G_traps)
  9455. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9456. free(G_traps[sig]);
  9457. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9458. #endif
  9459. }
  9460. }
  9461. }
  9462. /* Called a few times only (or even once if "sh -c") */
  9463. static void install_special_sighandlers(void)
  9464. {
  9465. unsigned mask;
  9466. /* Which signals are shell-special? */
  9467. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9468. if (G_interactive_fd) {
  9469. mask |= SPECIAL_INTERACTIVE_SIGS;
  9470. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9471. mask |= SPECIAL_JOBSTOP_SIGS;
  9472. }
  9473. /* Careful, do not re-install handlers we already installed */
  9474. if (G.special_sig_mask != mask) {
  9475. unsigned diff = mask & ~G.special_sig_mask;
  9476. G.special_sig_mask = mask;
  9477. install_sighandlers(diff);
  9478. }
  9479. }
  9480. #if ENABLE_HUSH_JOB
  9481. /* helper */
  9482. /* Set handlers to restore tty pgrp and exit */
  9483. static void install_fatal_sighandlers(void)
  9484. {
  9485. unsigned mask;
  9486. /* We will restore tty pgrp on these signals */
  9487. mask = 0
  9488. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9489. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9490. + (1 << SIGBUS ) * HUSH_DEBUG
  9491. + (1 << SIGSEGV) * HUSH_DEBUG
  9492. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9493. + (1 << SIGABRT)
  9494. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9495. + (1 << SIGPIPE)
  9496. + (1 << SIGALRM)
  9497. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9498. * if we aren't interactive... but in this case
  9499. * we never want to restore pgrp on exit, and this fn is not called
  9500. */
  9501. /*+ (1 << SIGHUP )*/
  9502. /*+ (1 << SIGTERM)*/
  9503. /*+ (1 << SIGINT )*/
  9504. ;
  9505. G_fatal_sig_mask = mask;
  9506. install_sighandlers(mask);
  9507. }
  9508. #endif
  9509. static int set_mode(int state, char mode, const char *o_opt)
  9510. {
  9511. int idx;
  9512. switch (mode) {
  9513. case 'n':
  9514. /* set -n has no effect in interactive shell */
  9515. /* Try: while set -n; do echo $-; done */
  9516. if (!G_interactive_fd)
  9517. G.o_opt[OPT_O_NOEXEC] = state;
  9518. break;
  9519. case 'x':
  9520. IF_HUSH_MODE_X(G_x_mode = state;)
  9521. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9522. break;
  9523. case 'e':
  9524. G.o_opt[OPT_O_ERREXIT] = state;
  9525. break;
  9526. case 'o':
  9527. if (!o_opt) {
  9528. /* "set -o" or "set +o" without parameter.
  9529. * in bash, set -o produces this output:
  9530. * pipefail off
  9531. * and set +o:
  9532. * set +o pipefail
  9533. * We always use the second form.
  9534. */
  9535. const char *p = o_opt_strings;
  9536. idx = 0;
  9537. while (*p) {
  9538. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9539. idx++;
  9540. p += strlen(p) + 1;
  9541. }
  9542. break;
  9543. }
  9544. idx = index_in_strings(o_opt_strings, o_opt);
  9545. if (idx >= 0) {
  9546. G.o_opt[idx] = state;
  9547. break;
  9548. }
  9549. /* fall through to error */
  9550. default:
  9551. return EXIT_FAILURE;
  9552. }
  9553. return EXIT_SUCCESS;
  9554. }
  9555. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9556. int hush_main(int argc, char **argv)
  9557. {
  9558. pid_t cached_getpid;
  9559. enum {
  9560. OPT_login = (1 << 0),
  9561. };
  9562. unsigned flags;
  9563. #if !BB_MMU
  9564. unsigned builtin_argc = 0;
  9565. #endif
  9566. char **e;
  9567. struct variable *cur_var;
  9568. struct variable *shell_ver;
  9569. INIT_G();
  9570. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9571. G.last_exitcode = EXIT_SUCCESS;
  9572. #if ENABLE_HUSH_TRAP
  9573. # if ENABLE_HUSH_FUNCTIONS
  9574. G.return_exitcode = -1;
  9575. # endif
  9576. G.pre_trap_exitcode = -1;
  9577. #endif
  9578. #if ENABLE_HUSH_FAST
  9579. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9580. #endif
  9581. #if !BB_MMU
  9582. G.argv0_for_re_execing = argv[0];
  9583. #endif
  9584. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9585. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9586. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9587. /* Deal with HUSH_VERSION */
  9588. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9589. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9590. shell_ver = xzalloc(sizeof(*shell_ver));
  9591. shell_ver->flg_export = 1;
  9592. shell_ver->flg_read_only = 1;
  9593. /* Code which handles ${var<op>...} needs writable values for all variables,
  9594. * therefore we xstrdup: */
  9595. shell_ver->varstr = xstrdup(hush_version_str);
  9596. /* Create shell local variables from the values
  9597. * currently living in the environment */
  9598. G.top_var = shell_ver;
  9599. cur_var = G.top_var;
  9600. e = environ;
  9601. if (e) while (*e) {
  9602. char *value = strchr(*e, '=');
  9603. if (value) { /* paranoia */
  9604. cur_var->next = xzalloc(sizeof(*cur_var));
  9605. cur_var = cur_var->next;
  9606. cur_var->varstr = *e;
  9607. cur_var->max_len = strlen(*e);
  9608. cur_var->flg_export = 1;
  9609. }
  9610. e++;
  9611. }
  9612. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9613. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9614. putenv(shell_ver->varstr);
  9615. /* Export PWD */
  9616. set_pwd_var(SETFLAG_EXPORT);
  9617. #if BASH_HOSTNAME_VAR
  9618. /* Set (but not export) HOSTNAME unless already set */
  9619. if (!get_local_var_value("HOSTNAME")) {
  9620. struct utsname uts;
  9621. uname(&uts);
  9622. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9623. }
  9624. #endif
  9625. /* IFS is not inherited from the parent environment */
  9626. set_local_var_from_halves("IFS", defifs);
  9627. if (!get_local_var_value("PATH"))
  9628. set_local_var_from_halves("PATH", bb_default_root_path);
  9629. /* PS1/PS2 are set later, if we determine that we are interactive */
  9630. /* bash also exports SHLVL and _,
  9631. * and sets (but doesn't export) the following variables:
  9632. * BASH=/bin/bash
  9633. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9634. * BASH_VERSION='3.2.0(1)-release'
  9635. * HOSTTYPE=i386
  9636. * MACHTYPE=i386-pc-linux-gnu
  9637. * OSTYPE=linux-gnu
  9638. * PPID=<NNNNN> - we also do it elsewhere
  9639. * EUID=<NNNNN>
  9640. * UID=<NNNNN>
  9641. * GROUPS=()
  9642. * LINES=<NNN>
  9643. * COLUMNS=<NNN>
  9644. * BASH_ARGC=()
  9645. * BASH_ARGV=()
  9646. * BASH_LINENO=()
  9647. * BASH_SOURCE=()
  9648. * DIRSTACK=()
  9649. * PIPESTATUS=([0]="0")
  9650. * HISTFILE=/<xxx>/.bash_history
  9651. * HISTFILESIZE=500
  9652. * HISTSIZE=500
  9653. * MAILCHECK=60
  9654. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9655. * SHELL=/bin/bash
  9656. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9657. * TERM=dumb
  9658. * OPTERR=1
  9659. * OPTIND=1
  9660. * PS4='+ '
  9661. */
  9662. #if NUM_SCRIPTS > 0
  9663. if (argc < 0) {
  9664. char *script = get_script_content(-argc - 1);
  9665. G.global_argv = argv;
  9666. G.global_argc = string_array_len(argv);
  9667. //install_special_sighandlers(); - needed?
  9668. parse_and_run_string(script);
  9669. goto final_return;
  9670. }
  9671. #endif
  9672. /* Initialize some more globals to non-zero values */
  9673. die_func = restore_ttypgrp_and__exit;
  9674. /* Shell is non-interactive at first. We need to call
  9675. * install_special_sighandlers() if we are going to execute "sh <script>",
  9676. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9677. * If we later decide that we are interactive, we run install_special_sighandlers()
  9678. * in order to intercept (more) signals.
  9679. */
  9680. /* Parse options */
  9681. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9682. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9683. while (1) {
  9684. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9685. "cexinsl"
  9686. #if !BB_MMU
  9687. "<:$:R:V:"
  9688. # if ENABLE_HUSH_FUNCTIONS
  9689. "F:"
  9690. # endif
  9691. #endif
  9692. );
  9693. if (opt <= 0)
  9694. break;
  9695. switch (opt) {
  9696. case 'c':
  9697. /* Note: -c is not an option with param!
  9698. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9699. */
  9700. G.opt_c = 1;
  9701. break;
  9702. case 'i':
  9703. /* Well, we cannot just declare interactiveness,
  9704. * we have to have some stuff (ctty, etc) */
  9705. /* G_interactive_fd++; */
  9706. //There are a few cases where bash -i -c 'SCRIPT'
  9707. //has visible effect (differs from bash -c 'SCRIPT'):
  9708. //it ignores TERM:
  9709. // bash -i -c 'kill $$; echo ALIVE'
  9710. // ALIVE
  9711. //it resets SIG_IGNed HUP to SIG_DFL:
  9712. // trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
  9713. // Hangup [the message is not printed by bash, it's the shell which started it]
  9714. //is talkative about jobs and exiting:
  9715. // bash -i -c 'sleep 1 & exit'
  9716. // [1] 16170
  9717. // exit
  9718. //includes $ENV file (only if run as "sh"):
  9719. // echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
  9720. // last: cannot open /var/log/wtmp: No such file or directory
  9721. // HERE
  9722. //(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
  9723. //
  9724. //ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
  9725. //(this may be a bug, bash does not do this).
  9726. //(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
  9727. //
  9728. //None of the above feel like useful features people would rely on.
  9729. break;
  9730. case 's':
  9731. G.opt_s = 1;
  9732. break;
  9733. case 'l':
  9734. flags |= OPT_login;
  9735. break;
  9736. #if !BB_MMU
  9737. case '<': /* "big heredoc" support */
  9738. full_write1_str(optarg);
  9739. _exit(0);
  9740. case '$': {
  9741. unsigned long long empty_trap_mask;
  9742. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9743. optarg++;
  9744. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9745. optarg++;
  9746. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9747. optarg++;
  9748. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9749. optarg++;
  9750. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9751. optarg++;
  9752. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9753. if (empty_trap_mask != 0) {
  9754. IF_HUSH_TRAP(int sig;)
  9755. install_special_sighandlers();
  9756. # if ENABLE_HUSH_TRAP
  9757. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9758. for (sig = 1; sig < NSIG; sig++) {
  9759. if (empty_trap_mask & (1LL << sig)) {
  9760. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9761. install_sighandler(sig, SIG_IGN);
  9762. }
  9763. }
  9764. # endif
  9765. }
  9766. # if ENABLE_HUSH_LOOPS
  9767. optarg++;
  9768. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9769. # endif
  9770. /* Suppress "killed by signal" message, -$ hack is used
  9771. * for subshells: echo `sh -c 'kill -9 $$'`
  9772. * should be silent.
  9773. */
  9774. IF_HUSH_JOB(G.run_list_level = 1;)
  9775. # if ENABLE_HUSH_FUNCTIONS
  9776. /* nommu uses re-exec trick for "... | func | ...",
  9777. * should allow "return".
  9778. * This accidentally allows returns in subshells.
  9779. */
  9780. G_flag_return_in_progress = -1;
  9781. # endif
  9782. break;
  9783. }
  9784. case 'R':
  9785. case 'V':
  9786. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9787. break;
  9788. # if ENABLE_HUSH_FUNCTIONS
  9789. case 'F': {
  9790. struct function *funcp = new_function(optarg);
  9791. /* funcp->name is already set to optarg */
  9792. /* funcp->body is set to NULL. It's a special case. */
  9793. funcp->body_as_string = argv[optind];
  9794. optind++;
  9795. break;
  9796. }
  9797. # endif
  9798. #endif
  9799. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9800. /*case 'n':*/
  9801. /*case 'x':*/
  9802. /*case 'e':*/
  9803. default:
  9804. if (set_mode(1, opt, NULL) == 0) /* no error */
  9805. break;
  9806. bb_show_usage();
  9807. }
  9808. } /* option parsing loop */
  9809. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9810. G.global_argc = argc - (optind - 1);
  9811. G.global_argv = argv + (optind - 1);
  9812. G.global_argv[0] = argv[0];
  9813. /* If we are login shell... */
  9814. if (flags & OPT_login) {
  9815. const char *hp = NULL;
  9816. HFILE *input;
  9817. debug_printf("sourcing /etc/profile\n");
  9818. input = hfopen("/etc/profile");
  9819. run_profile:
  9820. if (input != NULL) {
  9821. install_special_sighandlers();
  9822. parse_and_run_file(input);
  9823. hfclose(input);
  9824. }
  9825. /* bash: after sourcing /etc/profile,
  9826. * tries to source (in the given order):
  9827. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9828. * stopping on first found. --noprofile turns this off.
  9829. * bash also sources ~/.bash_logout on exit.
  9830. * If called as sh, skips .bash_XXX files.
  9831. */
  9832. if (!hp) { /* unless we looped on the "goto" already */
  9833. hp = get_local_var_value("HOME");
  9834. if (hp && hp[0]) {
  9835. debug_printf("sourcing ~/.profile\n");
  9836. hp = concat_path_file(hp, ".profile");
  9837. input = hfopen(hp);
  9838. free((char*)hp);
  9839. goto run_profile;
  9840. }
  9841. }
  9842. }
  9843. /* -c takes effect *after* -l */
  9844. if (G.opt_c) {
  9845. /* Possibilities:
  9846. * sh ... -c 'script'
  9847. * sh ... -c 'script' ARG0 [ARG1...]
  9848. * On NOMMU, if builtin_argc != 0,
  9849. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9850. * "" needs to be replaced with NULL
  9851. * and BARGV vector fed to builtin function.
  9852. * Note: the form without ARG0 never happens:
  9853. * sh ... -c 'builtin' BARGV... ""
  9854. */
  9855. char *script;
  9856. install_special_sighandlers();
  9857. G.global_argc--;
  9858. G.global_argv++;
  9859. #if !BB_MMU
  9860. if (builtin_argc) {
  9861. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9862. const struct built_in_command *x;
  9863. x = find_builtin(G.global_argv[0]);
  9864. if (x) { /* paranoia */
  9865. argv = G.global_argv;
  9866. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9867. G.global_argv += builtin_argc + 1;
  9868. G.global_argv[-1] = NULL; /* replace "" */
  9869. G.last_exitcode = x->b_function(argv);
  9870. }
  9871. goto final_return;
  9872. }
  9873. #endif
  9874. script = G.global_argv[0];
  9875. if (!script)
  9876. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9877. if (!G.global_argv[1]) {
  9878. /* -c 'script' (no params): prevent empty $0 */
  9879. G.global_argv[0] = argv[0];
  9880. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9881. G.global_argc--;
  9882. G.global_argv++;
  9883. }
  9884. parse_and_run_string(script);
  9885. goto final_return;
  9886. }
  9887. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9888. if (!G.opt_s && G.global_argv[1]) {
  9889. HFILE *input;
  9890. /*
  9891. * "bash <script>" (which is never interactive (unless -i?))
  9892. * sources $BASH_ENV here (without scanning $PATH).
  9893. * If called as sh, does the same but with $ENV.
  9894. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9895. */
  9896. G.global_argc--;
  9897. G.global_argv++;
  9898. debug_printf("running script '%s'\n", G.global_argv[0]);
  9899. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9900. input = hfopen(G.global_argv[0]);
  9901. if (!input) {
  9902. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9903. }
  9904. xfunc_error_retval = 1;
  9905. install_special_sighandlers();
  9906. parse_and_run_file(input);
  9907. #if ENABLE_FEATURE_CLEAN_UP
  9908. hfclose(input);
  9909. #endif
  9910. goto final_return;
  9911. }
  9912. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9913. G.opt_s = 1;
  9914. /* Up to here, shell was non-interactive. Now it may become one.
  9915. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9916. */
  9917. /* A shell is interactive if the '-i' flag was given,
  9918. * or if all of the following conditions are met:
  9919. * no -c command
  9920. * no arguments remaining or the -s flag given
  9921. * standard input is a terminal
  9922. * standard output is a terminal
  9923. * Refer to Posix.2, the description of the 'sh' utility.
  9924. */
  9925. #if ENABLE_HUSH_JOB
  9926. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9927. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9928. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9929. if (G_saved_tty_pgrp < 0)
  9930. G_saved_tty_pgrp = 0;
  9931. /* try to dup stdin to high fd#, >= 255 */
  9932. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9933. if (G_interactive_fd < 0) {
  9934. /* try to dup to any fd */
  9935. G_interactive_fd = dup(STDIN_FILENO);
  9936. if (G_interactive_fd < 0) {
  9937. /* give up */
  9938. G_interactive_fd = 0;
  9939. G_saved_tty_pgrp = 0;
  9940. }
  9941. }
  9942. }
  9943. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9944. if (G_interactive_fd) {
  9945. close_on_exec_on(G_interactive_fd);
  9946. if (G_saved_tty_pgrp) {
  9947. /* If we were run as 'hush &', sleep until we are
  9948. * in the foreground (tty pgrp == our pgrp).
  9949. * If we get started under a job aware app (like bash),
  9950. * make sure we are now in charge so we don't fight over
  9951. * who gets the foreground */
  9952. while (1) {
  9953. pid_t shell_pgrp = getpgrp();
  9954. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9955. if (G_saved_tty_pgrp == shell_pgrp)
  9956. break;
  9957. /* send TTIN to ourself (should stop us) */
  9958. kill(- shell_pgrp, SIGTTIN);
  9959. }
  9960. }
  9961. /* Install more signal handlers */
  9962. install_special_sighandlers();
  9963. if (G_saved_tty_pgrp) {
  9964. /* Set other signals to restore saved_tty_pgrp */
  9965. install_fatal_sighandlers();
  9966. /* Put ourselves in our own process group
  9967. * (bash, too, does this only if ctty is available) */
  9968. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9969. /* Grab control of the terminal */
  9970. tcsetpgrp(G_interactive_fd, cached_getpid);
  9971. }
  9972. enable_restore_tty_pgrp_on_exit();
  9973. # if ENABLE_FEATURE_EDITING
  9974. G.line_input_state = new_line_input_t(FOR_SHELL);
  9975. # if ENABLE_FEATURE_TAB_COMPLETION
  9976. G.line_input_state->get_exe_name = get_builtin_name;
  9977. # endif
  9978. # if EDITING_HAS_sh_get_var
  9979. G.line_input_state->sh_get_var = get_local_var_value;
  9980. # endif
  9981. # endif
  9982. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9983. {
  9984. const char *hp = get_local_var_value("HISTFILE");
  9985. if (!hp) {
  9986. hp = get_local_var_value("HOME");
  9987. if (hp)
  9988. hp = concat_path_file(hp, ".hush_history");
  9989. } else {
  9990. hp = xstrdup(hp);
  9991. }
  9992. if (hp) {
  9993. G.line_input_state->hist_file = hp;
  9994. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9995. }
  9996. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9997. hp = get_local_var_value("HISTFILESIZE");
  9998. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9999. # endif
  10000. }
  10001. # endif
  10002. } else {
  10003. install_special_sighandlers();
  10004. }
  10005. #elif ENABLE_HUSH_INTERACTIVE
  10006. /* No job control compiled in, only prompt/line editing */
  10007. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10008. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10009. if (G_interactive_fd < 0) {
  10010. /* try to dup to any fd */
  10011. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  10012. if (G_interactive_fd < 0)
  10013. /* give up */
  10014. G_interactive_fd = 0;
  10015. }
  10016. }
  10017. if (G_interactive_fd) {
  10018. close_on_exec_on(G_interactive_fd);
  10019. }
  10020. install_special_sighandlers();
  10021. #else
  10022. /* We have interactiveness code disabled */
  10023. install_special_sighandlers();
  10024. #endif
  10025. /* bash:
  10026. * if interactive but not a login shell, sources ~/.bashrc
  10027. * (--norc turns this off, --rcfile <file> overrides)
  10028. */
  10029. if (G_interactive_fd) {
  10030. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  10031. /* Set (but not export) PS1/2 unless already set */
  10032. if (!get_local_var_value("PS1"))
  10033. set_local_var_from_halves("PS1", "\\w \\$ ");
  10034. if (!get_local_var_value("PS2"))
  10035. set_local_var_from_halves("PS2", "> ");
  10036. #endif
  10037. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  10038. /* note: ash and hush share this string */
  10039. printf("\n\n%s %s\n"
  10040. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  10041. "\n",
  10042. bb_banner,
  10043. "hush - the humble shell"
  10044. );
  10045. }
  10046. }
  10047. parse_and_run_file(hfopen(NULL)); /* stdin */
  10048. final_return:
  10049. hush_exit(G.last_exitcode);
  10050. }
  10051. /*
  10052. * Built-ins
  10053. */
  10054. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  10055. {
  10056. return 0;
  10057. }
  10058. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  10059. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  10060. {
  10061. int argc = string_array_len(argv);
  10062. return applet_main_func(argc, argv);
  10063. }
  10064. #endif
  10065. #if ENABLE_HUSH_TEST || BASH_TEST2
  10066. static int FAST_FUNC builtin_test(char **argv)
  10067. {
  10068. return run_applet_main(argv, test_main);
  10069. }
  10070. #endif
  10071. #if ENABLE_HUSH_ECHO
  10072. static int FAST_FUNC builtin_echo(char **argv)
  10073. {
  10074. return run_applet_main(argv, echo_main);
  10075. }
  10076. #endif
  10077. #if ENABLE_HUSH_PRINTF
  10078. static int FAST_FUNC builtin_printf(char **argv)
  10079. {
  10080. return run_applet_main(argv, printf_main);
  10081. }
  10082. #endif
  10083. #if ENABLE_HUSH_HELP
  10084. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10085. {
  10086. const struct built_in_command *x;
  10087. printf(
  10088. "Built-in commands:\n"
  10089. "------------------\n");
  10090. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10091. if (x->b_descr)
  10092. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10093. }
  10094. return EXIT_SUCCESS;
  10095. }
  10096. #endif
  10097. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10098. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10099. {
  10100. show_history(G.line_input_state);
  10101. return EXIT_SUCCESS;
  10102. }
  10103. #endif
  10104. static char **skip_dash_dash(char **argv)
  10105. {
  10106. argv++;
  10107. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  10108. argv++;
  10109. return argv;
  10110. }
  10111. static int FAST_FUNC builtin_cd(char **argv)
  10112. {
  10113. const char *newdir;
  10114. argv = skip_dash_dash(argv);
  10115. newdir = argv[0];
  10116. if (newdir == NULL) {
  10117. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10118. * bash says "bash: cd: HOME not set" and does nothing
  10119. * (exitcode 1)
  10120. */
  10121. const char *home = get_local_var_value("HOME");
  10122. newdir = home ? home : "/";
  10123. }
  10124. if (chdir(newdir)) {
  10125. /* Mimic bash message exactly */
  10126. bb_perror_msg("cd: %s", newdir);
  10127. return EXIT_FAILURE;
  10128. }
  10129. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10130. * Note: do not enforce exporting. If PWD was unset or unexported,
  10131. * set it again, but do not export. bash does the same.
  10132. */
  10133. set_pwd_var(/*flag:*/ 0);
  10134. return EXIT_SUCCESS;
  10135. }
  10136. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10137. {
  10138. puts(get_cwd(0));
  10139. return EXIT_SUCCESS;
  10140. }
  10141. static int FAST_FUNC builtin_eval(char **argv)
  10142. {
  10143. argv = skip_dash_dash(argv);
  10144. if (!argv[0])
  10145. return EXIT_SUCCESS;
  10146. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10147. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10148. if (!argv[1]) {
  10149. /* bash:
  10150. * eval "echo Hi; done" ("done" is syntax error):
  10151. * "echo Hi" will not execute too.
  10152. */
  10153. parse_and_run_string(argv[0]);
  10154. } else {
  10155. /* "The eval utility shall construct a command by
  10156. * concatenating arguments together, separating
  10157. * each with a <space> character."
  10158. */
  10159. char *str, *p;
  10160. unsigned len = 0;
  10161. char **pp = argv;
  10162. do
  10163. len += strlen(*pp) + 1;
  10164. while (*++pp);
  10165. str = p = xmalloc(len);
  10166. pp = argv;
  10167. for (;;) {
  10168. p = stpcpy(p, *pp);
  10169. pp++;
  10170. if (!*pp)
  10171. break;
  10172. *p++ = ' ';
  10173. }
  10174. parse_and_run_string(str);
  10175. free(str);
  10176. }
  10177. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10178. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10179. return G.last_exitcode;
  10180. }
  10181. static int FAST_FUNC builtin_exec(char **argv)
  10182. {
  10183. argv = skip_dash_dash(argv);
  10184. if (argv[0] == NULL)
  10185. return EXIT_SUCCESS; /* bash does this */
  10186. /* Careful: we can end up here after [v]fork. Do not restore
  10187. * tty pgrp then, only top-level shell process does that */
  10188. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10189. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10190. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10191. * open here. However, they are all CLOEXEC, and execv below
  10192. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10193. * it should show no extra open fds in the "ls" process.
  10194. * If we'd try to run builtins/NOEXECs, this would need improving.
  10195. */
  10196. //close_saved_fds_and_FILE_fds();
  10197. /* TODO: if exec fails, bash does NOT exit! We do.
  10198. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10199. * and tcsetpgrp, and this is inherently racy.
  10200. */
  10201. execvp_or_die(argv);
  10202. }
  10203. static int FAST_FUNC builtin_exit(char **argv)
  10204. {
  10205. debug_printf_exec("%s()\n", __func__);
  10206. /* interactive bash:
  10207. * # trap "echo EEE" EXIT
  10208. * # exit
  10209. * exit
  10210. * There are stopped jobs.
  10211. * (if there are _stopped_ jobs, running ones don't count)
  10212. * # exit
  10213. * exit
  10214. * EEE (then bash exits)
  10215. *
  10216. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10217. */
  10218. /* note: EXIT trap is run by hush_exit */
  10219. argv = skip_dash_dash(argv);
  10220. if (argv[0] == NULL) {
  10221. #if ENABLE_HUSH_TRAP
  10222. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10223. hush_exit(G.pre_trap_exitcode);
  10224. #endif
  10225. hush_exit(G.last_exitcode);
  10226. }
  10227. /* mimic bash: exit 123abc == exit 255 + error msg */
  10228. xfunc_error_retval = 255;
  10229. /* bash: exit -2 == exit 254, no error msg */
  10230. hush_exit(xatoi(argv[0]) & 0xff);
  10231. }
  10232. #if ENABLE_HUSH_TYPE
  10233. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10234. static int FAST_FUNC builtin_type(char **argv)
  10235. {
  10236. int ret = EXIT_SUCCESS;
  10237. while (*++argv) {
  10238. const char *type;
  10239. char *path = NULL;
  10240. if (0) {} /* make conditional compile easier below */
  10241. /*else if (find_alias(*argv))
  10242. type = "an alias";*/
  10243. # if ENABLE_HUSH_FUNCTIONS
  10244. else if (find_function(*argv))
  10245. type = "a function";
  10246. # endif
  10247. else if (find_builtin(*argv))
  10248. type = "a shell builtin";
  10249. else if ((path = find_in_path(*argv)) != NULL)
  10250. type = path;
  10251. else {
  10252. bb_error_msg("type: %s: not found", *argv);
  10253. ret = EXIT_FAILURE;
  10254. continue;
  10255. }
  10256. printf("%s is %s\n", *argv, type);
  10257. free(path);
  10258. }
  10259. return ret;
  10260. }
  10261. #endif
  10262. #if ENABLE_HUSH_READ
  10263. /* Interruptibility of read builtin in bash
  10264. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10265. *
  10266. * Empty trap makes read ignore corresponding signal, for any signal.
  10267. *
  10268. * SIGINT:
  10269. * - terminates non-interactive shell;
  10270. * - interrupts read in interactive shell;
  10271. * if it has non-empty trap:
  10272. * - executes trap and returns to command prompt in interactive shell;
  10273. * - executes trap and returns to read in non-interactive shell;
  10274. * SIGTERM:
  10275. * - is ignored (does not interrupt) read in interactive shell;
  10276. * - terminates non-interactive shell;
  10277. * if it has non-empty trap:
  10278. * - executes trap and returns to read;
  10279. * SIGHUP:
  10280. * - terminates shell (regardless of interactivity);
  10281. * if it has non-empty trap:
  10282. * - executes trap and returns to read;
  10283. * SIGCHLD from children:
  10284. * - does not interrupt read regardless of interactivity:
  10285. * try: sleep 1 & read x; echo $x
  10286. */
  10287. static int FAST_FUNC builtin_read(char **argv)
  10288. {
  10289. const char *r;
  10290. struct builtin_read_params params;
  10291. memset(&params, 0, sizeof(params));
  10292. /* "!": do not abort on errors.
  10293. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10294. */
  10295. params.read_flags = getopt32(argv,
  10296. # if BASH_READ_D
  10297. IF_NOT_HUSH_BASH_COMPAT("^")
  10298. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10299. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10300. # else
  10301. IF_NOT_HUSH_BASH_COMPAT("^")
  10302. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10303. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10304. # endif
  10305. //TODO: print "read: need variable name"
  10306. //for the case of !BASH "read" with no args (now it fails silently)
  10307. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10308. );
  10309. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10310. return EXIT_FAILURE;
  10311. argv += optind;
  10312. params.argv = argv;
  10313. params.setvar = set_local_var_from_halves;
  10314. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10315. again:
  10316. r = shell_builtin_read(&params);
  10317. if ((uintptr_t)r == 1 && errno == EINTR) {
  10318. unsigned sig = check_and_run_traps();
  10319. if (sig != SIGINT)
  10320. goto again;
  10321. }
  10322. if ((uintptr_t)r > 1) {
  10323. bb_simple_error_msg(r);
  10324. r = (char*)(uintptr_t)1;
  10325. }
  10326. return (uintptr_t)r;
  10327. }
  10328. #endif
  10329. #if ENABLE_HUSH_UMASK
  10330. static int FAST_FUNC builtin_umask(char **argv)
  10331. {
  10332. int rc;
  10333. mode_t mask;
  10334. rc = 1;
  10335. mask = umask(0);
  10336. argv = skip_dash_dash(argv);
  10337. if (argv[0]) {
  10338. mode_t old_mask = mask;
  10339. /* numeric umasks are taken as-is */
  10340. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10341. if (!isdigit(argv[0][0]))
  10342. mask ^= 0777;
  10343. mask = bb_parse_mode(argv[0], mask);
  10344. if (!isdigit(argv[0][0]))
  10345. mask ^= 0777;
  10346. if ((unsigned)mask > 0777) {
  10347. mask = old_mask;
  10348. /* bash messages:
  10349. * bash: umask: 'q': invalid symbolic mode operator
  10350. * bash: umask: 999: octal number out of range
  10351. */
  10352. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10353. rc = 0;
  10354. }
  10355. } else {
  10356. /* Mimic bash */
  10357. printf("%04o\n", (unsigned) mask);
  10358. /* fall through and restore mask which we set to 0 */
  10359. }
  10360. umask(mask);
  10361. return !rc; /* rc != 0 - success */
  10362. }
  10363. #endif
  10364. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10365. static void print_escaped(const char *s)
  10366. {
  10367. if (*s == '\'')
  10368. goto squote;
  10369. do {
  10370. const char *p = strchrnul(s, '\'');
  10371. /* print 'xxxx', possibly just '' */
  10372. printf("'%.*s'", (int)(p - s), s);
  10373. if (*p == '\0')
  10374. break;
  10375. s = p;
  10376. squote:
  10377. /* s points to '; print "'''...'''" */
  10378. putchar('"');
  10379. do putchar('\''); while (*++s == '\'');
  10380. putchar('"');
  10381. } while (*s);
  10382. }
  10383. #endif
  10384. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10385. static int helper_export_local(char **argv, unsigned flags)
  10386. {
  10387. do {
  10388. char *name = *argv;
  10389. const char *name_end = endofname(name);
  10390. if (*name_end == '\0') {
  10391. struct variable *var, **vpp;
  10392. vpp = get_ptr_to_local_var(name, name_end - name);
  10393. var = vpp ? *vpp : NULL;
  10394. if (flags & SETFLAG_UNEXPORT) {
  10395. /* export -n NAME (without =VALUE) */
  10396. if (var) {
  10397. var->flg_export = 0;
  10398. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10399. unsetenv(name);
  10400. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10401. continue;
  10402. }
  10403. if (flags & SETFLAG_EXPORT) {
  10404. /* export NAME (without =VALUE) */
  10405. if (var) {
  10406. var->flg_export = 1;
  10407. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10408. putenv(var->varstr);
  10409. continue;
  10410. }
  10411. }
  10412. if (flags & SETFLAG_MAKE_RO) {
  10413. /* readonly NAME (without =VALUE) */
  10414. if (var) {
  10415. var->flg_read_only = 1;
  10416. continue;
  10417. }
  10418. }
  10419. # if ENABLE_HUSH_LOCAL
  10420. /* Is this "local" bltin? */
  10421. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10422. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10423. if (var && var->var_nest_level == lvl) {
  10424. /* "local x=abc; ...; local x" - ignore second local decl */
  10425. continue;
  10426. }
  10427. }
  10428. # endif
  10429. /* Exporting non-existing variable.
  10430. * bash does not put it in environment,
  10431. * but remembers that it is exported,
  10432. * and does put it in env when it is set later.
  10433. * We just set it to "" and export.
  10434. */
  10435. /* Or, it's "local NAME" (without =VALUE).
  10436. * bash sets the value to "".
  10437. */
  10438. /* Or, it's "readonly NAME" (without =VALUE).
  10439. * bash remembers NAME and disallows its creation
  10440. * in the future.
  10441. */
  10442. name = xasprintf("%s=", name);
  10443. } else {
  10444. if (*name_end != '=') {
  10445. bb_error_msg("'%s': bad variable name", name);
  10446. /* do not parse following argv[]s: */
  10447. return 1;
  10448. }
  10449. /* (Un)exporting/making local NAME=VALUE */
  10450. name = xstrdup(name);
  10451. /* Testcase: export PS1='\w \$ ' */
  10452. unbackslash(name);
  10453. }
  10454. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10455. if (set_local_var(name, flags))
  10456. return EXIT_FAILURE;
  10457. } while (*++argv);
  10458. return EXIT_SUCCESS;
  10459. }
  10460. #endif
  10461. #if ENABLE_HUSH_EXPORT
  10462. static int FAST_FUNC builtin_export(char **argv)
  10463. {
  10464. unsigned opt_unexport;
  10465. # if ENABLE_HUSH_EXPORT_N
  10466. /* "!": do not abort on errors */
  10467. opt_unexport = getopt32(argv, "!n");
  10468. if (opt_unexport == (uint32_t)-1)
  10469. return EXIT_FAILURE;
  10470. argv += optind;
  10471. # else
  10472. opt_unexport = 0;
  10473. argv++;
  10474. # endif
  10475. if (argv[0] == NULL) {
  10476. char **e = environ;
  10477. if (e) {
  10478. while (*e) {
  10479. # if 0
  10480. puts(*e++);
  10481. # else
  10482. /* ash emits: export VAR='VAL'
  10483. * bash: declare -x VAR="VAL"
  10484. * we follow ash example */
  10485. const char *s = *e++;
  10486. const char *p = strchr(s, '=');
  10487. if (!p) /* wtf? take next variable */
  10488. continue;
  10489. /* export var= */
  10490. printf("export %.*s", (int)(p - s) + 1, s);
  10491. print_escaped(p + 1);
  10492. putchar('\n');
  10493. # endif
  10494. }
  10495. /*fflush_all(); - done after each builtin anyway */
  10496. }
  10497. return EXIT_SUCCESS;
  10498. }
  10499. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10500. }
  10501. #endif
  10502. #if ENABLE_HUSH_LOCAL
  10503. static int FAST_FUNC builtin_local(char **argv)
  10504. {
  10505. if (G.func_nest_level == 0) {
  10506. bb_error_msg("%s: not in a function", argv[0]);
  10507. return EXIT_FAILURE; /* bash compat */
  10508. }
  10509. argv++;
  10510. /* Since all builtins run in a nested variable level,
  10511. * need to use level - 1 here. Or else the variable will be removed at once
  10512. * after builtin returns.
  10513. */
  10514. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10515. }
  10516. #endif
  10517. #if ENABLE_HUSH_READONLY
  10518. static int FAST_FUNC builtin_readonly(char **argv)
  10519. {
  10520. argv++;
  10521. if (*argv == NULL) {
  10522. /* bash: readonly [-p]: list all readonly VARs
  10523. * (-p has no effect in bash)
  10524. */
  10525. struct variable *e;
  10526. for (e = G.top_var; e; e = e->next) {
  10527. if (e->flg_read_only) {
  10528. //TODO: quote value: readonly VAR='VAL'
  10529. printf("readonly %s\n", e->varstr);
  10530. }
  10531. }
  10532. return EXIT_SUCCESS;
  10533. }
  10534. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10535. }
  10536. #endif
  10537. #if ENABLE_HUSH_UNSET
  10538. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10539. static int FAST_FUNC builtin_unset(char **argv)
  10540. {
  10541. int ret;
  10542. unsigned opts;
  10543. /* "!": do not abort on errors */
  10544. /* "+": stop at 1st non-option */
  10545. opts = getopt32(argv, "!+vf");
  10546. if (opts == (unsigned)-1)
  10547. return EXIT_FAILURE;
  10548. if (opts == 3) {
  10549. bb_simple_error_msg("unset: -v and -f are exclusive");
  10550. return EXIT_FAILURE;
  10551. }
  10552. argv += optind;
  10553. ret = EXIT_SUCCESS;
  10554. while (*argv) {
  10555. if (!(opts & 2)) { /* not -f */
  10556. if (unset_local_var(*argv)) {
  10557. /* unset <nonexistent_var> doesn't fail.
  10558. * Error is when one tries to unset RO var.
  10559. * Message was printed by unset_local_var. */
  10560. ret = EXIT_FAILURE;
  10561. }
  10562. }
  10563. # if ENABLE_HUSH_FUNCTIONS
  10564. else {
  10565. unset_func(*argv);
  10566. }
  10567. # endif
  10568. argv++;
  10569. }
  10570. return ret;
  10571. }
  10572. #endif
  10573. #if ENABLE_HUSH_SET
  10574. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10575. * built-in 'set' handler
  10576. * SUSv3 says:
  10577. * set [-abCefhmnuvx] [-o option] [argument...]
  10578. * set [+abCefhmnuvx] [+o option] [argument...]
  10579. * set -- [argument...]
  10580. * set -o
  10581. * set +o
  10582. * Implementations shall support the options in both their hyphen and
  10583. * plus-sign forms. These options can also be specified as options to sh.
  10584. * Examples:
  10585. * Write out all variables and their values: set
  10586. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10587. * Turn on the -x and -v options: set -xv
  10588. * Unset all positional parameters: set --
  10589. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10590. * Set the positional parameters to the expansion of x, even if x expands
  10591. * with a leading '-' or '+': set -- $x
  10592. *
  10593. * So far, we only support "set -- [argument...]" and some of the short names.
  10594. */
  10595. static int FAST_FUNC builtin_set(char **argv)
  10596. {
  10597. int n;
  10598. char **pp, **g_argv;
  10599. char *arg = *++argv;
  10600. if (arg == NULL) {
  10601. struct variable *e;
  10602. for (e = G.top_var; e; e = e->next)
  10603. puts(e->varstr);
  10604. return EXIT_SUCCESS;
  10605. }
  10606. do {
  10607. if (strcmp(arg, "--") == 0) {
  10608. ++argv;
  10609. goto set_argv;
  10610. }
  10611. if (arg[0] != '+' && arg[0] != '-')
  10612. break;
  10613. for (n = 1; arg[n]; ++n) {
  10614. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10615. bb_error_msg("%s: %s: invalid option", "set", arg);
  10616. return EXIT_FAILURE;
  10617. }
  10618. if (arg[n] == 'o' && argv[1])
  10619. argv++;
  10620. }
  10621. } while ((arg = *++argv) != NULL);
  10622. /* Now argv[0] is 1st argument */
  10623. if (arg == NULL)
  10624. return EXIT_SUCCESS;
  10625. set_argv:
  10626. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10627. g_argv = G.global_argv;
  10628. if (G.global_args_malloced) {
  10629. pp = g_argv;
  10630. while (*++pp)
  10631. free(*pp);
  10632. g_argv[1] = NULL;
  10633. } else {
  10634. G.global_args_malloced = 1;
  10635. pp = xzalloc(sizeof(pp[0]) * 2);
  10636. pp[0] = g_argv[0]; /* retain $0 */
  10637. g_argv = pp;
  10638. }
  10639. /* This realloc's G.global_argv */
  10640. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10641. G.global_argc = 1 + string_array_len(pp + 1);
  10642. return EXIT_SUCCESS;
  10643. }
  10644. #endif
  10645. static int FAST_FUNC builtin_shift(char **argv)
  10646. {
  10647. int n = 1;
  10648. argv = skip_dash_dash(argv);
  10649. if (argv[0]) {
  10650. n = bb_strtou(argv[0], NULL, 10);
  10651. if (errno || n < 0) {
  10652. /* shared string with ash.c */
  10653. bb_error_msg("Illegal number: %s", argv[0]);
  10654. /*
  10655. * ash aborts in this case.
  10656. * bash prints error message and set $? to 1.
  10657. * Interestingly, for "shift 99999" bash does not
  10658. * print error message, but does set $? to 1
  10659. * (and does no shifting at all).
  10660. */
  10661. }
  10662. }
  10663. if (n >= 0 && n < G.global_argc) {
  10664. if (G_global_args_malloced) {
  10665. int m = 1;
  10666. while (m <= n)
  10667. free(G.global_argv[m++]);
  10668. }
  10669. G.global_argc -= n;
  10670. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10671. G.global_argc * sizeof(G.global_argv[0]));
  10672. return EXIT_SUCCESS;
  10673. }
  10674. return EXIT_FAILURE;
  10675. }
  10676. #if ENABLE_HUSH_GETOPTS
  10677. static int FAST_FUNC builtin_getopts(char **argv)
  10678. {
  10679. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10680. TODO:
  10681. If a required argument is not found, and getopts is not silent,
  10682. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10683. diagnostic message is printed. If getopts is silent, then a
  10684. colon (:) is placed in VAR and OPTARG is set to the option
  10685. character found.
  10686. Test that VAR is a valid variable name?
  10687. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10688. */
  10689. char cbuf[2];
  10690. const char *cp, *optstring, *var;
  10691. int c, n, exitcode, my_opterr;
  10692. unsigned count;
  10693. optstring = *++argv;
  10694. if (!optstring || !(var = *++argv)) {
  10695. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10696. return EXIT_FAILURE;
  10697. }
  10698. if (argv[1])
  10699. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10700. else
  10701. argv = G.global_argv;
  10702. cbuf[1] = '\0';
  10703. my_opterr = 0;
  10704. if (optstring[0] != ':') {
  10705. cp = get_local_var_value("OPTERR");
  10706. /* 0 if "OPTERR=0", 1 otherwise */
  10707. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10708. }
  10709. /* getopts stops on first non-option. Add "+" to force that */
  10710. /*if (optstring[0] != '+')*/ {
  10711. char *s = alloca(strlen(optstring) + 2);
  10712. sprintf(s, "+%s", optstring);
  10713. optstring = s;
  10714. }
  10715. /* Naively, now we should just
  10716. * cp = get_local_var_value("OPTIND");
  10717. * optind = cp ? atoi(cp) : 0;
  10718. * optarg = NULL;
  10719. * opterr = my_opterr;
  10720. * c = getopt(string_array_len(argv), argv, optstring);
  10721. * and be done? Not so fast...
  10722. * Unlike normal getopt() usage in C programs, here
  10723. * each successive call will (usually) have the same argv[] CONTENTS,
  10724. * but not the ADDRESSES. Worse yet, it's possible that between
  10725. * invocations of "getopts", there will be calls to shell builtins
  10726. * which use getopt() internally. Example:
  10727. * while getopts "abc" RES -a -bc -abc de; do
  10728. * unset -ff func
  10729. * done
  10730. * This would not work correctly: getopt() call inside "unset"
  10731. * modifies internal libc state which is tracking position in
  10732. * multi-option strings ("-abc"). At best, it can skip options
  10733. * or return the same option infinitely. With glibc implementation
  10734. * of getopt(), it would use outright invalid pointers and return
  10735. * garbage even _without_ "unset" mangling internal state.
  10736. *
  10737. * We resort to resetting getopt() state and calling it N times,
  10738. * until we get Nth result (or failure).
  10739. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10740. */
  10741. GETOPT_RESET();
  10742. count = 0;
  10743. n = string_array_len(argv);
  10744. do {
  10745. optarg = NULL;
  10746. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10747. c = getopt(n, argv, optstring);
  10748. if (c < 0)
  10749. break;
  10750. count++;
  10751. } while (count <= G.getopt_count);
  10752. /* Set OPTIND. Prevent resetting of the magic counter! */
  10753. set_local_var_from_halves("OPTIND", utoa(optind));
  10754. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10755. GETOPT_RESET(); /* just in case */
  10756. /* Set OPTARG */
  10757. /* Always set or unset, never left as-is, even on exit/error:
  10758. * "If no option was found, or if the option that was found
  10759. * does not have an option-argument, OPTARG shall be unset."
  10760. */
  10761. cp = optarg;
  10762. if (c == '?') {
  10763. /* If ":optstring" and unknown option is seen,
  10764. * it is stored to OPTARG.
  10765. */
  10766. if (optstring[1] == ':') {
  10767. cbuf[0] = optopt;
  10768. cp = cbuf;
  10769. }
  10770. }
  10771. if (cp)
  10772. set_local_var_from_halves("OPTARG", cp);
  10773. else
  10774. unset_local_var("OPTARG");
  10775. /* Convert -1 to "?" */
  10776. exitcode = EXIT_SUCCESS;
  10777. if (c < 0) { /* -1: end of options */
  10778. exitcode = EXIT_FAILURE;
  10779. c = '?';
  10780. }
  10781. /* Set VAR */
  10782. cbuf[0] = c;
  10783. set_local_var_from_halves(var, cbuf);
  10784. return exitcode;
  10785. }
  10786. #endif
  10787. static int FAST_FUNC builtin_source(char **argv)
  10788. {
  10789. char *arg_path, *filename;
  10790. HFILE *input;
  10791. save_arg_t sv;
  10792. char *args_need_save;
  10793. #if ENABLE_HUSH_FUNCTIONS
  10794. smallint sv_flg;
  10795. #endif
  10796. argv = skip_dash_dash(argv);
  10797. filename = argv[0];
  10798. if (!filename) {
  10799. /* bash says: "bash: .: filename argument required" */
  10800. return 2; /* bash compat */
  10801. }
  10802. arg_path = NULL;
  10803. if (!strchr(filename, '/')) {
  10804. arg_path = find_in_path(filename);
  10805. if (arg_path)
  10806. filename = arg_path;
  10807. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10808. errno = ENOENT;
  10809. bb_simple_perror_msg(filename);
  10810. return EXIT_FAILURE;
  10811. }
  10812. }
  10813. input = hfopen(filename);
  10814. free(arg_path);
  10815. if (!input) {
  10816. bb_perror_msg("%s", filename);
  10817. /* POSIX: non-interactive shell should abort here,
  10818. * not merely fail. So far no one complained :)
  10819. */
  10820. return EXIT_FAILURE;
  10821. }
  10822. #if ENABLE_HUSH_FUNCTIONS
  10823. sv_flg = G_flag_return_in_progress;
  10824. /* "we are inside sourced file, ok to use return" */
  10825. G_flag_return_in_progress = -1;
  10826. #endif
  10827. args_need_save = argv[1]; /* used as a boolean variable */
  10828. if (args_need_save)
  10829. save_and_replace_G_args(&sv, argv);
  10830. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10831. G.last_exitcode = 0;
  10832. parse_and_run_file(input);
  10833. hfclose(input);
  10834. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10835. restore_G_args(&sv, argv);
  10836. #if ENABLE_HUSH_FUNCTIONS
  10837. G_flag_return_in_progress = sv_flg;
  10838. #endif
  10839. return G.last_exitcode;
  10840. }
  10841. #if ENABLE_HUSH_TRAP
  10842. static int FAST_FUNC builtin_trap(char **argv)
  10843. {
  10844. int sig;
  10845. char *new_cmd;
  10846. if (!G_traps)
  10847. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10848. argv++;
  10849. if (!*argv) {
  10850. int i;
  10851. /* No args: print all trapped */
  10852. for (i = 0; i < NSIG; ++i) {
  10853. if (G_traps[i]) {
  10854. printf("trap -- ");
  10855. print_escaped(G_traps[i]);
  10856. /* note: bash adds "SIG", but only if invoked
  10857. * as "bash". If called as "sh", or if set -o posix,
  10858. * then it prints short signal names.
  10859. * We are printing short names: */
  10860. printf(" %s\n", get_signame(i));
  10861. }
  10862. }
  10863. /*fflush_all(); - done after each builtin anyway */
  10864. return EXIT_SUCCESS;
  10865. }
  10866. new_cmd = NULL;
  10867. /* If first arg is a number: reset all specified signals */
  10868. sig = bb_strtou(*argv, NULL, 10);
  10869. if (errno == 0) {
  10870. int ret;
  10871. process_sig_list:
  10872. ret = EXIT_SUCCESS;
  10873. while (*argv) {
  10874. sighandler_t handler;
  10875. sig = get_signum(*argv++);
  10876. if (sig < 0) {
  10877. ret = EXIT_FAILURE;
  10878. /* Mimic bash message exactly */
  10879. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10880. continue;
  10881. }
  10882. free(G_traps[sig]);
  10883. G_traps[sig] = xstrdup(new_cmd);
  10884. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10885. get_signame(sig), sig, G_traps[sig]);
  10886. /* There is no signal for 0 (EXIT) */
  10887. if (sig == 0)
  10888. continue;
  10889. if (new_cmd)
  10890. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10891. else
  10892. /* We are removing trap handler */
  10893. handler = pick_sighandler(sig);
  10894. install_sighandler(sig, handler);
  10895. }
  10896. return ret;
  10897. }
  10898. if (!argv[1]) { /* no second arg */
  10899. bb_simple_error_msg("trap: invalid arguments");
  10900. return EXIT_FAILURE;
  10901. }
  10902. /* First arg is "-": reset all specified to default */
  10903. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10904. /* Everything else: set arg as signal handler
  10905. * (includes "" case, which ignores signal) */
  10906. if (argv[0][0] == '-') {
  10907. if (argv[0][1] == '\0') { /* "-" */
  10908. /* new_cmd remains NULL: "reset these sigs" */
  10909. goto reset_traps;
  10910. }
  10911. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10912. argv++;
  10913. }
  10914. /* else: "-something", no special meaning */
  10915. }
  10916. new_cmd = *argv;
  10917. reset_traps:
  10918. argv++;
  10919. goto process_sig_list;
  10920. }
  10921. #endif
  10922. #if ENABLE_HUSH_JOB
  10923. static struct pipe *parse_jobspec(const char *str)
  10924. {
  10925. struct pipe *pi;
  10926. unsigned jobnum;
  10927. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10928. if (str[0] != '%'
  10929. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10930. ) {
  10931. bb_error_msg("bad argument '%s'", str);
  10932. return NULL;
  10933. }
  10934. /* It is "%%", "%+" or "%" - current job */
  10935. jobnum = G.last_jobid;
  10936. if (jobnum == 0) {
  10937. bb_simple_error_msg("no current job");
  10938. return NULL;
  10939. }
  10940. }
  10941. for (pi = G.job_list; pi; pi = pi->next) {
  10942. if (pi->jobid == jobnum) {
  10943. return pi;
  10944. }
  10945. }
  10946. bb_error_msg("%u: no such job", jobnum);
  10947. return NULL;
  10948. }
  10949. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10950. {
  10951. struct pipe *job;
  10952. const char *status_string;
  10953. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10954. for (job = G.job_list; job; job = job->next) {
  10955. if (job->alive_cmds == job->stopped_cmds)
  10956. status_string = "Stopped";
  10957. else
  10958. status_string = "Running";
  10959. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10960. }
  10961. clean_up_last_dead_job();
  10962. return EXIT_SUCCESS;
  10963. }
  10964. /* built-in 'fg' and 'bg' handler */
  10965. static int FAST_FUNC builtin_fg_bg(char **argv)
  10966. {
  10967. int i;
  10968. struct pipe *pi;
  10969. if (!G_interactive_fd)
  10970. return EXIT_FAILURE;
  10971. /* If they gave us no args, assume they want the last backgrounded task */
  10972. if (!argv[1]) {
  10973. for (pi = G.job_list; pi; pi = pi->next) {
  10974. if (pi->jobid == G.last_jobid) {
  10975. goto found;
  10976. }
  10977. }
  10978. bb_error_msg("%s: no current job", argv[0]);
  10979. return EXIT_FAILURE;
  10980. }
  10981. pi = parse_jobspec(argv[1]);
  10982. if (!pi)
  10983. return EXIT_FAILURE;
  10984. found:
  10985. /* TODO: bash prints a string representation
  10986. * of job being foregrounded (like "sleep 1 | cat") */
  10987. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10988. /* Put the job into the foreground. */
  10989. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10990. }
  10991. /* Restart the processes in the job */
  10992. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10993. for (i = 0; i < pi->num_cmds; i++) {
  10994. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10995. }
  10996. pi->stopped_cmds = 0;
  10997. i = kill(- pi->pgrp, SIGCONT);
  10998. if (i < 0) {
  10999. if (errno == ESRCH) {
  11000. delete_finished_job(pi);
  11001. return EXIT_SUCCESS;
  11002. }
  11003. bb_simple_perror_msg("kill (SIGCONT)");
  11004. }
  11005. if (argv[0][0] == 'f') {
  11006. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  11007. return checkjobs_and_fg_shell(pi);
  11008. }
  11009. return EXIT_SUCCESS;
  11010. }
  11011. #endif
  11012. #if ENABLE_HUSH_KILL
  11013. static int FAST_FUNC builtin_kill(char **argv)
  11014. {
  11015. int ret = 0;
  11016. # if ENABLE_HUSH_JOB
  11017. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  11018. int i = 1;
  11019. do {
  11020. struct pipe *pi;
  11021. char *dst;
  11022. int j, n;
  11023. if (argv[i][0] != '%')
  11024. continue;
  11025. /*
  11026. * "kill %N" - job kill
  11027. * Converting to pgrp / pid kill
  11028. */
  11029. pi = parse_jobspec(argv[i]);
  11030. if (!pi) {
  11031. /* Eat bad jobspec */
  11032. j = i;
  11033. do {
  11034. j++;
  11035. argv[j - 1] = argv[j];
  11036. } while (argv[j]);
  11037. ret = 1;
  11038. i--;
  11039. continue;
  11040. }
  11041. /*
  11042. * In jobs started under job control, we signal
  11043. * entire process group by kill -PGRP_ID.
  11044. * This happens, f.e., in interactive shell.
  11045. *
  11046. * Otherwise, we signal each child via
  11047. * kill PID1 PID2 PID3.
  11048. * Testcases:
  11049. * sh -c 'sleep 1|sleep 1 & kill %1'
  11050. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  11051. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  11052. */
  11053. n = G_interactive_fd ? 1 : pi->num_cmds;
  11054. dst = alloca(n * sizeof(int)*4);
  11055. argv[i] = dst;
  11056. if (G_interactive_fd)
  11057. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  11058. else for (j = 0; j < n; j++) {
  11059. struct command *cmd = &pi->cmds[j];
  11060. /* Skip exited members of the job */
  11061. if (cmd->pid == 0)
  11062. continue;
  11063. /*
  11064. * kill_main has matching code to expect
  11065. * leading space. Needed to not confuse
  11066. * negative pids with "kill -SIGNAL_NO" syntax
  11067. */
  11068. dst += sprintf(dst, " %u", (int)cmd->pid);
  11069. }
  11070. *dst = '\0';
  11071. } while (argv[++i]);
  11072. }
  11073. # endif
  11074. if (argv[1] || ret == 0) {
  11075. ret = run_applet_main(argv, kill_main);
  11076. }
  11077. /* else: ret = 1, "kill %bad_jobspec" case */
  11078. return ret;
  11079. }
  11080. #endif
  11081. #if ENABLE_HUSH_WAIT
  11082. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11083. # if !ENABLE_HUSH_JOB
  11084. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11085. # endif
  11086. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11087. {
  11088. int ret = 0;
  11089. for (;;) {
  11090. int sig;
  11091. sigset_t oldset;
  11092. if (!sigisemptyset(&G.pending_set))
  11093. goto check_sig;
  11094. /* waitpid is not interruptible by SA_RESTARTed
  11095. * signals which we use. Thus, this ugly dance:
  11096. */
  11097. /* Make sure possible SIGCHLD is stored in kernel's
  11098. * pending signal mask before we call waitpid.
  11099. * Or else we may race with SIGCHLD, lose it,
  11100. * and get stuck in sigsuspend...
  11101. */
  11102. sigfillset(&oldset); /* block all signals, remember old set */
  11103. sigprocmask2(SIG_SETMASK, &oldset);
  11104. if (!sigisemptyset(&G.pending_set)) {
  11105. /* Crap! we raced with some signal! */
  11106. goto restore;
  11107. }
  11108. /*errno = 0; - checkjobs does this */
  11109. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11110. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11111. debug_printf_exec("checkjobs:%d\n", ret);
  11112. # if ENABLE_HUSH_JOB
  11113. if (waitfor_pipe) {
  11114. int rcode = job_exited_or_stopped(waitfor_pipe);
  11115. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11116. if (rcode >= 0) {
  11117. ret = rcode;
  11118. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11119. break;
  11120. }
  11121. }
  11122. # endif
  11123. /* if ECHILD, there are no children (ret is -1 or 0) */
  11124. /* if ret == 0, no children changed state */
  11125. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11126. if (errno == ECHILD || ret) {
  11127. ret--;
  11128. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11129. ret = 0;
  11130. # if ENABLE_HUSH_BASH_COMPAT
  11131. if (waitfor_pid == -1 && errno == ECHILD) {
  11132. /* exitcode of "wait -n" with no children is 127, not 0 */
  11133. ret = 127;
  11134. }
  11135. # endif
  11136. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11137. break;
  11138. }
  11139. /* Wait for SIGCHLD or any other signal */
  11140. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11141. /* Note: sigsuspend invokes signal handler */
  11142. sigsuspend(&oldset);
  11143. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11144. * to make sure SIGCHLD is not masked off?
  11145. * It was reported that this:
  11146. * fn() { : | return; }
  11147. * shopt -s lastpipe
  11148. * fn
  11149. * exec hush SCRIPT
  11150. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11151. * making "wait" commands in SCRIPT block forever.
  11152. */
  11153. restore:
  11154. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11155. check_sig:
  11156. /* So, did we get a signal? */
  11157. sig = check_and_run_traps();
  11158. if (sig /*&& sig != SIGCHLD - always true */) {
  11159. /* Do this for any (non-ignored) signal, not only for ^C */
  11160. ret = 128 | sig;
  11161. break;
  11162. }
  11163. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11164. }
  11165. return ret;
  11166. }
  11167. static int FAST_FUNC builtin_wait(char **argv)
  11168. {
  11169. int ret;
  11170. int status;
  11171. argv = skip_dash_dash(argv);
  11172. # if ENABLE_HUSH_BASH_COMPAT
  11173. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11174. /* wait -n */
  11175. /* (bash accepts "wait -n PID" too and ignores PID) */
  11176. G.dead_job_exitcode = -1;
  11177. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11178. }
  11179. # endif
  11180. if (argv[0] == NULL) {
  11181. /* Don't care about wait results */
  11182. /* Note 1: must wait until there are no more children */
  11183. /* Note 2: must be interruptible */
  11184. /* Examples:
  11185. * $ sleep 3 & sleep 6 & wait
  11186. * [1] 30934 sleep 3
  11187. * [2] 30935 sleep 6
  11188. * [1] Done sleep 3
  11189. * [2] Done sleep 6
  11190. * $ sleep 3 & sleep 6 & wait
  11191. * [1] 30936 sleep 3
  11192. * [2] 30937 sleep 6
  11193. * [1] Done sleep 3
  11194. * ^C <-- after ~4 sec from keyboard
  11195. * $
  11196. */
  11197. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11198. }
  11199. do {
  11200. pid_t pid = bb_strtou(*argv, NULL, 10);
  11201. if (errno || pid <= 0) {
  11202. # if ENABLE_HUSH_JOB
  11203. if (argv[0][0] == '%') {
  11204. struct pipe *wait_pipe;
  11205. ret = 127; /* bash compat for bad jobspecs */
  11206. wait_pipe = parse_jobspec(*argv);
  11207. if (wait_pipe) {
  11208. ret = job_exited_or_stopped(wait_pipe);
  11209. if (ret < 0) {
  11210. ret = wait_for_child_or_signal(wait_pipe, 0);
  11211. } else {
  11212. /* waiting on "last dead job" removes it */
  11213. clean_up_last_dead_job();
  11214. }
  11215. }
  11216. /* else: parse_jobspec() already emitted error msg */
  11217. continue;
  11218. }
  11219. # endif
  11220. /* mimic bash message */
  11221. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11222. ret = EXIT_FAILURE;
  11223. continue; /* bash checks all argv[] */
  11224. }
  11225. /* Do we have such child? */
  11226. ret = waitpid(pid, &status, WNOHANG);
  11227. if (ret < 0) {
  11228. /* No */
  11229. ret = 127;
  11230. if (errno == ECHILD) {
  11231. if (pid == G.last_bg_pid) {
  11232. /* "wait $!" but last bg task has already exited. Try:
  11233. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11234. * In bash it prints exitcode 0, then 3.
  11235. * In dash, it is 127.
  11236. */
  11237. ret = G.last_bg_pid_exitcode;
  11238. } else {
  11239. /* Example: "wait 1". mimic bash message */
  11240. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11241. }
  11242. } else {
  11243. /* ??? */
  11244. bb_perror_msg("wait %s", *argv);
  11245. }
  11246. continue; /* bash checks all argv[] */
  11247. }
  11248. if (ret == 0) {
  11249. /* Yes, and it still runs */
  11250. ret = wait_for_child_or_signal(NULL, pid);
  11251. } else {
  11252. /* Yes, and it just exited */
  11253. process_wait_result(NULL, pid, status);
  11254. ret = WEXITSTATUS(status);
  11255. if (WIFSIGNALED(status))
  11256. ret = 128 | WTERMSIG(status);
  11257. }
  11258. } while (*++argv);
  11259. return ret;
  11260. }
  11261. #endif
  11262. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11263. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11264. {
  11265. if (argv[1]) {
  11266. def = bb_strtou(argv[1], NULL, 10);
  11267. if (errno || def < def_min || argv[2]) {
  11268. bb_error_msg("%s: bad arguments", argv[0]);
  11269. def = UINT_MAX;
  11270. }
  11271. }
  11272. return def;
  11273. }
  11274. #endif
  11275. #if ENABLE_HUSH_LOOPS
  11276. static int FAST_FUNC builtin_break(char **argv)
  11277. {
  11278. unsigned depth;
  11279. if (G.depth_of_loop == 0) {
  11280. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11281. /* if we came from builtin_continue(), need to undo "= 1" */
  11282. G.flag_break_continue = 0;
  11283. return EXIT_SUCCESS; /* bash compat */
  11284. }
  11285. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11286. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11287. if (depth == UINT_MAX)
  11288. G.flag_break_continue = BC_BREAK;
  11289. if (G.depth_of_loop < depth)
  11290. G.depth_break_continue = G.depth_of_loop;
  11291. return EXIT_SUCCESS;
  11292. }
  11293. static int FAST_FUNC builtin_continue(char **argv)
  11294. {
  11295. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11296. return builtin_break(argv);
  11297. }
  11298. #endif
  11299. #if ENABLE_HUSH_FUNCTIONS
  11300. static int FAST_FUNC builtin_return(char **argv)
  11301. {
  11302. int rc;
  11303. if (G_flag_return_in_progress != -1) {
  11304. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11305. return EXIT_FAILURE; /* bash compat */
  11306. }
  11307. G_flag_return_in_progress = 1;
  11308. /* bash:
  11309. * out of range: wraps around at 256, does not error out
  11310. * non-numeric param:
  11311. * f() { false; return qwe; }; f; echo $?
  11312. * bash: return: qwe: numeric argument required <== we do this
  11313. * 255 <== we also do this
  11314. */
  11315. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11316. # if ENABLE_HUSH_TRAP
  11317. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11318. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11319. G.return_exitcode = rc;
  11320. }
  11321. # endif
  11322. return rc;
  11323. }
  11324. #endif
  11325. #if ENABLE_HUSH_TIMES
  11326. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11327. {
  11328. static const uint8_t times_tbl[] ALIGN1 = {
  11329. ' ', offsetof(struct tms, tms_utime),
  11330. '\n', offsetof(struct tms, tms_stime),
  11331. ' ', offsetof(struct tms, tms_cutime),
  11332. '\n', offsetof(struct tms, tms_cstime),
  11333. 0
  11334. };
  11335. const uint8_t *p;
  11336. unsigned clk_tck;
  11337. struct tms buf;
  11338. clk_tck = bb_clk_tck();
  11339. times(&buf);
  11340. p = times_tbl;
  11341. do {
  11342. unsigned sec, frac;
  11343. unsigned long t;
  11344. t = *(clock_t *)(((char *) &buf) + p[1]);
  11345. sec = t / clk_tck;
  11346. frac = t % clk_tck;
  11347. printf("%um%u.%03us%c",
  11348. sec / 60, sec % 60,
  11349. (frac * 1000) / clk_tck,
  11350. p[0]);
  11351. p += 2;
  11352. } while (*p);
  11353. return EXIT_SUCCESS;
  11354. }
  11355. #endif
  11356. #if ENABLE_HUSH_MEMLEAK
  11357. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11358. {
  11359. void *p;
  11360. unsigned long l;
  11361. # ifdef M_TRIM_THRESHOLD
  11362. /* Optional. Reduces probability of false positives */
  11363. malloc_trim(0);
  11364. # endif
  11365. /* Crude attempt to find where "free memory" starts,
  11366. * sans fragmentation. */
  11367. p = malloc(240);
  11368. l = (unsigned long)p;
  11369. free(p);
  11370. p = malloc(3400);
  11371. if (l < (unsigned long)p) l = (unsigned long)p;
  11372. free(p);
  11373. # if 0 /* debug */
  11374. {
  11375. struct mallinfo mi = mallinfo();
  11376. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11377. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11378. }
  11379. # endif
  11380. if (!G.memleak_value)
  11381. G.memleak_value = l;
  11382. l -= G.memleak_value;
  11383. if ((long)l < 0)
  11384. l = 0;
  11385. l /= 1024;
  11386. if (l > 127)
  11387. l = 127;
  11388. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11389. return l;
  11390. }
  11391. #endif