hush.c 324 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (68 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support command substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef O_CLOEXEC
  356. # define O_CLOEXEC 0
  357. #endif
  358. #ifndef F_DUPFD_CLOEXEC
  359. # define F_DUPFD_CLOEXEC F_DUPFD
  360. #endif
  361. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  362. # include "embedded_scripts.h"
  363. #else
  364. # define NUM_SCRIPTS 0
  365. #endif
  366. /* So far, all bash compat is controlled by one config option */
  367. /* Separate defines document which part of code implements what */
  368. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  369. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  370. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  371. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  372. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  373. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  374. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  375. /* Build knobs */
  376. #define LEAK_HUNTING 0
  377. #define BUILD_AS_NOMMU 0
  378. /* Enable/disable sanity checks. Ok to enable in production,
  379. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  380. * Keeping 1 for now even in released versions.
  381. */
  382. #define HUSH_DEBUG 1
  383. /* Slightly bigger (+200 bytes), but faster hush.
  384. * So far it only enables a trick with counting SIGCHLDs and forks,
  385. * which allows us to do fewer waitpid's.
  386. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  387. * and therefore waitpid will return the same result as last time)
  388. */
  389. #define ENABLE_HUSH_FAST 0
  390. /* TODO: implement simplified code for users which do not need ${var%...} ops
  391. * So far ${var%...} ops are always enabled:
  392. */
  393. #define ENABLE_HUSH_DOLLAR_OPS 1
  394. #if BUILD_AS_NOMMU
  395. # undef BB_MMU
  396. # undef USE_FOR_NOMMU
  397. # undef USE_FOR_MMU
  398. # define BB_MMU 0
  399. # define USE_FOR_NOMMU(...) __VA_ARGS__
  400. # define USE_FOR_MMU(...)
  401. #endif
  402. #include "NUM_APPLETS.h"
  403. #if NUM_APPLETS == 1
  404. /* STANDALONE does not make sense, and won't compile */
  405. # undef CONFIG_FEATURE_SH_STANDALONE
  406. # undef ENABLE_FEATURE_SH_STANDALONE
  407. # undef IF_FEATURE_SH_STANDALONE
  408. # undef IF_NOT_FEATURE_SH_STANDALONE
  409. # define ENABLE_FEATURE_SH_STANDALONE 0
  410. # define IF_FEATURE_SH_STANDALONE(...)
  411. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  412. #endif
  413. #if !ENABLE_HUSH_INTERACTIVE
  414. # undef ENABLE_FEATURE_EDITING
  415. # define ENABLE_FEATURE_EDITING 0
  416. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  417. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  418. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  419. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  420. #endif
  421. /* Do we support ANY keywords? */
  422. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  423. # define HAS_KEYWORDS 1
  424. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  425. # define IF_HAS_NO_KEYWORDS(...)
  426. #else
  427. # define HAS_KEYWORDS 0
  428. # define IF_HAS_KEYWORDS(...)
  429. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  430. #endif
  431. /* If you comment out one of these below, it will be #defined later
  432. * to perform debug printfs to stderr: */
  433. #define debug_printf(...) do {} while (0)
  434. /* Finer-grained debug switches */
  435. #define debug_printf_parse(...) do {} while (0)
  436. #define debug_printf_heredoc(...) do {} while (0)
  437. #define debug_print_tree(a, b) do {} while (0)
  438. #define debug_printf_exec(...) do {} while (0)
  439. #define debug_printf_env(...) do {} while (0)
  440. #define debug_printf_jobs(...) do {} while (0)
  441. #define debug_printf_expand(...) do {} while (0)
  442. #define debug_printf_varexp(...) do {} while (0)
  443. #define debug_printf_glob(...) do {} while (0)
  444. #define debug_printf_redir(...) do {} while (0)
  445. #define debug_printf_list(...) do {} while (0)
  446. #define debug_printf_subst(...) do {} while (0)
  447. #define debug_printf_prompt(...) do {} while (0)
  448. #define debug_printf_clean(...) do {} while (0)
  449. #define ERR_PTR ((void*)(long)1)
  450. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  451. #define _SPECIAL_VARS_STR "_*@$!?#-"
  452. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  453. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  454. #if BASH_PATTERN_SUBST
  455. /* Support / and // replace ops */
  456. /* Note that // is stored as \ in "encoded" string representation */
  457. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  458. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  459. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  460. #else
  461. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  462. # define VAR_SUBST_OPS "%#:-=+?"
  463. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  464. #endif
  465. #define SPECIAL_VAR_SYMBOL_STR "\3"
  466. #define SPECIAL_VAR_SYMBOL 3
  467. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  468. #define SPECIAL_VAR_QUOTED_SVS 1
  469. struct variable;
  470. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  471. /* This supports saving pointers malloced in vfork child,
  472. * to be freed in the parent.
  473. */
  474. #if !BB_MMU
  475. typedef struct nommu_save_t {
  476. struct variable *old_vars;
  477. char **argv;
  478. char **argv_from_re_execing;
  479. } nommu_save_t;
  480. #endif
  481. enum {
  482. RES_NONE = 0,
  483. #if ENABLE_HUSH_IF
  484. RES_IF ,
  485. RES_THEN ,
  486. RES_ELIF ,
  487. RES_ELSE ,
  488. RES_FI ,
  489. #endif
  490. #if ENABLE_HUSH_LOOPS
  491. RES_FOR ,
  492. RES_WHILE ,
  493. RES_UNTIL ,
  494. RES_DO ,
  495. RES_DONE ,
  496. #endif
  497. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  498. RES_IN ,
  499. #endif
  500. #if ENABLE_HUSH_CASE
  501. RES_CASE ,
  502. /* three pseudo-keywords support contrived "case" syntax: */
  503. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  504. RES_MATCH , /* "word)" */
  505. RES_CASE_BODY, /* "this command is inside CASE" */
  506. RES_ESAC ,
  507. #endif
  508. RES_XXXX ,
  509. RES_SNTX
  510. };
  511. typedef struct o_string {
  512. char *data;
  513. int length; /* position where data is appended */
  514. int maxlen;
  515. int o_expflags;
  516. /* At least some part of the string was inside '' or "",
  517. * possibly empty one: word"", wo''rd etc. */
  518. smallint has_quoted_part;
  519. smallint has_empty_slot;
  520. smallint ended_in_ifs;
  521. } o_string;
  522. enum {
  523. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  524. EXP_FLAG_GLOB = 0x2,
  525. /* Protect newly added chars against globbing
  526. * by prepending \ to *, ?, [, \ */
  527. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  528. };
  529. /* Used for initialization: o_string foo = NULL_O_STRING; */
  530. #define NULL_O_STRING { NULL }
  531. #ifndef debug_printf_parse
  532. static const char *const assignment_flag[] = {
  533. "MAYBE_ASSIGNMENT",
  534. "DEFINITELY_ASSIGNMENT",
  535. "NOT_ASSIGNMENT",
  536. "WORD_IS_KEYWORD",
  537. };
  538. #endif
  539. /* We almost can use standard FILE api, but we need an ability to move
  540. * its fd when redirects coincide with it. No api exists for that
  541. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  542. * HFILE is our internal alternative. Only supports reading.
  543. * Since we now can, we incorporate linked list of all opened HFILEs
  544. * into the struct (used to be a separate mini-list).
  545. */
  546. typedef struct HFILE {
  547. char *cur;
  548. char *end;
  549. struct HFILE *next_hfile;
  550. int fd;
  551. char buf[1024];
  552. } HFILE;
  553. typedef struct in_str {
  554. const char *p;
  555. int peek_buf[2];
  556. int last_char;
  557. HFILE *file;
  558. } in_str;
  559. /* The descrip member of this structure is only used to make
  560. * debugging output pretty */
  561. static const struct {
  562. int mode;
  563. signed char default_fd;
  564. char descrip[3];
  565. } redir_table[] = {
  566. { O_RDONLY, 0, "<" },
  567. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  568. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  569. { O_CREAT|O_RDWR, 1, "<>" },
  570. { O_RDONLY, 0, "<<" },
  571. /* Should not be needed. Bogus default_fd helps in debugging */
  572. /* { O_RDONLY, 77, "<<" }, */
  573. };
  574. struct redir_struct {
  575. struct redir_struct *next;
  576. char *rd_filename; /* filename */
  577. int rd_fd; /* fd to redirect */
  578. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  579. int rd_dup;
  580. smallint rd_type; /* (enum redir_type) */
  581. /* note: for heredocs, rd_filename contains heredoc delimiter,
  582. * and subsequently heredoc itself; and rd_dup is a bitmask:
  583. * bit 0: do we need to trim leading tabs?
  584. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  585. */
  586. };
  587. typedef enum redir_type {
  588. REDIRECT_INPUT = 0,
  589. REDIRECT_OVERWRITE = 1,
  590. REDIRECT_APPEND = 2,
  591. REDIRECT_IO = 3,
  592. REDIRECT_HEREDOC = 4,
  593. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  594. REDIRFD_CLOSE = -3,
  595. REDIRFD_SYNTAX_ERR = -2,
  596. REDIRFD_TO_FILE = -1,
  597. /* otherwise, rd_fd is redirected to rd_dup */
  598. HEREDOC_SKIPTABS = 1,
  599. HEREDOC_QUOTED = 2,
  600. } redir_type;
  601. struct command {
  602. pid_t pid; /* 0 if exited */
  603. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  604. #if ENABLE_HUSH_LINENO_VAR
  605. unsigned lineno;
  606. #endif
  607. smallint cmd_type; /* CMD_xxx */
  608. #define CMD_NORMAL 0
  609. #define CMD_SUBSHELL 1
  610. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  611. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  612. * "export v=t*"
  613. */
  614. # define CMD_SINGLEWORD_NOGLOB 2
  615. #endif
  616. #if ENABLE_HUSH_FUNCTIONS
  617. # define CMD_FUNCDEF 3
  618. #endif
  619. smalluint cmd_exitcode;
  620. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  621. struct pipe *group;
  622. #if !BB_MMU
  623. char *group_as_string;
  624. #endif
  625. #if ENABLE_HUSH_FUNCTIONS
  626. struct function *child_func;
  627. /* This field is used to prevent a bug here:
  628. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  629. * When we execute "f1() {a;}" cmd, we create new function and clear
  630. * cmd->group, cmd->group_as_string, cmd->argv[0].
  631. * When we execute "f1() {b;}", we notice that f1 exists,
  632. * and that its "parent cmd" struct is still "alive",
  633. * we put those fields back into cmd->xxx
  634. * (struct function has ->parent_cmd ptr to facilitate that).
  635. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  636. * Without this trick, loop would execute a;b;b;b;...
  637. * instead of correct sequence a;b;a;b;...
  638. * When command is freed, it severs the link
  639. * (sets ->child_func->parent_cmd to NULL).
  640. */
  641. #endif
  642. char **argv; /* command name and arguments */
  643. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  644. * and on execution these are substituted with their values.
  645. * Substitution can make _several_ words out of one argv[n]!
  646. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  647. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  648. */
  649. struct redir_struct *redirects; /* I/O redirections */
  650. };
  651. /* Is there anything in this command at all? */
  652. #define IS_NULL_CMD(cmd) \
  653. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  654. struct pipe {
  655. struct pipe *next;
  656. int num_cmds; /* total number of commands in pipe */
  657. int alive_cmds; /* number of commands running (not exited) */
  658. int stopped_cmds; /* number of commands alive, but stopped */
  659. #if ENABLE_HUSH_JOB
  660. unsigned jobid; /* job number */
  661. pid_t pgrp; /* process group ID for the job */
  662. char *cmdtext; /* name of job */
  663. #endif
  664. struct command *cmds; /* array of commands in pipe */
  665. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  666. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  667. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  668. };
  669. typedef enum pipe_style {
  670. PIPE_SEQ = 0,
  671. PIPE_AND = 1,
  672. PIPE_OR = 2,
  673. PIPE_BG = 3,
  674. } pipe_style;
  675. /* Is there anything in this pipe at all? */
  676. #define IS_NULL_PIPE(pi) \
  677. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  678. /* This holds pointers to the various results of parsing */
  679. struct parse_context {
  680. /* linked list of pipes */
  681. struct pipe *list_head;
  682. /* last pipe (being constructed right now) */
  683. struct pipe *pipe;
  684. /* last command in pipe (being constructed right now) */
  685. struct command *command;
  686. /* last redirect in command->redirects list */
  687. struct redir_struct *pending_redirect;
  688. o_string word;
  689. #if !BB_MMU
  690. o_string as_string;
  691. #endif
  692. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  693. #if HAS_KEYWORDS
  694. smallint ctx_res_w;
  695. smallint ctx_inverted; /* "! cmd | cmd" */
  696. #if ENABLE_HUSH_CASE
  697. smallint ctx_dsemicolon; /* ";;" seen */
  698. #endif
  699. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  700. int old_flag;
  701. /* group we are enclosed in:
  702. * example: "if pipe1; pipe2; then pipe3; fi"
  703. * when we see "if" or "then", we malloc and copy current context,
  704. * and make ->stack point to it. then we parse pipeN.
  705. * when closing "then" / fi" / whatever is found,
  706. * we move list_head into ->stack->command->group,
  707. * copy ->stack into current context, and delete ->stack.
  708. * (parsing of { list } and ( list ) doesn't use this method)
  709. */
  710. struct parse_context *stack;
  711. #endif
  712. };
  713. enum {
  714. MAYBE_ASSIGNMENT = 0,
  715. DEFINITELY_ASSIGNMENT = 1,
  716. NOT_ASSIGNMENT = 2,
  717. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  718. WORD_IS_KEYWORD = 3,
  719. };
  720. /* On program start, environ points to initial environment.
  721. * putenv adds new pointers into it, unsetenv removes them.
  722. * Neither of these (de)allocates the strings.
  723. * setenv allocates new strings in malloc space and does putenv,
  724. * and thus setenv is unusable (leaky) for shell's purposes */
  725. #define setenv(...) setenv_is_leaky_dont_use()
  726. struct variable {
  727. struct variable *next;
  728. char *varstr; /* points to "name=" portion */
  729. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  730. uint16_t var_nest_level;
  731. smallint flg_export; /* putenv should be done on this var */
  732. smallint flg_read_only;
  733. };
  734. enum {
  735. BC_BREAK = 1,
  736. BC_CONTINUE = 2,
  737. };
  738. #if ENABLE_HUSH_FUNCTIONS
  739. struct function {
  740. struct function *next;
  741. char *name;
  742. struct command *parent_cmd;
  743. struct pipe *body;
  744. # if !BB_MMU
  745. char *body_as_string;
  746. # endif
  747. };
  748. #endif
  749. /* set -/+o OPT support. (TODO: make it optional)
  750. * bash supports the following opts:
  751. * allexport off
  752. * braceexpand on
  753. * emacs on
  754. * errexit off
  755. * errtrace off
  756. * functrace off
  757. * hashall on
  758. * histexpand off
  759. * history on
  760. * ignoreeof off
  761. * interactive-comments on
  762. * keyword off
  763. * monitor on
  764. * noclobber off
  765. * noexec off
  766. * noglob off
  767. * nolog off
  768. * notify off
  769. * nounset off
  770. * onecmd off
  771. * physical off
  772. * pipefail off
  773. * posix off
  774. * privileged off
  775. * verbose off
  776. * vi off
  777. * xtrace off
  778. */
  779. static const char o_opt_strings[] ALIGN1 =
  780. "pipefail\0"
  781. "noexec\0"
  782. "errexit\0"
  783. #if ENABLE_HUSH_MODE_X
  784. "xtrace\0"
  785. #endif
  786. ;
  787. enum {
  788. OPT_O_PIPEFAIL,
  789. OPT_O_NOEXEC,
  790. OPT_O_ERREXIT,
  791. #if ENABLE_HUSH_MODE_X
  792. OPT_O_XTRACE,
  793. #endif
  794. NUM_OPT_O
  795. };
  796. /* "Globals" within this file */
  797. /* Sorted roughly by size (smaller offsets == smaller code) */
  798. struct globals {
  799. /* interactive_fd != 0 means we are an interactive shell.
  800. * If we are, then saved_tty_pgrp can also be != 0, meaning
  801. * that controlling tty is available. With saved_tty_pgrp == 0,
  802. * job control still works, but terminal signals
  803. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  804. * process groups can only be created with "cmd &".
  805. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  806. * to give tty to the foreground process group,
  807. * and will take it back when the group is stopped (^Z)
  808. * or killed (^C).
  809. */
  810. #if ENABLE_HUSH_INTERACTIVE
  811. /* 'interactive_fd' is a fd# open to ctty, if we have one
  812. * _AND_ if we decided to act interactively */
  813. int interactive_fd;
  814. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  815. # define G_interactive_fd (G.interactive_fd)
  816. #else
  817. # define G_interactive_fd 0
  818. #endif
  819. #if ENABLE_FEATURE_EDITING
  820. line_input_t *line_input_state;
  821. #endif
  822. pid_t root_pid;
  823. pid_t root_ppid;
  824. pid_t last_bg_pid;
  825. #if ENABLE_HUSH_RANDOM_SUPPORT
  826. random_t random_gen;
  827. #endif
  828. #if ENABLE_HUSH_JOB
  829. int run_list_level;
  830. unsigned last_jobid;
  831. pid_t saved_tty_pgrp;
  832. struct pipe *job_list;
  833. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  834. #else
  835. # define G_saved_tty_pgrp 0
  836. #endif
  837. /* How deeply are we in context where "set -e" is ignored */
  838. int errexit_depth;
  839. /* "set -e" rules (do we follow them correctly?):
  840. * Exit if pipe, list, or compound command exits with a non-zero status.
  841. * Shell does not exit if failed command is part of condition in
  842. * if/while, part of && or || list except the last command, any command
  843. * in a pipe but the last, or if the command's return value is being
  844. * inverted with !. If a compound command other than a subshell returns a
  845. * non-zero status because a command failed while -e was being ignored, the
  846. * shell does not exit. A trap on ERR, if set, is executed before the shell
  847. * exits [ERR is a bashism].
  848. *
  849. * If a compound command or function executes in a context where -e is
  850. * ignored, none of the commands executed within are affected by the -e
  851. * setting. If a compound command or function sets -e while executing in a
  852. * context where -e is ignored, that setting does not have any effect until
  853. * the compound command or the command containing the function call completes.
  854. */
  855. char o_opt[NUM_OPT_O];
  856. #if ENABLE_HUSH_MODE_X
  857. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  858. #else
  859. # define G_x_mode 0
  860. #endif
  861. char opt_s;
  862. char opt_c;
  863. #if ENABLE_HUSH_INTERACTIVE
  864. smallint promptmode; /* 0: PS1, 1: PS2 */
  865. #endif
  866. smallint flag_SIGINT;
  867. #if ENABLE_HUSH_LOOPS
  868. smallint flag_break_continue;
  869. #endif
  870. #if ENABLE_HUSH_FUNCTIONS
  871. /* 0: outside of a function (or sourced file)
  872. * -1: inside of a function, ok to use return builtin
  873. * 1: return is invoked, skip all till end of func
  874. */
  875. smallint flag_return_in_progress;
  876. # define G_flag_return_in_progress (G.flag_return_in_progress)
  877. #else
  878. # define G_flag_return_in_progress 0
  879. #endif
  880. smallint exiting; /* used to prevent EXIT trap recursion */
  881. /* These support $? */
  882. smalluint last_exitcode;
  883. smalluint expand_exitcode;
  884. smalluint last_bg_pid_exitcode;
  885. #if ENABLE_HUSH_SET
  886. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  887. smalluint global_args_malloced;
  888. # define G_global_args_malloced (G.global_args_malloced)
  889. #else
  890. # define G_global_args_malloced 0
  891. #endif
  892. #if ENABLE_HUSH_BASH_COMPAT
  893. int dead_job_exitcode; /* for "wait -n" */
  894. #endif
  895. /* how many non-NULL argv's we have. NB: $# + 1 */
  896. int global_argc;
  897. char **global_argv;
  898. #if !BB_MMU
  899. char *argv0_for_re_execing;
  900. #endif
  901. #if ENABLE_HUSH_LOOPS
  902. unsigned depth_break_continue;
  903. unsigned depth_of_loop;
  904. #endif
  905. #if ENABLE_HUSH_GETOPTS
  906. unsigned getopt_count;
  907. #endif
  908. const char *ifs;
  909. char *ifs_whitespace; /* = G.ifs or malloced */
  910. const char *cwd;
  911. struct variable *top_var;
  912. char **expanded_assignments;
  913. struct variable **shadowed_vars_pp;
  914. unsigned var_nest_level;
  915. #if ENABLE_HUSH_FUNCTIONS
  916. # if ENABLE_HUSH_LOCAL
  917. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  918. # endif
  919. struct function *top_func;
  920. #endif
  921. /* Signal and trap handling */
  922. #if ENABLE_HUSH_FAST
  923. unsigned count_SIGCHLD;
  924. unsigned handled_SIGCHLD;
  925. smallint we_have_children;
  926. #endif
  927. #if ENABLE_HUSH_LINENO_VAR
  928. unsigned parse_lineno;
  929. unsigned execute_lineno;
  930. #endif
  931. HFILE *HFILE_list;
  932. HFILE *HFILE_stdin;
  933. /* Which signals have non-DFL handler (even with no traps set)?
  934. * Set at the start to:
  935. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  936. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  937. * The rest is cleared right before execv syscalls.
  938. * Other than these two times, never modified.
  939. */
  940. unsigned special_sig_mask;
  941. #if ENABLE_HUSH_JOB
  942. unsigned fatal_sig_mask;
  943. # define G_fatal_sig_mask (G.fatal_sig_mask)
  944. #else
  945. # define G_fatal_sig_mask 0
  946. #endif
  947. #if ENABLE_HUSH_TRAP
  948. char **traps; /* char *traps[NSIG] */
  949. # define G_traps G.traps
  950. #else
  951. # define G_traps ((char**)NULL)
  952. #endif
  953. sigset_t pending_set;
  954. #if ENABLE_HUSH_MEMLEAK
  955. unsigned long memleak_value;
  956. #endif
  957. #if ENABLE_HUSH_MODE_X
  958. unsigned x_mode_depth;
  959. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  960. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  961. * for all subsequent output.
  962. */
  963. int x_mode_fd;
  964. o_string x_mode_buf;
  965. #endif
  966. #if HUSH_DEBUG >= 2
  967. int debug_indent;
  968. #endif
  969. struct sigaction sa;
  970. char optstring_buf[sizeof("eixcs")];
  971. #if BASH_EPOCH_VARS
  972. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  973. #endif
  974. #if ENABLE_FEATURE_EDITING
  975. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  976. #endif
  977. };
  978. #define G (*ptr_to_globals)
  979. /* Not #defining name to G.name - this quickly gets unwieldy
  980. * (too many defines). Also, I actually prefer to see when a variable
  981. * is global, thus "G." prefix is a useful hint */
  982. #define INIT_G() do { \
  983. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  984. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  985. sigfillset(&G.sa.sa_mask); \
  986. G.sa.sa_flags = SA_RESTART; \
  987. } while (0)
  988. /* Function prototypes for builtins */
  989. static int builtin_cd(char **argv) FAST_FUNC;
  990. #if ENABLE_HUSH_ECHO
  991. static int builtin_echo(char **argv) FAST_FUNC;
  992. #endif
  993. static int builtin_eval(char **argv) FAST_FUNC;
  994. static int builtin_exec(char **argv) FAST_FUNC;
  995. static int builtin_exit(char **argv) FAST_FUNC;
  996. #if ENABLE_HUSH_EXPORT
  997. static int builtin_export(char **argv) FAST_FUNC;
  998. #endif
  999. #if ENABLE_HUSH_READONLY
  1000. static int builtin_readonly(char **argv) FAST_FUNC;
  1001. #endif
  1002. #if ENABLE_HUSH_JOB
  1003. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1004. static int builtin_jobs(char **argv) FAST_FUNC;
  1005. #endif
  1006. #if ENABLE_HUSH_GETOPTS
  1007. static int builtin_getopts(char **argv) FAST_FUNC;
  1008. #endif
  1009. #if ENABLE_HUSH_HELP
  1010. static int builtin_help(char **argv) FAST_FUNC;
  1011. #endif
  1012. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1013. static int builtin_history(char **argv) FAST_FUNC;
  1014. #endif
  1015. #if ENABLE_HUSH_LOCAL
  1016. static int builtin_local(char **argv) FAST_FUNC;
  1017. #endif
  1018. #if ENABLE_HUSH_MEMLEAK
  1019. static int builtin_memleak(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_PRINTF
  1022. static int builtin_printf(char **argv) FAST_FUNC;
  1023. #endif
  1024. static int builtin_pwd(char **argv) FAST_FUNC;
  1025. #if ENABLE_HUSH_READ
  1026. static int builtin_read(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if ENABLE_HUSH_SET
  1029. static int builtin_set(char **argv) FAST_FUNC;
  1030. #endif
  1031. static int builtin_shift(char **argv) FAST_FUNC;
  1032. static int builtin_source(char **argv) FAST_FUNC;
  1033. #if ENABLE_HUSH_TEST || BASH_TEST2
  1034. static int builtin_test(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_TRAP
  1037. static int builtin_trap(char **argv) FAST_FUNC;
  1038. #endif
  1039. #if ENABLE_HUSH_TYPE
  1040. static int builtin_type(char **argv) FAST_FUNC;
  1041. #endif
  1042. #if ENABLE_HUSH_TIMES
  1043. static int builtin_times(char **argv) FAST_FUNC;
  1044. #endif
  1045. static int builtin_true(char **argv) FAST_FUNC;
  1046. #if ENABLE_HUSH_UMASK
  1047. static int builtin_umask(char **argv) FAST_FUNC;
  1048. #endif
  1049. #if ENABLE_HUSH_UNSET
  1050. static int builtin_unset(char **argv) FAST_FUNC;
  1051. #endif
  1052. #if ENABLE_HUSH_KILL
  1053. static int builtin_kill(char **argv) FAST_FUNC;
  1054. #endif
  1055. #if ENABLE_HUSH_WAIT
  1056. static int builtin_wait(char **argv) FAST_FUNC;
  1057. #endif
  1058. #if ENABLE_HUSH_LOOPS
  1059. static int builtin_break(char **argv) FAST_FUNC;
  1060. static int builtin_continue(char **argv) FAST_FUNC;
  1061. #endif
  1062. #if ENABLE_HUSH_FUNCTIONS
  1063. static int builtin_return(char **argv) FAST_FUNC;
  1064. #endif
  1065. /* Table of built-in functions. They can be forked or not, depending on
  1066. * context: within pipes, they fork. As simple commands, they do not.
  1067. * When used in non-forking context, they can change global variables
  1068. * in the parent shell process. If forked, of course they cannot.
  1069. * For example, 'unset foo | whatever' will parse and run, but foo will
  1070. * still be set at the end. */
  1071. struct built_in_command {
  1072. const char *b_cmd;
  1073. int (*b_function)(char **argv) FAST_FUNC;
  1074. #if ENABLE_HUSH_HELP
  1075. const char *b_descr;
  1076. # define BLTIN(cmd, func, help) { cmd, func, help }
  1077. #else
  1078. # define BLTIN(cmd, func, help) { cmd, func }
  1079. #endif
  1080. };
  1081. static const struct built_in_command bltins1[] = {
  1082. BLTIN("." , builtin_source , "Run commands in file"),
  1083. BLTIN(":" , builtin_true , NULL),
  1084. #if ENABLE_HUSH_JOB
  1085. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1086. #endif
  1087. #if ENABLE_HUSH_LOOPS
  1088. BLTIN("break" , builtin_break , "Exit loop"),
  1089. #endif
  1090. BLTIN("cd" , builtin_cd , "Change directory"),
  1091. #if ENABLE_HUSH_LOOPS
  1092. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1093. #endif
  1094. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1095. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1096. BLTIN("exit" , builtin_exit , NULL),
  1097. #if ENABLE_HUSH_EXPORT
  1098. BLTIN("export" , builtin_export , "Set environment variables"),
  1099. #endif
  1100. #if ENABLE_HUSH_JOB
  1101. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1102. #endif
  1103. #if ENABLE_HUSH_GETOPTS
  1104. BLTIN("getopts" , builtin_getopts , NULL),
  1105. #endif
  1106. #if ENABLE_HUSH_HELP
  1107. BLTIN("help" , builtin_help , NULL),
  1108. #endif
  1109. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1110. BLTIN("history" , builtin_history , "Show history"),
  1111. #endif
  1112. #if ENABLE_HUSH_JOB
  1113. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1114. #endif
  1115. #if ENABLE_HUSH_KILL
  1116. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1117. #endif
  1118. #if ENABLE_HUSH_LOCAL
  1119. BLTIN("local" , builtin_local , "Set local variables"),
  1120. #endif
  1121. #if ENABLE_HUSH_MEMLEAK
  1122. BLTIN("memleak" , builtin_memleak , NULL),
  1123. #endif
  1124. #if ENABLE_HUSH_READ
  1125. BLTIN("read" , builtin_read , "Input into variable"),
  1126. #endif
  1127. #if ENABLE_HUSH_READONLY
  1128. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1129. #endif
  1130. #if ENABLE_HUSH_FUNCTIONS
  1131. BLTIN("return" , builtin_return , "Return from function"),
  1132. #endif
  1133. #if ENABLE_HUSH_SET
  1134. BLTIN("set" , builtin_set , "Set positional parameters"),
  1135. #endif
  1136. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1137. #if BASH_SOURCE
  1138. BLTIN("source" , builtin_source , NULL),
  1139. #endif
  1140. #if ENABLE_HUSH_TIMES
  1141. BLTIN("times" , builtin_times , NULL),
  1142. #endif
  1143. #if ENABLE_HUSH_TRAP
  1144. BLTIN("trap" , builtin_trap , "Trap signals"),
  1145. #endif
  1146. BLTIN("true" , builtin_true , NULL),
  1147. #if ENABLE_HUSH_TYPE
  1148. BLTIN("type" , builtin_type , "Show command type"),
  1149. #endif
  1150. #if ENABLE_HUSH_ULIMIT
  1151. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1152. #endif
  1153. #if ENABLE_HUSH_UMASK
  1154. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1155. #endif
  1156. #if ENABLE_HUSH_UNSET
  1157. BLTIN("unset" , builtin_unset , "Unset variables"),
  1158. #endif
  1159. #if ENABLE_HUSH_WAIT
  1160. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1161. #endif
  1162. };
  1163. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1164. * (it's cheaper to run an external program in this case):
  1165. */
  1166. static const struct built_in_command bltins2[] = {
  1167. #if ENABLE_HUSH_TEST
  1168. BLTIN("[" , builtin_test , NULL),
  1169. #endif
  1170. #if BASH_TEST2
  1171. BLTIN("[[" , builtin_test , NULL),
  1172. #endif
  1173. #if ENABLE_HUSH_ECHO
  1174. BLTIN("echo" , builtin_echo , NULL),
  1175. #endif
  1176. #if ENABLE_HUSH_PRINTF
  1177. BLTIN("printf" , builtin_printf , NULL),
  1178. #endif
  1179. BLTIN("pwd" , builtin_pwd , NULL),
  1180. #if ENABLE_HUSH_TEST
  1181. BLTIN("test" , builtin_test , NULL),
  1182. #endif
  1183. };
  1184. /* Debug printouts.
  1185. */
  1186. #if HUSH_DEBUG >= 2
  1187. /* prevent disasters with G.debug_indent < 0 */
  1188. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1189. # define debug_enter() (G.debug_indent++)
  1190. # define debug_leave() (G.debug_indent--)
  1191. #else
  1192. # define indent() ((void)0)
  1193. # define debug_enter() ((void)0)
  1194. # define debug_leave() ((void)0)
  1195. #endif
  1196. #ifndef debug_printf
  1197. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1198. #endif
  1199. #ifndef debug_printf_parse
  1200. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1201. #endif
  1202. #ifndef debug_printf_heredoc
  1203. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1204. #endif
  1205. #ifndef debug_printf_exec
  1206. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1207. #endif
  1208. #ifndef debug_printf_env
  1209. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1210. #endif
  1211. #ifndef debug_printf_jobs
  1212. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. # define DEBUG_JOBS 1
  1214. #else
  1215. # define DEBUG_JOBS 0
  1216. #endif
  1217. #ifndef debug_printf_expand
  1218. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. # define DEBUG_EXPAND 1
  1220. #else
  1221. # define DEBUG_EXPAND 0
  1222. #endif
  1223. #ifndef debug_printf_varexp
  1224. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_glob
  1227. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_GLOB 1
  1229. #else
  1230. # define DEBUG_GLOB 0
  1231. #endif
  1232. #ifndef debug_printf_redir
  1233. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. #endif
  1235. #ifndef debug_printf_list
  1236. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1237. #endif
  1238. #ifndef debug_printf_subst
  1239. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_prompt
  1242. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. #endif
  1244. #ifndef debug_printf_clean
  1245. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1246. # define DEBUG_CLEAN 1
  1247. #else
  1248. # define DEBUG_CLEAN 0
  1249. #endif
  1250. #if DEBUG_EXPAND
  1251. static void debug_print_strings(const char *prefix, char **vv)
  1252. {
  1253. indent();
  1254. fdprintf(2, "%s:\n", prefix);
  1255. while (*vv)
  1256. fdprintf(2, " '%s'\n", *vv++);
  1257. }
  1258. #else
  1259. # define debug_print_strings(prefix, vv) ((void)0)
  1260. #endif
  1261. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1262. */
  1263. #if LEAK_HUNTING
  1264. static void *xxmalloc(int lineno, size_t size)
  1265. {
  1266. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1267. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1268. return ptr;
  1269. }
  1270. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1271. {
  1272. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1273. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1274. return ptr;
  1275. }
  1276. static char *xxstrdup(int lineno, const char *str)
  1277. {
  1278. char *ptr = xstrdup(str);
  1279. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1280. return ptr;
  1281. }
  1282. static void xxfree(void *ptr)
  1283. {
  1284. fdprintf(2, "free %p\n", ptr);
  1285. free(ptr);
  1286. }
  1287. # define xmalloc(s) xxmalloc(__LINE__, s)
  1288. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1289. # define xstrdup(s) xxstrdup(__LINE__, s)
  1290. # define free(p) xxfree(p)
  1291. #endif
  1292. /* Syntax and runtime errors. They always abort scripts.
  1293. * In interactive use they usually discard unparsed and/or unexecuted commands
  1294. * and return to the prompt.
  1295. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1296. */
  1297. #if HUSH_DEBUG < 2
  1298. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1299. # define syntax_error(lineno, msg) syntax_error(msg)
  1300. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1301. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1302. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1303. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1304. #endif
  1305. static void die_if_script(void)
  1306. {
  1307. if (!G_interactive_fd) {
  1308. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1309. xfunc_error_retval = G.last_exitcode;
  1310. xfunc_die();
  1311. }
  1312. }
  1313. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1314. {
  1315. va_list p;
  1316. #if HUSH_DEBUG >= 2
  1317. bb_error_msg("hush.c:%u", lineno);
  1318. #endif
  1319. va_start(p, fmt);
  1320. bb_verror_msg(fmt, p, NULL);
  1321. va_end(p);
  1322. die_if_script();
  1323. }
  1324. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1325. {
  1326. if (msg)
  1327. bb_error_msg("syntax error: %s", msg);
  1328. else
  1329. bb_simple_error_msg("syntax error");
  1330. die_if_script();
  1331. }
  1332. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1333. {
  1334. bb_error_msg("syntax error at '%s'", msg);
  1335. die_if_script();
  1336. }
  1337. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1338. {
  1339. bb_error_msg("syntax error: unterminated %s", s);
  1340. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1341. // die_if_script();
  1342. }
  1343. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1344. {
  1345. char msg[2] = { ch, '\0' };
  1346. syntax_error_unterm_str(lineno, msg);
  1347. }
  1348. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1349. {
  1350. char msg[2];
  1351. msg[0] = ch;
  1352. msg[1] = '\0';
  1353. #if HUSH_DEBUG >= 2
  1354. bb_error_msg("hush.c:%u", lineno);
  1355. #endif
  1356. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1357. die_if_script();
  1358. }
  1359. #if HUSH_DEBUG < 2
  1360. # undef msg_and_die_if_script
  1361. # undef syntax_error
  1362. # undef syntax_error_at
  1363. # undef syntax_error_unterm_ch
  1364. # undef syntax_error_unterm_str
  1365. # undef syntax_error_unexpected_ch
  1366. #else
  1367. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1368. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1369. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1370. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1371. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1372. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1373. #endif
  1374. /* Utility functions
  1375. */
  1376. /* Replace each \x with x in place, return ptr past NUL. */
  1377. static char *unbackslash(char *src)
  1378. {
  1379. char *dst = src = strchrnul(src, '\\');
  1380. while (1) {
  1381. if (*src == '\\') {
  1382. src++;
  1383. if (*src != '\0') {
  1384. /* \x -> x */
  1385. *dst++ = *src++;
  1386. continue;
  1387. }
  1388. /* else: "\<nul>". Do not delete this backslash.
  1389. * Testcase: eval 'echo ok\'
  1390. */
  1391. *dst++ = '\\';
  1392. /* fallthrough */
  1393. }
  1394. if ((*dst++ = *src++) == '\0')
  1395. break;
  1396. }
  1397. return dst;
  1398. }
  1399. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1400. {
  1401. int i;
  1402. unsigned count1;
  1403. unsigned count2;
  1404. char **v;
  1405. v = strings;
  1406. count1 = 0;
  1407. if (v) {
  1408. while (*v) {
  1409. count1++;
  1410. v++;
  1411. }
  1412. }
  1413. count2 = 0;
  1414. v = add;
  1415. while (*v) {
  1416. count2++;
  1417. v++;
  1418. }
  1419. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1420. v[count1 + count2] = NULL;
  1421. i = count2;
  1422. while (--i >= 0)
  1423. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1424. return v;
  1425. }
  1426. #if LEAK_HUNTING
  1427. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1428. {
  1429. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1430. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1431. return ptr;
  1432. }
  1433. #define add_strings_to_strings(strings, add, need_to_dup) \
  1434. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1435. #endif
  1436. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1437. static char **add_string_to_strings(char **strings, char *add)
  1438. {
  1439. char *v[2];
  1440. v[0] = add;
  1441. v[1] = NULL;
  1442. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1443. }
  1444. #if LEAK_HUNTING
  1445. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1446. {
  1447. char **ptr = add_string_to_strings(strings, add);
  1448. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1449. return ptr;
  1450. }
  1451. #define add_string_to_strings(strings, add) \
  1452. xx_add_string_to_strings(__LINE__, strings, add)
  1453. #endif
  1454. static void free_strings(char **strings)
  1455. {
  1456. char **v;
  1457. if (!strings)
  1458. return;
  1459. v = strings;
  1460. while (*v) {
  1461. free(*v);
  1462. v++;
  1463. }
  1464. free(strings);
  1465. }
  1466. static int dup_CLOEXEC(int fd, int avoid_fd)
  1467. {
  1468. int newfd;
  1469. repeat:
  1470. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1471. if (newfd >= 0) {
  1472. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1473. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1474. } else { /* newfd < 0 */
  1475. if (errno == EBUSY)
  1476. goto repeat;
  1477. if (errno == EINTR)
  1478. goto repeat;
  1479. }
  1480. return newfd;
  1481. }
  1482. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1483. {
  1484. int newfd;
  1485. repeat:
  1486. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1487. if (newfd < 0) {
  1488. if (errno == EBUSY)
  1489. goto repeat;
  1490. if (errno == EINTR)
  1491. goto repeat;
  1492. /* fd was not open? */
  1493. if (errno == EBADF)
  1494. return fd;
  1495. xfunc_die();
  1496. }
  1497. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1498. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1499. close(fd);
  1500. return newfd;
  1501. }
  1502. /* Manipulating HFILEs */
  1503. static HFILE *hfopen(const char *name)
  1504. {
  1505. HFILE *fp;
  1506. int fd;
  1507. fd = STDIN_FILENO;
  1508. if (name) {
  1509. fd = open(name, O_RDONLY | O_CLOEXEC);
  1510. if (fd < 0)
  1511. return NULL;
  1512. if (O_CLOEXEC == 0) /* ancient libc */
  1513. close_on_exec_on(fd);
  1514. }
  1515. fp = xmalloc(sizeof(*fp));
  1516. if (name == NULL)
  1517. G.HFILE_stdin = fp;
  1518. fp->fd = fd;
  1519. fp->cur = fp->end = fp->buf;
  1520. fp->next_hfile = G.HFILE_list;
  1521. G.HFILE_list = fp;
  1522. return fp;
  1523. }
  1524. static void hfclose(HFILE *fp)
  1525. {
  1526. HFILE **pp = &G.HFILE_list;
  1527. while (*pp) {
  1528. HFILE *cur = *pp;
  1529. if (cur == fp) {
  1530. *pp = cur->next_hfile;
  1531. break;
  1532. }
  1533. pp = &cur->next_hfile;
  1534. }
  1535. if (fp->fd >= 0)
  1536. close(fp->fd);
  1537. free(fp);
  1538. }
  1539. static int refill_HFILE_and_getc(HFILE *fp)
  1540. {
  1541. int n;
  1542. if (fp->fd < 0) {
  1543. /* Already saw EOF */
  1544. return EOF;
  1545. }
  1546. /* Try to buffer more input */
  1547. fp->cur = fp->buf;
  1548. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1549. if (n < 0) {
  1550. bb_simple_perror_msg("read error");
  1551. n = 0;
  1552. }
  1553. fp->end = fp->buf + n;
  1554. if (n == 0) {
  1555. /* EOF/error */
  1556. close(fp->fd);
  1557. fp->fd = -1;
  1558. return EOF;
  1559. }
  1560. return (unsigned char)(*fp->cur++);
  1561. }
  1562. /* Inlined for common case of non-empty buffer.
  1563. */
  1564. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1565. {
  1566. if (fp->cur < fp->end)
  1567. return (unsigned char)(*fp->cur++);
  1568. /* Buffer empty */
  1569. return refill_HFILE_and_getc(fp);
  1570. }
  1571. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1572. {
  1573. HFILE *fl = G.HFILE_list;
  1574. while (fl) {
  1575. if (fd == fl->fd) {
  1576. /* We use it only on script files, they are all CLOEXEC */
  1577. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1578. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1579. return 1; /* "found and moved" */
  1580. }
  1581. fl = fl->next_hfile;
  1582. }
  1583. #if ENABLE_HUSH_MODE_X
  1584. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1585. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1586. return 1; /* "found and moved" */
  1587. }
  1588. #endif
  1589. return 0; /* "not in the list" */
  1590. }
  1591. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1592. static void close_all_HFILE_list(void)
  1593. {
  1594. HFILE *fl = G.HFILE_list;
  1595. while (fl) {
  1596. /* hfclose would also free HFILE object.
  1597. * It is disastrous if we share memory with a vforked parent.
  1598. * I'm not sure we never come here after vfork.
  1599. * Therefore just close fd, nothing more.
  1600. *
  1601. * ">" instead of ">=": we don't close fd#0,
  1602. * interactive shell uses hfopen(NULL) as stdin input
  1603. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1604. * If we'd close it here, then e.g. interactive "set | sort"
  1605. * with NOFORKed sort, would have sort's input fd closed.
  1606. */
  1607. if (fl->fd > 0)
  1608. /*hfclose(fl); - unsafe */
  1609. close(fl->fd);
  1610. fl = fl->next_hfile;
  1611. }
  1612. }
  1613. #endif
  1614. static int fd_in_HFILEs(int fd)
  1615. {
  1616. HFILE *fl = G.HFILE_list;
  1617. while (fl) {
  1618. if (fl->fd == fd)
  1619. return 1;
  1620. fl = fl->next_hfile;
  1621. }
  1622. return 0;
  1623. }
  1624. /* Helpers for setting new $n and restoring them back
  1625. */
  1626. typedef struct save_arg_t {
  1627. char *sv_argv0;
  1628. char **sv_g_argv;
  1629. int sv_g_argc;
  1630. IF_HUSH_SET(smallint sv_g_malloced;)
  1631. } save_arg_t;
  1632. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1633. {
  1634. sv->sv_argv0 = argv[0];
  1635. sv->sv_g_argv = G.global_argv;
  1636. sv->sv_g_argc = G.global_argc;
  1637. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1638. argv[0] = G.global_argv[0]; /* retain $0 */
  1639. G.global_argv = argv;
  1640. IF_HUSH_SET(G.global_args_malloced = 0;)
  1641. G.global_argc = 1 + string_array_len(argv + 1);
  1642. }
  1643. static void restore_G_args(save_arg_t *sv, char **argv)
  1644. {
  1645. #if ENABLE_HUSH_SET
  1646. if (G.global_args_malloced) {
  1647. /* someone ran "set -- arg1 arg2 ...", undo */
  1648. char **pp = G.global_argv;
  1649. while (*++pp) /* note: does not free $0 */
  1650. free(*pp);
  1651. free(G.global_argv);
  1652. }
  1653. #endif
  1654. argv[0] = sv->sv_argv0;
  1655. G.global_argv = sv->sv_g_argv;
  1656. G.global_argc = sv->sv_g_argc;
  1657. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1658. }
  1659. /* Basic theory of signal handling in shell
  1660. * ========================================
  1661. * This does not describe what hush does, rather, it is current understanding
  1662. * what it _should_ do. If it doesn't, it's a bug.
  1663. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1664. *
  1665. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1666. * is finished or backgrounded. It is the same in interactive and
  1667. * non-interactive shells, and is the same regardless of whether
  1668. * a user trap handler is installed or a shell special one is in effect.
  1669. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1670. * backgrounds (i.e. stops) or kills all members of currently running
  1671. * pipe.
  1672. *
  1673. * Wait builtin is interruptible by signals for which user trap is set
  1674. * or by SIGINT in interactive shell.
  1675. *
  1676. * Trap handlers will execute even within trap handlers. (right?)
  1677. *
  1678. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1679. * except for handlers set to '' (empty string).
  1680. *
  1681. * If job control is off, backgrounded commands ("cmd &")
  1682. * have SIGINT, SIGQUIT set to SIG_IGN.
  1683. *
  1684. * Commands which are run in command substitution ("`cmd`")
  1685. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1686. *
  1687. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1688. * by the shell from its parent.
  1689. *
  1690. * Signals which differ from SIG_DFL action
  1691. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1692. *
  1693. * SIGQUIT: ignore
  1694. * SIGTERM (interactive): ignore
  1695. * SIGHUP (interactive):
  1696. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1697. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1698. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1699. * that all pipe members are stopped. Try this in bash:
  1700. * while :; do :; done - ^Z does not background it
  1701. * (while :; do :; done) - ^Z backgrounds it
  1702. * SIGINT (interactive): wait for last pipe, ignore the rest
  1703. * of the command line, show prompt. NB: ^C does not send SIGINT
  1704. * to interactive shell while shell is waiting for a pipe,
  1705. * since shell is bg'ed (is not in foreground process group).
  1706. * Example 1: this waits 5 sec, but does not execute ls:
  1707. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1708. * Example 2: this does not wait and does not execute ls:
  1709. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1710. * Example 3: this does not wait 5 sec, but executes ls:
  1711. * "sleep 5; ls -l" + press ^C
  1712. * Example 4: this does not wait and does not execute ls:
  1713. * "sleep 5 & wait; ls -l" + press ^C
  1714. *
  1715. * (What happens to signals which are IGN on shell start?)
  1716. * (What happens with signal mask on shell start?)
  1717. *
  1718. * Old implementation
  1719. * ==================
  1720. * We use in-kernel pending signal mask to determine which signals were sent.
  1721. * We block all signals which we don't want to take action immediately,
  1722. * i.e. we block all signals which need to have special handling as described
  1723. * above, and all signals which have traps set.
  1724. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1725. * and act on them.
  1726. *
  1727. * unsigned special_sig_mask: a mask of such "special" signals
  1728. * sigset_t blocked_set: current blocked signal set
  1729. *
  1730. * "trap - SIGxxx":
  1731. * clear bit in blocked_set unless it is also in special_sig_mask
  1732. * "trap 'cmd' SIGxxx":
  1733. * set bit in blocked_set (even if 'cmd' is '')
  1734. * after [v]fork, if we plan to be a shell:
  1735. * unblock signals with special interactive handling
  1736. * (child shell is not interactive),
  1737. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1738. * after [v]fork, if we plan to exec:
  1739. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1740. * Restore blocked signal set to one inherited by shell just prior to exec.
  1741. *
  1742. * Note: as a result, we do not use signal handlers much. The only uses
  1743. * are to count SIGCHLDs
  1744. * and to restore tty pgrp on signal-induced exit.
  1745. *
  1746. * Note 2 (compat):
  1747. * Standard says "When a subshell is entered, traps that are not being ignored
  1748. * are set to the default actions". bash interprets it so that traps which
  1749. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1750. *
  1751. * Problem: the above approach makes it unwieldy to catch signals while
  1752. * we are in read builtin, or while we read commands from stdin:
  1753. * masked signals are not visible!
  1754. *
  1755. * New implementation
  1756. * ==================
  1757. * We record each signal we are interested in by installing signal handler
  1758. * for them - a bit like emulating kernel pending signal mask in userspace.
  1759. * We are interested in: signals which need to have special handling
  1760. * as described above, and all signals which have traps set.
  1761. * Signals are recorded in pending_set.
  1762. * After each pipe execution, we extract any pending signals
  1763. * and act on them.
  1764. *
  1765. * unsigned special_sig_mask: a mask of shell-special signals.
  1766. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1767. * char *traps[sig] if trap for sig is set (even if it's '').
  1768. * sigset_t pending_set: set of sigs we received.
  1769. *
  1770. * "trap - SIGxxx":
  1771. * if sig is in special_sig_mask, set handler back to:
  1772. * record_pending_signo, or to IGN if it's a tty stop signal
  1773. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1774. * else: set handler back to SIG_DFL
  1775. * "trap 'cmd' SIGxxx":
  1776. * set handler to record_pending_signo.
  1777. * "trap '' SIGxxx":
  1778. * set handler to SIG_IGN.
  1779. * after [v]fork, if we plan to be a shell:
  1780. * set signals with special interactive handling to SIG_DFL
  1781. * (because child shell is not interactive),
  1782. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1783. * after [v]fork, if we plan to exec:
  1784. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1785. *
  1786. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1787. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1788. *
  1789. * Note (compat):
  1790. * Standard says "When a subshell is entered, traps that are not being ignored
  1791. * are set to the default actions". bash interprets it so that traps which
  1792. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1793. */
  1794. enum {
  1795. SPECIAL_INTERACTIVE_SIGS = 0
  1796. | (1 << SIGTERM)
  1797. | (1 << SIGINT)
  1798. | (1 << SIGHUP)
  1799. ,
  1800. SPECIAL_JOBSTOP_SIGS = 0
  1801. #if ENABLE_HUSH_JOB
  1802. | (1 << SIGTTIN)
  1803. | (1 << SIGTTOU)
  1804. | (1 << SIGTSTP)
  1805. #endif
  1806. ,
  1807. };
  1808. static void record_pending_signo(int sig)
  1809. {
  1810. sigaddset(&G.pending_set, sig);
  1811. #if ENABLE_HUSH_FAST
  1812. if (sig == SIGCHLD) {
  1813. G.count_SIGCHLD++;
  1814. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1815. }
  1816. #endif
  1817. }
  1818. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1819. {
  1820. struct sigaction old_sa;
  1821. /* We could use signal() to install handlers... almost:
  1822. * except that we need to mask ALL signals while handlers run.
  1823. * I saw signal nesting in strace, race window isn't small.
  1824. * SA_RESTART is also needed, but in Linux, signal()
  1825. * sets SA_RESTART too.
  1826. */
  1827. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1828. /* sigfillset(&G.sa.sa_mask); - already done */
  1829. /* G.sa.sa_flags = SA_RESTART; - already done */
  1830. G.sa.sa_handler = handler;
  1831. sigaction(sig, &G.sa, &old_sa);
  1832. return old_sa.sa_handler;
  1833. }
  1834. static void hush_exit(int exitcode) NORETURN;
  1835. static void restore_ttypgrp_and__exit(void) NORETURN;
  1836. static void restore_ttypgrp_and__exit(void)
  1837. {
  1838. /* xfunc has failed! die die die */
  1839. /* no EXIT traps, this is an escape hatch! */
  1840. G.exiting = 1;
  1841. hush_exit(xfunc_error_retval);
  1842. }
  1843. #if ENABLE_HUSH_JOB
  1844. /* Needed only on some libc:
  1845. * It was observed that on exit(), fgetc'ed buffered data
  1846. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1847. * With the net effect that even after fork(), not vfork(),
  1848. * exit() in NOEXECed applet in "sh SCRIPT":
  1849. * noexec_applet_here
  1850. * echo END_OF_SCRIPT
  1851. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1852. * This makes "echo END_OF_SCRIPT" executed twice.
  1853. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1854. * and in `cmd` handling.
  1855. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1856. */
  1857. static void fflush_and__exit(void) NORETURN;
  1858. static void fflush_and__exit(void)
  1859. {
  1860. fflush_all();
  1861. _exit(xfunc_error_retval);
  1862. }
  1863. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1864. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1865. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1866. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1867. /* Restores tty foreground process group, and exits.
  1868. * May be called as signal handler for fatal signal
  1869. * (will resend signal to itself, producing correct exit state)
  1870. * or called directly with -EXITCODE.
  1871. * We also call it if xfunc is exiting.
  1872. */
  1873. static void sigexit(int sig) NORETURN;
  1874. static void sigexit(int sig)
  1875. {
  1876. /* Careful: we can end up here after [v]fork. Do not restore
  1877. * tty pgrp then, only top-level shell process does that */
  1878. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1879. /* Disable all signals: job control, SIGPIPE, etc.
  1880. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1881. */
  1882. sigprocmask_allsigs(SIG_BLOCK);
  1883. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1884. }
  1885. /* Not a signal, just exit */
  1886. if (sig <= 0)
  1887. _exit(- sig);
  1888. kill_myself_with_sig(sig); /* does not return */
  1889. }
  1890. #else
  1891. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1892. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1893. #endif
  1894. static sighandler_t pick_sighandler(unsigned sig)
  1895. {
  1896. sighandler_t handler = SIG_DFL;
  1897. if (sig < sizeof(unsigned)*8) {
  1898. unsigned sigmask = (1 << sig);
  1899. #if ENABLE_HUSH_JOB
  1900. /* is sig fatal? */
  1901. if (G_fatal_sig_mask & sigmask)
  1902. handler = sigexit;
  1903. else
  1904. #endif
  1905. /* sig has special handling? */
  1906. if (G.special_sig_mask & sigmask) {
  1907. handler = record_pending_signo;
  1908. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1909. * in order to ignore them: they will be raised
  1910. * in an endless loop when we try to do some
  1911. * terminal ioctls! We do have to _ignore_ these.
  1912. */
  1913. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1914. handler = SIG_IGN;
  1915. }
  1916. }
  1917. return handler;
  1918. }
  1919. /* Restores tty foreground process group, and exits. */
  1920. static void hush_exit(int exitcode)
  1921. {
  1922. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1923. if (G.line_input_state)
  1924. save_history(G.line_input_state);
  1925. #endif
  1926. fflush_all();
  1927. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1928. char *argv[3];
  1929. /* argv[0] is unused */
  1930. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1931. argv[2] = NULL;
  1932. G.exiting = 1; /* prevent EXIT trap recursion */
  1933. /* Note: G_traps[0] is not cleared!
  1934. * "trap" will still show it, if executed
  1935. * in the handler */
  1936. builtin_eval(argv);
  1937. }
  1938. #if ENABLE_FEATURE_CLEAN_UP
  1939. {
  1940. struct variable *cur_var;
  1941. if (G.cwd != bb_msg_unknown)
  1942. free((char*)G.cwd);
  1943. cur_var = G.top_var;
  1944. while (cur_var) {
  1945. struct variable *tmp = cur_var;
  1946. if (!cur_var->max_len)
  1947. free(cur_var->varstr);
  1948. cur_var = cur_var->next;
  1949. free(tmp);
  1950. }
  1951. }
  1952. #endif
  1953. fflush_all();
  1954. #if ENABLE_HUSH_JOB
  1955. sigexit(- (exitcode & 0xff));
  1956. #else
  1957. _exit(exitcode);
  1958. #endif
  1959. }
  1960. //TODO: return a mask of ALL handled sigs?
  1961. static int check_and_run_traps(void)
  1962. {
  1963. int last_sig = 0;
  1964. while (1) {
  1965. int sig;
  1966. if (sigisemptyset(&G.pending_set))
  1967. break;
  1968. sig = 0;
  1969. do {
  1970. sig++;
  1971. if (sigismember(&G.pending_set, sig)) {
  1972. sigdelset(&G.pending_set, sig);
  1973. goto got_sig;
  1974. }
  1975. } while (sig < NSIG);
  1976. break;
  1977. got_sig:
  1978. if (G_traps && G_traps[sig]) {
  1979. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1980. if (G_traps[sig][0]) {
  1981. /* We have user-defined handler */
  1982. smalluint save_rcode;
  1983. char *argv[3];
  1984. /* argv[0] is unused */
  1985. argv[1] = xstrdup(G_traps[sig]);
  1986. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1987. argv[2] = NULL;
  1988. save_rcode = G.last_exitcode;
  1989. builtin_eval(argv);
  1990. free(argv[1]);
  1991. //FIXME: shouldn't it be set to 128 + sig instead?
  1992. G.last_exitcode = save_rcode;
  1993. last_sig = sig;
  1994. } /* else: "" trap, ignoring signal */
  1995. continue;
  1996. }
  1997. /* not a trap: special action */
  1998. switch (sig) {
  1999. case SIGINT:
  2000. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2001. G.flag_SIGINT = 1;
  2002. last_sig = sig;
  2003. break;
  2004. #if ENABLE_HUSH_JOB
  2005. case SIGHUP: {
  2006. //TODO: why are we doing this? ash and dash don't do this,
  2007. //they have no handler for SIGHUP at all,
  2008. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2009. struct pipe *job;
  2010. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2011. /* bash is observed to signal whole process groups,
  2012. * not individual processes */
  2013. for (job = G.job_list; job; job = job->next) {
  2014. if (job->pgrp <= 0)
  2015. continue;
  2016. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2017. if (kill(- job->pgrp, SIGHUP) == 0)
  2018. kill(- job->pgrp, SIGCONT);
  2019. }
  2020. sigexit(SIGHUP);
  2021. }
  2022. #endif
  2023. #if ENABLE_HUSH_FAST
  2024. case SIGCHLD:
  2025. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2026. G.count_SIGCHLD++;
  2027. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2028. /* Note:
  2029. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2030. * This simplifies wait builtin a bit.
  2031. */
  2032. break;
  2033. #endif
  2034. default: /* ignored: */
  2035. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2036. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2037. /* Note:
  2038. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2039. * Example: wait is not interrupted by TERM
  2040. * in interactive shell, because TERM is ignored.
  2041. */
  2042. break;
  2043. }
  2044. }
  2045. return last_sig;
  2046. }
  2047. static const char *get_cwd(int force)
  2048. {
  2049. if (force || G.cwd == NULL) {
  2050. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2051. * we must not try to free(bb_msg_unknown) */
  2052. if (G.cwd == bb_msg_unknown)
  2053. G.cwd = NULL;
  2054. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2055. if (!G.cwd)
  2056. G.cwd = bb_msg_unknown;
  2057. }
  2058. return G.cwd;
  2059. }
  2060. /*
  2061. * Shell and environment variable support
  2062. */
  2063. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2064. {
  2065. struct variable **pp;
  2066. struct variable *cur;
  2067. pp = &G.top_var;
  2068. while ((cur = *pp) != NULL) {
  2069. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2070. return pp;
  2071. pp = &cur->next;
  2072. }
  2073. return NULL;
  2074. }
  2075. static const char* FAST_FUNC get_local_var_value(const char *name)
  2076. {
  2077. struct variable **vpp;
  2078. unsigned len = strlen(name);
  2079. if (G.expanded_assignments) {
  2080. char **cpp = G.expanded_assignments;
  2081. while (*cpp) {
  2082. char *cp = *cpp;
  2083. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2084. return cp + len + 1;
  2085. cpp++;
  2086. }
  2087. }
  2088. vpp = get_ptr_to_local_var(name, len);
  2089. if (vpp)
  2090. return (*vpp)->varstr + len + 1;
  2091. if (strcmp(name, "PPID") == 0)
  2092. return utoa(G.root_ppid);
  2093. // bash compat: UID? EUID?
  2094. #if ENABLE_HUSH_RANDOM_SUPPORT
  2095. if (strcmp(name, "RANDOM") == 0)
  2096. return utoa(next_random(&G.random_gen));
  2097. #endif
  2098. #if ENABLE_HUSH_LINENO_VAR
  2099. if (strcmp(name, "LINENO") == 0)
  2100. return utoa(G.execute_lineno);
  2101. #endif
  2102. #if BASH_EPOCH_VARS
  2103. {
  2104. const char *fmt = NULL;
  2105. if (strcmp(name, "EPOCHSECONDS") == 0)
  2106. fmt = "%lu";
  2107. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2108. fmt = "%lu.%06u";
  2109. if (fmt) {
  2110. struct timeval tv;
  2111. gettimeofday(&tv, NULL);
  2112. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2113. (unsigned)tv.tv_usec);
  2114. return G.epoch_buf;
  2115. }
  2116. }
  2117. #endif
  2118. return NULL;
  2119. }
  2120. #if ENABLE_HUSH_GETOPTS
  2121. static void handle_changed_special_names(const char *name, unsigned name_len)
  2122. {
  2123. if (name_len == 6) {
  2124. if (strncmp(name, "OPTIND", 6) == 0) {
  2125. G.getopt_count = 0;
  2126. return;
  2127. }
  2128. }
  2129. }
  2130. #else
  2131. /* Do not even bother evaluating arguments */
  2132. # define handle_changed_special_names(...) ((void)0)
  2133. #endif
  2134. /* str holds "NAME=VAL" and is expected to be malloced.
  2135. * We take ownership of it.
  2136. */
  2137. #define SETFLAG_EXPORT (1 << 0)
  2138. #define SETFLAG_UNEXPORT (1 << 1)
  2139. #define SETFLAG_MAKE_RO (1 << 2)
  2140. #define SETFLAG_VARLVL_SHIFT 3
  2141. static int set_local_var(char *str, unsigned flags)
  2142. {
  2143. struct variable **cur_pp;
  2144. struct variable *cur;
  2145. char *free_me = NULL;
  2146. char *eq_sign;
  2147. int name_len;
  2148. int retval;
  2149. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2150. eq_sign = strchr(str, '=');
  2151. if (HUSH_DEBUG && !eq_sign)
  2152. bb_simple_error_msg_and_die("BUG in setvar");
  2153. name_len = eq_sign - str + 1; /* including '=' */
  2154. cur_pp = &G.top_var;
  2155. while ((cur = *cur_pp) != NULL) {
  2156. if (strncmp(cur->varstr, str, name_len) != 0) {
  2157. cur_pp = &cur->next;
  2158. continue;
  2159. }
  2160. /* We found an existing var with this name */
  2161. if (cur->flg_read_only) {
  2162. bb_error_msg("%s: readonly variable", str);
  2163. free(str);
  2164. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2165. //but export per se succeeds (does put the var in env). We don't mimic that.
  2166. return -1;
  2167. }
  2168. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2169. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2170. *eq_sign = '\0';
  2171. unsetenv(str);
  2172. *eq_sign = '=';
  2173. }
  2174. if (cur->var_nest_level < local_lvl) {
  2175. /* bash 3.2.33(1) and exported vars:
  2176. * # export z=z
  2177. * # f() { local z=a; env | grep ^z; }
  2178. * # f
  2179. * z=a
  2180. * # env | grep ^z
  2181. * z=z
  2182. */
  2183. if (cur->flg_export)
  2184. flags |= SETFLAG_EXPORT;
  2185. /* New variable is local ("local VAR=VAL" or
  2186. * "VAR=VAL cmd")
  2187. * and existing one is global, or local
  2188. * on a lower level that new one.
  2189. * Remove it from global variable list:
  2190. */
  2191. *cur_pp = cur->next;
  2192. if (G.shadowed_vars_pp) {
  2193. /* Save in "shadowed" list */
  2194. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2195. cur->flg_export ? "exported " : "",
  2196. cur->varstr, cur->var_nest_level, str, local_lvl
  2197. );
  2198. cur->next = *G.shadowed_vars_pp;
  2199. *G.shadowed_vars_pp = cur;
  2200. } else {
  2201. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2202. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2203. cur->flg_export ? "exported " : "",
  2204. cur->varstr, cur->var_nest_level, str, local_lvl
  2205. );
  2206. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2207. free_me = cur->varstr; /* then free it later */
  2208. free(cur);
  2209. }
  2210. break;
  2211. }
  2212. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2213. debug_printf_env("assignement '%s' does not change anything\n", str);
  2214. free_and_exp:
  2215. free(str);
  2216. goto exp;
  2217. }
  2218. /* Replace the value in the found "struct variable" */
  2219. if (cur->max_len != 0) {
  2220. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2221. /* This one is from startup env, reuse space */
  2222. debug_printf_env("reusing startup env for '%s'\n", str);
  2223. strcpy(cur->varstr, str);
  2224. goto free_and_exp;
  2225. }
  2226. /* Can't reuse */
  2227. cur->max_len = 0;
  2228. goto set_str_and_exp;
  2229. }
  2230. /* max_len == 0 signifies "malloced" var, which we can
  2231. * (and have to) free. But we can't free(cur->varstr) here:
  2232. * if cur->flg_export is 1, it is in the environment.
  2233. * We should either unsetenv+free, or wait until putenv,
  2234. * then putenv(new)+free(old).
  2235. */
  2236. free_me = cur->varstr;
  2237. goto set_str_and_exp;
  2238. }
  2239. /* Not found or shadowed - create new variable struct */
  2240. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2241. cur = xzalloc(sizeof(*cur));
  2242. cur->var_nest_level = local_lvl;
  2243. cur->next = *cur_pp;
  2244. *cur_pp = cur;
  2245. set_str_and_exp:
  2246. cur->varstr = str;
  2247. exp:
  2248. #if !BB_MMU || ENABLE_HUSH_READONLY
  2249. if (flags & SETFLAG_MAKE_RO) {
  2250. cur->flg_read_only = 1;
  2251. }
  2252. #endif
  2253. if (flags & SETFLAG_EXPORT)
  2254. cur->flg_export = 1;
  2255. retval = 0;
  2256. if (cur->flg_export) {
  2257. if (flags & SETFLAG_UNEXPORT) {
  2258. cur->flg_export = 0;
  2259. /* unsetenv was already done */
  2260. } else {
  2261. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2262. retval = putenv(cur->varstr);
  2263. /* fall through to "free(free_me)" -
  2264. * only now we can free old exported malloced string
  2265. */
  2266. }
  2267. }
  2268. free(free_me);
  2269. handle_changed_special_names(cur->varstr, name_len - 1);
  2270. return retval;
  2271. }
  2272. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2273. {
  2274. char *var = xasprintf("%s=%s", name, val);
  2275. set_local_var(var, /*flag:*/ 0);
  2276. }
  2277. /* Used at startup and after each cd */
  2278. static void set_pwd_var(unsigned flag)
  2279. {
  2280. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2281. }
  2282. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2283. static int unset_local_var_len(const char *name, int name_len)
  2284. {
  2285. struct variable *cur;
  2286. struct variable **cur_pp;
  2287. cur_pp = &G.top_var;
  2288. while ((cur = *cur_pp) != NULL) {
  2289. if (strncmp(cur->varstr, name, name_len) == 0
  2290. && cur->varstr[name_len] == '='
  2291. ) {
  2292. if (cur->flg_read_only) {
  2293. bb_error_msg("%s: readonly variable", name);
  2294. return EXIT_FAILURE;
  2295. }
  2296. *cur_pp = cur->next;
  2297. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2298. bb_unsetenv(cur->varstr);
  2299. if (!cur->max_len)
  2300. free(cur->varstr);
  2301. free(cur);
  2302. break;
  2303. }
  2304. cur_pp = &cur->next;
  2305. }
  2306. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2307. handle_changed_special_names(name, name_len);
  2308. return EXIT_SUCCESS;
  2309. }
  2310. static int unset_local_var(const char *name)
  2311. {
  2312. return unset_local_var_len(name, strlen(name));
  2313. }
  2314. #endif
  2315. /*
  2316. * Helpers for "var1=val1 var2=val2 cmd" feature
  2317. */
  2318. static void add_vars(struct variable *var)
  2319. {
  2320. struct variable *next;
  2321. while (var) {
  2322. next = var->next;
  2323. var->next = G.top_var;
  2324. G.top_var = var;
  2325. if (var->flg_export) {
  2326. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2327. putenv(var->varstr);
  2328. } else {
  2329. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2330. }
  2331. var = next;
  2332. }
  2333. }
  2334. /* We put strings[i] into variable table and possibly putenv them.
  2335. * If variable is read only, we can free the strings[i]
  2336. * which attempts to overwrite it.
  2337. * The strings[] vector itself is freed.
  2338. */
  2339. static void set_vars_and_save_old(char **strings)
  2340. {
  2341. char **s;
  2342. if (!strings)
  2343. return;
  2344. s = strings;
  2345. while (*s) {
  2346. struct variable *var_p;
  2347. struct variable **var_pp;
  2348. char *eq;
  2349. eq = strchr(*s, '=');
  2350. if (HUSH_DEBUG && !eq)
  2351. bb_simple_error_msg_and_die("BUG in varexp4");
  2352. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2353. if (var_pp) {
  2354. var_p = *var_pp;
  2355. if (var_p->flg_read_only) {
  2356. char **p;
  2357. bb_error_msg("%s: readonly variable", *s);
  2358. /*
  2359. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2360. * If VAR is readonly, leaving it in the list
  2361. * after asssignment error (msg above)
  2362. * causes doubled error message later, on unset.
  2363. */
  2364. debug_printf_env("removing/freeing '%s' element\n", *s);
  2365. free(*s);
  2366. p = s;
  2367. do { *p = p[1]; p++; } while (*p);
  2368. goto next;
  2369. }
  2370. /* below, set_local_var() with nest level will
  2371. * "shadow" (remove) this variable from
  2372. * global linked list.
  2373. */
  2374. }
  2375. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2376. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2377. s++;
  2378. next: ;
  2379. }
  2380. free(strings);
  2381. }
  2382. /*
  2383. * Unicode helper
  2384. */
  2385. static void reinit_unicode_for_hush(void)
  2386. {
  2387. /* Unicode support should be activated even if LANG is set
  2388. * _during_ shell execution, not only if it was set when
  2389. * shell was started. Therefore, re-check LANG every time:
  2390. */
  2391. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2392. || ENABLE_UNICODE_USING_LOCALE
  2393. ) {
  2394. const char *s = get_local_var_value("LC_ALL");
  2395. if (!s) s = get_local_var_value("LC_CTYPE");
  2396. if (!s) s = get_local_var_value("LANG");
  2397. reinit_unicode(s);
  2398. }
  2399. }
  2400. /*
  2401. * in_str support (strings, and "strings" read from files).
  2402. */
  2403. #if ENABLE_HUSH_INTERACTIVE
  2404. /* To test correct lineedit/interactive behavior, type from command line:
  2405. * echo $P\
  2406. * \
  2407. * AT\
  2408. * H\
  2409. * \
  2410. * It exercises a lot of corner cases.
  2411. */
  2412. static const char *setup_prompt_string(void)
  2413. {
  2414. const char *prompt_str;
  2415. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2416. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2417. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2418. if (!prompt_str)
  2419. prompt_str = "";
  2420. # else
  2421. prompt_str = "> "; /* if PS2, else... */
  2422. if (G.promptmode == 0) { /* PS1 */
  2423. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2424. free(G.PS1);
  2425. /* bash uses $PWD value, even if it is set by user.
  2426. * It uses current dir only if PWD is unset.
  2427. * We always use current dir. */
  2428. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2429. }
  2430. # endif
  2431. debug_printf("prompt_str '%s'\n", prompt_str);
  2432. return prompt_str;
  2433. }
  2434. static int get_user_input(struct in_str *i)
  2435. {
  2436. int r;
  2437. const char *prompt_str;
  2438. prompt_str = setup_prompt_string();
  2439. # if ENABLE_FEATURE_EDITING
  2440. for (;;) {
  2441. reinit_unicode_for_hush();
  2442. if (G.flag_SIGINT) {
  2443. /* There was ^C'ed, make it look prettier: */
  2444. bb_putchar('\n');
  2445. G.flag_SIGINT = 0;
  2446. }
  2447. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2448. * only after <Enter>. (^C works immediately) */
  2449. r = read_line_input(G.line_input_state, prompt_str,
  2450. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2451. );
  2452. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2453. if (r == 0)
  2454. raise(SIGINT);
  2455. check_and_run_traps();
  2456. if (r != 0 && !G.flag_SIGINT)
  2457. break;
  2458. /* ^C or SIGINT: repeat */
  2459. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2460. write(STDOUT_FILENO, "^C", 2);
  2461. G.last_exitcode = 128 + SIGINT;
  2462. }
  2463. if (r < 0) {
  2464. /* EOF/error detected */
  2465. i->p = NULL;
  2466. i->peek_buf[0] = r = EOF;
  2467. return r;
  2468. }
  2469. i->p = G.user_input_buf;
  2470. return (unsigned char)*i->p++;
  2471. # else
  2472. for (;;) {
  2473. G.flag_SIGINT = 0;
  2474. if (i->last_char == '\0' || i->last_char == '\n') {
  2475. /* Why check_and_run_traps here? Try this interactively:
  2476. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2477. * $ <[enter], repeatedly...>
  2478. * Without check_and_run_traps, handler never runs.
  2479. */
  2480. check_and_run_traps();
  2481. fputs(prompt_str, stdout);
  2482. }
  2483. fflush_all();
  2484. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2485. r = hfgetc(i->file);
  2486. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2487. * no ^C masking happens during fgetc, no special code for ^C:
  2488. * it generates SIGINT as usual.
  2489. */
  2490. check_and_run_traps();
  2491. if (G.flag_SIGINT)
  2492. G.last_exitcode = 128 + SIGINT;
  2493. if (r != '\0')
  2494. break;
  2495. }
  2496. return r;
  2497. # endif
  2498. }
  2499. /* This is the magic location that prints prompts
  2500. * and gets data back from the user */
  2501. static int fgetc_interactive(struct in_str *i)
  2502. {
  2503. int ch;
  2504. /* If it's interactive stdin, get new line. */
  2505. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2506. /* Returns first char (or EOF), the rest is in i->p[] */
  2507. ch = get_user_input(i);
  2508. G.promptmode = 1; /* PS2 */
  2509. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2510. } else {
  2511. /* Not stdin: script file, sourced file, etc */
  2512. do ch = hfgetc(i->file); while (ch == '\0');
  2513. }
  2514. return ch;
  2515. }
  2516. #else
  2517. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2518. {
  2519. int ch;
  2520. do ch = hfgetc(i->file); while (ch == '\0');
  2521. return ch;
  2522. }
  2523. #endif /* INTERACTIVE */
  2524. static int i_getch(struct in_str *i)
  2525. {
  2526. int ch;
  2527. if (!i->file) {
  2528. /* string-based in_str */
  2529. ch = (unsigned char)*i->p;
  2530. if (ch != '\0') {
  2531. i->p++;
  2532. i->last_char = ch;
  2533. return ch;
  2534. }
  2535. return EOF;
  2536. }
  2537. /* FILE-based in_str */
  2538. #if ENABLE_FEATURE_EDITING
  2539. /* This can be stdin, check line editing char[] buffer */
  2540. if (i->p && *i->p != '\0') {
  2541. ch = (unsigned char)*i->p++;
  2542. goto out;
  2543. }
  2544. #endif
  2545. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2546. ch = i->peek_buf[0];
  2547. if (ch != 0) {
  2548. int ch2 = i->peek_buf[1];
  2549. i->peek_buf[0] = ch2;
  2550. if (ch2 == 0) /* very likely, avoid redundant write */
  2551. goto out;
  2552. i->peek_buf[1] = 0;
  2553. goto out;
  2554. }
  2555. ch = fgetc_interactive(i);
  2556. out:
  2557. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2558. i->last_char = ch;
  2559. #if ENABLE_HUSH_LINENO_VAR
  2560. if (ch == '\n') {
  2561. G.parse_lineno++;
  2562. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2563. }
  2564. #endif
  2565. return ch;
  2566. }
  2567. static int i_peek(struct in_str *i)
  2568. {
  2569. int ch;
  2570. if (!i->file) {
  2571. /* string-based in_str */
  2572. /* Doesn't report EOF on NUL. None of the callers care. */
  2573. return (unsigned char)*i->p;
  2574. }
  2575. /* FILE-based in_str */
  2576. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2577. /* This can be stdin, check line editing char[] buffer */
  2578. if (i->p && *i->p != '\0')
  2579. return (unsigned char)*i->p;
  2580. #endif
  2581. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2582. ch = i->peek_buf[0];
  2583. if (ch != 0)
  2584. return ch;
  2585. /* Need to get a new char */
  2586. ch = fgetc_interactive(i);
  2587. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2588. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2589. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2590. if (i->p) {
  2591. i->p -= 1;
  2592. return ch;
  2593. }
  2594. #endif
  2595. i->peek_buf[0] = ch;
  2596. /*i->peek_buf[1] = 0; - already is */
  2597. return ch;
  2598. }
  2599. /* Only ever called if i_peek() was called, and did not return EOF.
  2600. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2601. * not end-of-line. Therefore we never need to read a new editing line here.
  2602. */
  2603. static int i_peek2(struct in_str *i)
  2604. {
  2605. int ch;
  2606. /* There are two cases when i->p[] buffer exists.
  2607. * (1) it's a string in_str.
  2608. * (2) It's a file, and we have a saved line editing buffer.
  2609. * In both cases, we know that i->p[0] exists and not NUL, and
  2610. * the peek2 result is in i->p[1].
  2611. */
  2612. if (i->p)
  2613. return (unsigned char)i->p[1];
  2614. /* Now we know it is a file-based in_str. */
  2615. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2616. /* Is there 2nd char? */
  2617. ch = i->peek_buf[1];
  2618. if (ch == 0) {
  2619. /* We did not read it yet, get it now */
  2620. do ch = hfgetc(i->file); while (ch == '\0');
  2621. i->peek_buf[1] = ch;
  2622. }
  2623. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2624. return ch;
  2625. }
  2626. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2627. {
  2628. for (;;) {
  2629. int ch, ch2;
  2630. ch = i_getch(input);
  2631. if (ch != '\\')
  2632. return ch;
  2633. ch2 = i_peek(input);
  2634. if (ch2 != '\n')
  2635. return ch;
  2636. /* backslash+newline, skip it */
  2637. i_getch(input);
  2638. }
  2639. }
  2640. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2641. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2642. */
  2643. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2644. {
  2645. for (;;) {
  2646. int ch, ch2;
  2647. ch = i_peek(input);
  2648. if (ch != '\\')
  2649. return ch;
  2650. ch2 = i_peek2(input);
  2651. if (ch2 != '\n')
  2652. return ch;
  2653. /* backslash+newline, skip it */
  2654. i_getch(input);
  2655. i_getch(input);
  2656. }
  2657. }
  2658. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2659. {
  2660. memset(i, 0, sizeof(*i));
  2661. i->file = fp;
  2662. /* i->p = NULL; */
  2663. }
  2664. static void setup_string_in_str(struct in_str *i, const char *s)
  2665. {
  2666. memset(i, 0, sizeof(*i));
  2667. /*i->file = NULL */;
  2668. i->p = s;
  2669. }
  2670. /*
  2671. * o_string support
  2672. */
  2673. #define B_CHUNK (32 * sizeof(char*))
  2674. static void o_reset_to_empty_unquoted(o_string *o)
  2675. {
  2676. o->length = 0;
  2677. o->has_quoted_part = 0;
  2678. if (o->data)
  2679. o->data[0] = '\0';
  2680. }
  2681. static void o_free_and_set_NULL(o_string *o)
  2682. {
  2683. free(o->data);
  2684. memset(o, 0, sizeof(*o));
  2685. }
  2686. static ALWAYS_INLINE void o_free(o_string *o)
  2687. {
  2688. free(o->data);
  2689. }
  2690. static void o_grow_by(o_string *o, int len)
  2691. {
  2692. if (o->length + len > o->maxlen) {
  2693. o->maxlen += (2 * len) | (B_CHUNK-1);
  2694. o->data = xrealloc(o->data, 1 + o->maxlen);
  2695. }
  2696. }
  2697. static void o_addchr(o_string *o, int ch)
  2698. {
  2699. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2700. if (o->length < o->maxlen) {
  2701. /* likely. avoid o_grow_by() call */
  2702. add:
  2703. o->data[o->length] = ch;
  2704. o->length++;
  2705. o->data[o->length] = '\0';
  2706. return;
  2707. }
  2708. o_grow_by(o, 1);
  2709. goto add;
  2710. }
  2711. #if 0
  2712. /* Valid only if we know o_string is not empty */
  2713. static void o_delchr(o_string *o)
  2714. {
  2715. o->length--;
  2716. o->data[o->length] = '\0';
  2717. }
  2718. #endif
  2719. static void o_addblock(o_string *o, const char *str, int len)
  2720. {
  2721. o_grow_by(o, len);
  2722. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2723. o->length += len;
  2724. }
  2725. static void o_addstr(o_string *o, const char *str)
  2726. {
  2727. o_addblock(o, str, strlen(str));
  2728. }
  2729. static void o_addstr_with_NUL(o_string *o, const char *str)
  2730. {
  2731. o_addblock(o, str, strlen(str) + 1);
  2732. }
  2733. #if !BB_MMU
  2734. static void nommu_addchr(o_string *o, int ch)
  2735. {
  2736. if (o)
  2737. o_addchr(o, ch);
  2738. }
  2739. #else
  2740. # define nommu_addchr(o, str) ((void)0)
  2741. #endif
  2742. #if ENABLE_HUSH_MODE_X
  2743. static void x_mode_addchr(int ch)
  2744. {
  2745. o_addchr(&G.x_mode_buf, ch);
  2746. }
  2747. static void x_mode_addstr(const char *str)
  2748. {
  2749. o_addstr(&G.x_mode_buf, str);
  2750. }
  2751. static void x_mode_addblock(const char *str, int len)
  2752. {
  2753. o_addblock(&G.x_mode_buf, str, len);
  2754. }
  2755. static void x_mode_prefix(void)
  2756. {
  2757. int n = G.x_mode_depth;
  2758. do x_mode_addchr('+'); while (--n >= 0);
  2759. }
  2760. static void x_mode_flush(void)
  2761. {
  2762. int len = G.x_mode_buf.length;
  2763. if (len <= 0)
  2764. return;
  2765. if (G.x_mode_fd > 0) {
  2766. G.x_mode_buf.data[len] = '\n';
  2767. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2768. }
  2769. G.x_mode_buf.length = 0;
  2770. }
  2771. #endif
  2772. /*
  2773. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2774. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2775. * Apparently, on unquoted $v bash still does globbing
  2776. * ("v='*.txt'; echo $v" prints all .txt files),
  2777. * but NOT brace expansion! Thus, there should be TWO independent
  2778. * quoting mechanisms on $v expansion side: one protects
  2779. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2780. * We have only second one.
  2781. */
  2782. #if ENABLE_HUSH_BRACE_EXPANSION
  2783. # define MAYBE_BRACES "{}"
  2784. #else
  2785. # define MAYBE_BRACES ""
  2786. #endif
  2787. /* My analysis of quoting semantics tells me that state information
  2788. * is associated with a destination, not a source.
  2789. */
  2790. static void o_addqchr(o_string *o, int ch)
  2791. {
  2792. int sz = 1;
  2793. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2794. if (found)
  2795. sz++;
  2796. o_grow_by(o, sz);
  2797. if (found) {
  2798. o->data[o->length] = '\\';
  2799. o->length++;
  2800. }
  2801. o->data[o->length] = ch;
  2802. o->length++;
  2803. o->data[o->length] = '\0';
  2804. }
  2805. static void o_addQchr(o_string *o, int ch)
  2806. {
  2807. int sz = 1;
  2808. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2809. && strchr("*?[\\" MAYBE_BRACES, ch)
  2810. ) {
  2811. sz++;
  2812. o->data[o->length] = '\\';
  2813. o->length++;
  2814. }
  2815. o_grow_by(o, sz);
  2816. o->data[o->length] = ch;
  2817. o->length++;
  2818. o->data[o->length] = '\0';
  2819. }
  2820. static void o_addqblock(o_string *o, const char *str, int len)
  2821. {
  2822. while (len) {
  2823. char ch;
  2824. int sz;
  2825. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2826. if (ordinary_cnt > len) /* paranoia */
  2827. ordinary_cnt = len;
  2828. o_addblock(o, str, ordinary_cnt);
  2829. if (ordinary_cnt == len)
  2830. return; /* NUL is already added by o_addblock */
  2831. str += ordinary_cnt;
  2832. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2833. ch = *str++;
  2834. sz = 1;
  2835. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2836. sz++;
  2837. o->data[o->length] = '\\';
  2838. o->length++;
  2839. }
  2840. o_grow_by(o, sz);
  2841. o->data[o->length] = ch;
  2842. o->length++;
  2843. }
  2844. o->data[o->length] = '\0';
  2845. }
  2846. static void o_addQblock(o_string *o, const char *str, int len)
  2847. {
  2848. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2849. o_addblock(o, str, len);
  2850. return;
  2851. }
  2852. o_addqblock(o, str, len);
  2853. }
  2854. static void o_addQstr(o_string *o, const char *str)
  2855. {
  2856. o_addQblock(o, str, strlen(str));
  2857. }
  2858. /* A special kind of o_string for $VAR and `cmd` expansion.
  2859. * It contains char* list[] at the beginning, which is grown in 16 element
  2860. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2861. * list[i] contains an INDEX (int!) into this string data.
  2862. * It means that if list[] needs to grow, data needs to be moved higher up
  2863. * but list[i]'s need not be modified.
  2864. * NB: remembering how many list[i]'s you have there is crucial.
  2865. * o_finalize_list() operation post-processes this structure - calculates
  2866. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2867. */
  2868. #if DEBUG_EXPAND || DEBUG_GLOB
  2869. static void debug_print_list(const char *prefix, o_string *o, int n)
  2870. {
  2871. char **list = (char**)o->data;
  2872. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2873. int i = 0;
  2874. indent();
  2875. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2876. prefix, list, n, string_start, o->length, o->maxlen,
  2877. !!(o->o_expflags & EXP_FLAG_GLOB),
  2878. o->has_quoted_part,
  2879. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2880. while (i < n) {
  2881. indent();
  2882. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2883. o->data + (int)(uintptr_t)list[i] + string_start,
  2884. o->data + (int)(uintptr_t)list[i] + string_start);
  2885. i++;
  2886. }
  2887. if (n) {
  2888. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2889. indent();
  2890. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2891. }
  2892. }
  2893. #else
  2894. # define debug_print_list(prefix, o, n) ((void)0)
  2895. #endif
  2896. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2897. * in list[n] so that it points past last stored byte so far.
  2898. * It returns n+1. */
  2899. static int o_save_ptr_helper(o_string *o, int n)
  2900. {
  2901. char **list = (char**)o->data;
  2902. int string_start;
  2903. int string_len;
  2904. if (!o->has_empty_slot) {
  2905. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2906. string_len = o->length - string_start;
  2907. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2908. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2909. /* list[n] points to string_start, make space for 16 more pointers */
  2910. o->maxlen += 0x10 * sizeof(list[0]);
  2911. o->data = xrealloc(o->data, o->maxlen + 1);
  2912. list = (char**)o->data;
  2913. memmove(list + n + 0x10, list + n, string_len);
  2914. /*
  2915. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2916. * check. (grep for -prev-ifs-check-).
  2917. * Ensure that argv[-1][last] is not garbage
  2918. * but zero bytes, to save index check there.
  2919. */
  2920. list[n + 0x10 - 1] = 0;
  2921. o->length += 0x10 * sizeof(list[0]);
  2922. } else {
  2923. debug_printf_list("list[%d]=%d string_start=%d\n",
  2924. n, string_len, string_start);
  2925. }
  2926. } else {
  2927. /* We have empty slot at list[n], reuse without growth */
  2928. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2929. string_len = o->length - string_start;
  2930. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2931. n, string_len, string_start);
  2932. o->has_empty_slot = 0;
  2933. }
  2934. o->has_quoted_part = 0;
  2935. list[n] = (char*)(uintptr_t)string_len;
  2936. return n + 1;
  2937. }
  2938. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2939. static int o_get_last_ptr(o_string *o, int n)
  2940. {
  2941. char **list = (char**)o->data;
  2942. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2943. return ((int)(uintptr_t)list[n-1]) + string_start;
  2944. }
  2945. /*
  2946. * Globbing routines.
  2947. *
  2948. * Most words in commands need to be globbed, even ones which are
  2949. * (single or double) quoted. This stems from the possiblity of
  2950. * constructs like "abc"* and 'abc'* - these should be globbed.
  2951. * Having a different code path for fully-quoted strings ("abc",
  2952. * 'abc') would only help performance-wise, but we still need
  2953. * code for partially-quoted strings.
  2954. *
  2955. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2956. * the logic can't be "shell-syntax argument is first transformed
  2957. * to a string, then globbed, and if globbing does not match anything,
  2958. * it is used verbatim". Here are two examples where it fails:
  2959. *
  2960. * echo 'b\*'?
  2961. *
  2962. * The globbing can't be avoided (because of '?' at the end).
  2963. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2964. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2965. * - IOW: they "unbackslash" the glob pattern.
  2966. * Now, look at this:
  2967. *
  2968. * v='\\\*'; echo b$v?
  2969. *
  2970. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2971. * should be used as glob pattern with no changes. However, if glob
  2972. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2973. *
  2974. * ash implements this by having an encoded representation of the word
  2975. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2976. * Glob pattern is derived from it. If glob fails, the decision what result
  2977. * should be is made using that encoded representation. Not glob pattern.
  2978. */
  2979. #if ENABLE_HUSH_BRACE_EXPANSION
  2980. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2981. * first, it processes even {a} (no commas), second,
  2982. * I didn't manage to make it return strings when they don't match
  2983. * existing files. Need to re-implement it.
  2984. */
  2985. /* Helper */
  2986. static int glob_needed(const char *s)
  2987. {
  2988. while (*s) {
  2989. if (*s == '\\') {
  2990. if (!s[1])
  2991. return 0;
  2992. s += 2;
  2993. continue;
  2994. }
  2995. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2996. return 1;
  2997. s++;
  2998. }
  2999. return 0;
  3000. }
  3001. /* Return pointer to next closing brace or to comma */
  3002. static const char *next_brace_sub(const char *cp)
  3003. {
  3004. unsigned depth = 0;
  3005. cp++;
  3006. while (*cp != '\0') {
  3007. if (*cp == '\\') {
  3008. if (*++cp == '\0')
  3009. break;
  3010. cp++;
  3011. continue;
  3012. }
  3013. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3014. break;
  3015. if (*cp++ == '{')
  3016. depth++;
  3017. }
  3018. return *cp != '\0' ? cp : NULL;
  3019. }
  3020. /* Recursive brace globber. Note: may garble pattern[]. */
  3021. static int glob_brace(char *pattern, o_string *o, int n)
  3022. {
  3023. char *new_pattern_buf;
  3024. const char *begin;
  3025. const char *next;
  3026. const char *rest;
  3027. const char *p;
  3028. size_t rest_len;
  3029. debug_printf_glob("glob_brace('%s')\n", pattern);
  3030. begin = pattern;
  3031. while (1) {
  3032. if (*begin == '\0')
  3033. goto simple_glob;
  3034. if (*begin == '{') {
  3035. /* Find the first sub-pattern and at the same time
  3036. * find the rest after the closing brace */
  3037. next = next_brace_sub(begin);
  3038. if (next == NULL) {
  3039. /* An illegal expression */
  3040. goto simple_glob;
  3041. }
  3042. if (*next == '}') {
  3043. /* "{abc}" with no commas - illegal
  3044. * brace expr, disregard and skip it */
  3045. begin = next + 1;
  3046. continue;
  3047. }
  3048. break;
  3049. }
  3050. if (*begin == '\\' && begin[1] != '\0')
  3051. begin++;
  3052. begin++;
  3053. }
  3054. debug_printf_glob("begin:%s\n", begin);
  3055. debug_printf_glob("next:%s\n", next);
  3056. /* Now find the end of the whole brace expression */
  3057. rest = next;
  3058. while (*rest != '}') {
  3059. rest = next_brace_sub(rest);
  3060. if (rest == NULL) {
  3061. /* An illegal expression */
  3062. goto simple_glob;
  3063. }
  3064. debug_printf_glob("rest:%s\n", rest);
  3065. }
  3066. rest_len = strlen(++rest) + 1;
  3067. /* We are sure the brace expression is well-formed */
  3068. /* Allocate working buffer large enough for our work */
  3069. new_pattern_buf = xmalloc(strlen(pattern));
  3070. /* We have a brace expression. BEGIN points to the opening {,
  3071. * NEXT points past the terminator of the first element, and REST
  3072. * points past the final }. We will accumulate result names from
  3073. * recursive runs for each brace alternative in the buffer using
  3074. * GLOB_APPEND. */
  3075. p = begin + 1;
  3076. while (1) {
  3077. /* Construct the new glob expression */
  3078. memcpy(
  3079. mempcpy(
  3080. mempcpy(new_pattern_buf,
  3081. /* We know the prefix for all sub-patterns */
  3082. pattern, begin - pattern),
  3083. p, next - p),
  3084. rest, rest_len);
  3085. /* Note: glob_brace() may garble new_pattern_buf[].
  3086. * That's why we re-copy prefix every time (1st memcpy above).
  3087. */
  3088. n = glob_brace(new_pattern_buf, o, n);
  3089. if (*next == '}') {
  3090. /* We saw the last entry */
  3091. break;
  3092. }
  3093. p = next + 1;
  3094. next = next_brace_sub(next);
  3095. }
  3096. free(new_pattern_buf);
  3097. return n;
  3098. simple_glob:
  3099. {
  3100. int gr;
  3101. glob_t globdata;
  3102. memset(&globdata, 0, sizeof(globdata));
  3103. gr = glob(pattern, 0, NULL, &globdata);
  3104. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3105. if (gr != 0) {
  3106. if (gr == GLOB_NOMATCH) {
  3107. globfree(&globdata);
  3108. /* NB: garbles parameter */
  3109. unbackslash(pattern);
  3110. o_addstr_with_NUL(o, pattern);
  3111. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3112. return o_save_ptr_helper(o, n);
  3113. }
  3114. if (gr == GLOB_NOSPACE)
  3115. bb_die_memory_exhausted();
  3116. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3117. * but we didn't specify it. Paranoia again. */
  3118. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3119. }
  3120. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3121. char **argv = globdata.gl_pathv;
  3122. while (1) {
  3123. o_addstr_with_NUL(o, *argv);
  3124. n = o_save_ptr_helper(o, n);
  3125. argv++;
  3126. if (!*argv)
  3127. break;
  3128. }
  3129. }
  3130. globfree(&globdata);
  3131. }
  3132. return n;
  3133. }
  3134. /* Performs globbing on last list[],
  3135. * saving each result as a new list[].
  3136. */
  3137. static int perform_glob(o_string *o, int n)
  3138. {
  3139. char *pattern, *copy;
  3140. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3141. if (!o->data)
  3142. return o_save_ptr_helper(o, n);
  3143. pattern = o->data + o_get_last_ptr(o, n);
  3144. debug_printf_glob("glob pattern '%s'\n", pattern);
  3145. if (!glob_needed(pattern)) {
  3146. /* unbackslash last string in o in place, fix length */
  3147. o->length = unbackslash(pattern) - o->data;
  3148. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3149. return o_save_ptr_helper(o, n);
  3150. }
  3151. copy = xstrdup(pattern);
  3152. /* "forget" pattern in o */
  3153. o->length = pattern - o->data;
  3154. n = glob_brace(copy, o, n);
  3155. free(copy);
  3156. if (DEBUG_GLOB)
  3157. debug_print_list("perform_glob returning", o, n);
  3158. return n;
  3159. }
  3160. #else /* !HUSH_BRACE_EXPANSION */
  3161. /* Helper */
  3162. static int glob_needed(const char *s)
  3163. {
  3164. while (*s) {
  3165. if (*s == '\\') {
  3166. if (!s[1])
  3167. return 0;
  3168. s += 2;
  3169. continue;
  3170. }
  3171. if (*s == '*' || *s == '[' || *s == '?')
  3172. return 1;
  3173. s++;
  3174. }
  3175. return 0;
  3176. }
  3177. /* Performs globbing on last list[],
  3178. * saving each result as a new list[].
  3179. */
  3180. static int perform_glob(o_string *o, int n)
  3181. {
  3182. glob_t globdata;
  3183. int gr;
  3184. char *pattern;
  3185. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3186. if (!o->data)
  3187. return o_save_ptr_helper(o, n);
  3188. pattern = o->data + o_get_last_ptr(o, n);
  3189. debug_printf_glob("glob pattern '%s'\n", pattern);
  3190. if (!glob_needed(pattern)) {
  3191. literal:
  3192. /* unbackslash last string in o in place, fix length */
  3193. o->length = unbackslash(pattern) - o->data;
  3194. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3195. return o_save_ptr_helper(o, n);
  3196. }
  3197. memset(&globdata, 0, sizeof(globdata));
  3198. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3199. * If we glob "*.\*" and don't find anything, we need
  3200. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3201. * will return "*.\*"!
  3202. */
  3203. gr = glob(pattern, 0, NULL, &globdata);
  3204. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3205. if (gr != 0) {
  3206. if (gr == GLOB_NOMATCH) {
  3207. globfree(&globdata);
  3208. goto literal;
  3209. }
  3210. if (gr == GLOB_NOSPACE)
  3211. bb_die_memory_exhausted();
  3212. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3213. * but we didn't specify it. Paranoia again. */
  3214. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3215. }
  3216. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3217. char **argv = globdata.gl_pathv;
  3218. /* "forget" pattern in o */
  3219. o->length = pattern - o->data;
  3220. while (1) {
  3221. o_addstr_with_NUL(o, *argv);
  3222. n = o_save_ptr_helper(o, n);
  3223. argv++;
  3224. if (!*argv)
  3225. break;
  3226. }
  3227. }
  3228. globfree(&globdata);
  3229. if (DEBUG_GLOB)
  3230. debug_print_list("perform_glob returning", o, n);
  3231. return n;
  3232. }
  3233. #endif /* !HUSH_BRACE_EXPANSION */
  3234. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3235. * Otherwise, just finish current list[] and start new */
  3236. static int o_save_ptr(o_string *o, int n)
  3237. {
  3238. if (o->o_expflags & EXP_FLAG_GLOB) {
  3239. /* If o->has_empty_slot, list[n] was already globbed
  3240. * (if it was requested back then when it was filled)
  3241. * so don't do that again! */
  3242. if (!o->has_empty_slot)
  3243. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3244. }
  3245. return o_save_ptr_helper(o, n);
  3246. }
  3247. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3248. static char **o_finalize_list(o_string *o, int n)
  3249. {
  3250. char **list;
  3251. int string_start;
  3252. if (DEBUG_EXPAND)
  3253. debug_print_list("finalized", o, n);
  3254. debug_printf_expand("finalized n:%d\n", n);
  3255. list = (char**)o->data;
  3256. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3257. list[--n] = NULL;
  3258. while (n) {
  3259. n--;
  3260. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3261. }
  3262. return list;
  3263. }
  3264. static void free_pipe_list(struct pipe *pi);
  3265. /* Returns pi->next - next pipe in the list */
  3266. static struct pipe *free_pipe(struct pipe *pi)
  3267. {
  3268. struct pipe *next;
  3269. int i;
  3270. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3271. for (i = 0; i < pi->num_cmds; i++) {
  3272. struct command *command;
  3273. struct redir_struct *r, *rnext;
  3274. command = &pi->cmds[i];
  3275. debug_printf_clean(" command %d:\n", i);
  3276. if (command->argv) {
  3277. if (DEBUG_CLEAN) {
  3278. int a;
  3279. char **p;
  3280. for (a = 0, p = command->argv; *p; a++, p++) {
  3281. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3282. }
  3283. }
  3284. free_strings(command->argv);
  3285. //command->argv = NULL;
  3286. }
  3287. /* not "else if": on syntax error, we may have both! */
  3288. if (command->group) {
  3289. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3290. command->cmd_type);
  3291. free_pipe_list(command->group);
  3292. debug_printf_clean(" end group\n");
  3293. //command->group = NULL;
  3294. }
  3295. /* else is crucial here.
  3296. * If group != NULL, child_func is meaningless */
  3297. #if ENABLE_HUSH_FUNCTIONS
  3298. else if (command->child_func) {
  3299. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3300. command->child_func->parent_cmd = NULL;
  3301. }
  3302. #endif
  3303. #if !BB_MMU
  3304. free(command->group_as_string);
  3305. //command->group_as_string = NULL;
  3306. #endif
  3307. for (r = command->redirects; r; r = rnext) {
  3308. debug_printf_clean(" redirect %d%s",
  3309. r->rd_fd, redir_table[r->rd_type].descrip);
  3310. /* guard against the case >$FOO, where foo is unset or blank */
  3311. if (r->rd_filename) {
  3312. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3313. free(r->rd_filename);
  3314. //r->rd_filename = NULL;
  3315. }
  3316. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3317. rnext = r->next;
  3318. free(r);
  3319. }
  3320. //command->redirects = NULL;
  3321. }
  3322. free(pi->cmds); /* children are an array, they get freed all at once */
  3323. //pi->cmds = NULL;
  3324. #if ENABLE_HUSH_JOB
  3325. free(pi->cmdtext);
  3326. //pi->cmdtext = NULL;
  3327. #endif
  3328. next = pi->next;
  3329. free(pi);
  3330. return next;
  3331. }
  3332. static void free_pipe_list(struct pipe *pi)
  3333. {
  3334. while (pi) {
  3335. #if HAS_KEYWORDS
  3336. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3337. #endif
  3338. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3339. pi = free_pipe(pi);
  3340. }
  3341. }
  3342. /*** Parsing routines ***/
  3343. #ifndef debug_print_tree
  3344. static void debug_print_tree(struct pipe *pi, int lvl)
  3345. {
  3346. static const char *const PIPE[] = {
  3347. [PIPE_SEQ] = "SEQ",
  3348. [PIPE_AND] = "AND",
  3349. [PIPE_OR ] = "OR" ,
  3350. [PIPE_BG ] = "BG" ,
  3351. };
  3352. static const char *RES[] = {
  3353. [RES_NONE ] = "NONE" ,
  3354. # if ENABLE_HUSH_IF
  3355. [RES_IF ] = "IF" ,
  3356. [RES_THEN ] = "THEN" ,
  3357. [RES_ELIF ] = "ELIF" ,
  3358. [RES_ELSE ] = "ELSE" ,
  3359. [RES_FI ] = "FI" ,
  3360. # endif
  3361. # if ENABLE_HUSH_LOOPS
  3362. [RES_FOR ] = "FOR" ,
  3363. [RES_WHILE] = "WHILE",
  3364. [RES_UNTIL] = "UNTIL",
  3365. [RES_DO ] = "DO" ,
  3366. [RES_DONE ] = "DONE" ,
  3367. # endif
  3368. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3369. [RES_IN ] = "IN" ,
  3370. # endif
  3371. # if ENABLE_HUSH_CASE
  3372. [RES_CASE ] = "CASE" ,
  3373. [RES_CASE_IN ] = "CASE_IN" ,
  3374. [RES_MATCH] = "MATCH",
  3375. [RES_CASE_BODY] = "CASE_BODY",
  3376. [RES_ESAC ] = "ESAC" ,
  3377. # endif
  3378. [RES_XXXX ] = "XXXX" ,
  3379. [RES_SNTX ] = "SNTX" ,
  3380. };
  3381. static const char *const CMDTYPE[] = {
  3382. "{}",
  3383. "()",
  3384. "[noglob]",
  3385. # if ENABLE_HUSH_FUNCTIONS
  3386. "func()",
  3387. # endif
  3388. };
  3389. int pin, prn;
  3390. pin = 0;
  3391. while (pi) {
  3392. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3393. lvl*2, "",
  3394. pin,
  3395. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3396. RES[pi->res_word],
  3397. pi->followup, PIPE[pi->followup]
  3398. );
  3399. prn = 0;
  3400. while (prn < pi->num_cmds) {
  3401. struct command *command = &pi->cmds[prn];
  3402. char **argv = command->argv;
  3403. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3404. lvl*2, "", prn,
  3405. command->assignment_cnt);
  3406. #if ENABLE_HUSH_LINENO_VAR
  3407. fdprintf(2, " LINENO:%u", command->lineno);
  3408. #endif
  3409. if (command->group) {
  3410. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3411. CMDTYPE[command->cmd_type],
  3412. argv
  3413. # if !BB_MMU
  3414. , " group_as_string:", command->group_as_string
  3415. # else
  3416. , "", ""
  3417. # endif
  3418. );
  3419. debug_print_tree(command->group, lvl+1);
  3420. prn++;
  3421. continue;
  3422. }
  3423. if (argv) while (*argv) {
  3424. fdprintf(2, " '%s'", *argv);
  3425. argv++;
  3426. }
  3427. if (command->redirects)
  3428. fdprintf(2, " {redir}");
  3429. fdprintf(2, "\n");
  3430. prn++;
  3431. }
  3432. pi = pi->next;
  3433. pin++;
  3434. }
  3435. }
  3436. #endif /* debug_print_tree */
  3437. static struct pipe *new_pipe(void)
  3438. {
  3439. struct pipe *pi;
  3440. pi = xzalloc(sizeof(struct pipe));
  3441. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3442. return pi;
  3443. }
  3444. /* Command (member of a pipe) is complete, or we start a new pipe
  3445. * if ctx->command is NULL.
  3446. * No errors possible here.
  3447. */
  3448. static int done_command(struct parse_context *ctx)
  3449. {
  3450. /* The command is really already in the pipe structure, so
  3451. * advance the pipe counter and make a new, null command. */
  3452. struct pipe *pi = ctx->pipe;
  3453. struct command *command = ctx->command;
  3454. #if 0 /* Instead we emit error message at run time */
  3455. if (ctx->pending_redirect) {
  3456. /* For example, "cmd >" (no filename to redirect to) */
  3457. syntax_error("invalid redirect");
  3458. ctx->pending_redirect = NULL;
  3459. }
  3460. #endif
  3461. if (command) {
  3462. if (IS_NULL_CMD(command)) {
  3463. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3464. goto clear_and_ret;
  3465. }
  3466. pi->num_cmds++;
  3467. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3468. //debug_print_tree(ctx->list_head, 20);
  3469. } else {
  3470. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3471. }
  3472. /* Only real trickiness here is that the uncommitted
  3473. * command structure is not counted in pi->num_cmds. */
  3474. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3475. ctx->command = command = &pi->cmds[pi->num_cmds];
  3476. clear_and_ret:
  3477. memset(command, 0, sizeof(*command));
  3478. #if ENABLE_HUSH_LINENO_VAR
  3479. command->lineno = G.parse_lineno;
  3480. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3481. #endif
  3482. return pi->num_cmds; /* used only for 0/nonzero check */
  3483. }
  3484. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3485. {
  3486. int not_null;
  3487. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3488. /* Close previous command */
  3489. not_null = done_command(ctx);
  3490. #if HAS_KEYWORDS
  3491. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3492. ctx->ctx_inverted = 0;
  3493. ctx->pipe->res_word = ctx->ctx_res_w;
  3494. #endif
  3495. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3496. /* Necessary since && and || have precedence over &:
  3497. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3498. * in a backgrounded subshell.
  3499. */
  3500. struct pipe *pi;
  3501. struct command *command;
  3502. /* Is this actually this construct, all pipes end with && or ||? */
  3503. pi = ctx->list_head;
  3504. while (pi != ctx->pipe) {
  3505. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3506. goto no_conv;
  3507. pi = pi->next;
  3508. }
  3509. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3510. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3511. pi = xzalloc(sizeof(*pi));
  3512. pi->followup = PIPE_BG;
  3513. pi->num_cmds = 1;
  3514. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3515. command = &pi->cmds[0];
  3516. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3517. command->cmd_type = CMD_NORMAL;
  3518. command->group = ctx->list_head;
  3519. #if !BB_MMU
  3520. command->group_as_string = xstrndup(
  3521. ctx->as_string.data,
  3522. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3523. );
  3524. #endif
  3525. /* Replace all pipes in ctx with one newly created */
  3526. ctx->list_head = ctx->pipe = pi;
  3527. } else {
  3528. no_conv:
  3529. ctx->pipe->followup = type;
  3530. }
  3531. /* Without this check, even just <enter> on command line generates
  3532. * tree of three NOPs (!). Which is harmless but annoying.
  3533. * IOW: it is safe to do it unconditionally. */
  3534. if (not_null
  3535. #if ENABLE_HUSH_IF
  3536. || ctx->ctx_res_w == RES_FI
  3537. #endif
  3538. #if ENABLE_HUSH_LOOPS
  3539. || ctx->ctx_res_w == RES_DONE
  3540. || ctx->ctx_res_w == RES_FOR
  3541. || ctx->ctx_res_w == RES_IN
  3542. #endif
  3543. #if ENABLE_HUSH_CASE
  3544. || ctx->ctx_res_w == RES_ESAC
  3545. #endif
  3546. ) {
  3547. struct pipe *new_p;
  3548. debug_printf_parse("done_pipe: adding new pipe: "
  3549. "not_null:%d ctx->ctx_res_w:%d\n",
  3550. not_null, ctx->ctx_res_w);
  3551. new_p = new_pipe();
  3552. ctx->pipe->next = new_p;
  3553. ctx->pipe = new_p;
  3554. /* RES_THEN, RES_DO etc are "sticky" -
  3555. * they remain set for pipes inside if/while.
  3556. * This is used to control execution.
  3557. * RES_FOR and RES_IN are NOT sticky (needed to support
  3558. * cases where variable or value happens to match a keyword):
  3559. */
  3560. #if ENABLE_HUSH_LOOPS
  3561. if (ctx->ctx_res_w == RES_FOR
  3562. || ctx->ctx_res_w == RES_IN)
  3563. ctx->ctx_res_w = RES_NONE;
  3564. #endif
  3565. #if ENABLE_HUSH_CASE
  3566. if (ctx->ctx_res_w == RES_MATCH)
  3567. ctx->ctx_res_w = RES_CASE_BODY;
  3568. if (ctx->ctx_res_w == RES_CASE)
  3569. ctx->ctx_res_w = RES_CASE_IN;
  3570. #endif
  3571. ctx->command = NULL; /* trick done_command below */
  3572. /* Create the memory for command, roughly:
  3573. * ctx->pipe->cmds = new struct command;
  3574. * ctx->command = &ctx->pipe->cmds[0];
  3575. */
  3576. done_command(ctx);
  3577. //debug_print_tree(ctx->list_head, 10);
  3578. }
  3579. debug_printf_parse("done_pipe return\n");
  3580. }
  3581. static void initialize_context(struct parse_context *ctx)
  3582. {
  3583. memset(ctx, 0, sizeof(*ctx));
  3584. if (MAYBE_ASSIGNMENT != 0)
  3585. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3586. ctx->pipe = ctx->list_head = new_pipe();
  3587. /* Create the memory for command, roughly:
  3588. * ctx->pipe->cmds = new struct command;
  3589. * ctx->command = &ctx->pipe->cmds[0];
  3590. */
  3591. done_command(ctx);
  3592. }
  3593. /* If a reserved word is found and processed, parse context is modified
  3594. * and 1 is returned.
  3595. */
  3596. #if HAS_KEYWORDS
  3597. struct reserved_combo {
  3598. char literal[6];
  3599. unsigned char res;
  3600. unsigned char assignment_flag;
  3601. int flag;
  3602. };
  3603. enum {
  3604. FLAG_END = (1 << RES_NONE ),
  3605. # if ENABLE_HUSH_IF
  3606. FLAG_IF = (1 << RES_IF ),
  3607. FLAG_THEN = (1 << RES_THEN ),
  3608. FLAG_ELIF = (1 << RES_ELIF ),
  3609. FLAG_ELSE = (1 << RES_ELSE ),
  3610. FLAG_FI = (1 << RES_FI ),
  3611. # endif
  3612. # if ENABLE_HUSH_LOOPS
  3613. FLAG_FOR = (1 << RES_FOR ),
  3614. FLAG_WHILE = (1 << RES_WHILE),
  3615. FLAG_UNTIL = (1 << RES_UNTIL),
  3616. FLAG_DO = (1 << RES_DO ),
  3617. FLAG_DONE = (1 << RES_DONE ),
  3618. FLAG_IN = (1 << RES_IN ),
  3619. # endif
  3620. # if ENABLE_HUSH_CASE
  3621. FLAG_MATCH = (1 << RES_MATCH),
  3622. FLAG_ESAC = (1 << RES_ESAC ),
  3623. # endif
  3624. FLAG_START = (1 << RES_XXXX ),
  3625. };
  3626. static const struct reserved_combo* match_reserved_word(o_string *word)
  3627. {
  3628. /* Mostly a list of accepted follow-up reserved words.
  3629. * FLAG_END means we are done with the sequence, and are ready
  3630. * to turn the compound list into a command.
  3631. * FLAG_START means the word must start a new compound list.
  3632. */
  3633. static const struct reserved_combo reserved_list[] = {
  3634. # if ENABLE_HUSH_IF
  3635. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3636. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3637. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3638. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3639. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3640. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3641. # endif
  3642. # if ENABLE_HUSH_LOOPS
  3643. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3644. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3645. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3646. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3647. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3648. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3649. # endif
  3650. # if ENABLE_HUSH_CASE
  3651. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3652. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3653. # endif
  3654. };
  3655. const struct reserved_combo *r;
  3656. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3657. if (strcmp(word->data, r->literal) == 0)
  3658. return r;
  3659. }
  3660. return NULL;
  3661. }
  3662. /* Return NULL: not a keyword, else: keyword
  3663. */
  3664. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3665. {
  3666. # if ENABLE_HUSH_CASE
  3667. static const struct reserved_combo reserved_match = {
  3668. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3669. };
  3670. # endif
  3671. const struct reserved_combo *r;
  3672. if (ctx->word.has_quoted_part)
  3673. return 0;
  3674. r = match_reserved_word(&ctx->word);
  3675. if (!r)
  3676. return r; /* NULL */
  3677. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3678. # if ENABLE_HUSH_CASE
  3679. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3680. /* "case word IN ..." - IN part starts first MATCH part */
  3681. r = &reserved_match;
  3682. } else
  3683. # endif
  3684. if (r->flag == 0) { /* '!' */
  3685. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3686. syntax_error("! ! command");
  3687. ctx->ctx_res_w = RES_SNTX;
  3688. }
  3689. ctx->ctx_inverted = 1;
  3690. return r;
  3691. }
  3692. if (r->flag & FLAG_START) {
  3693. struct parse_context *old;
  3694. old = xmemdup(ctx, sizeof(*ctx));
  3695. debug_printf_parse("push stack %p\n", old);
  3696. initialize_context(ctx);
  3697. ctx->stack = old;
  3698. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3699. syntax_error_at(ctx->word.data);
  3700. ctx->ctx_res_w = RES_SNTX;
  3701. return r;
  3702. } else {
  3703. /* "{...} fi" is ok. "{...} if" is not
  3704. * Example:
  3705. * if { echo foo; } then { echo bar; } fi */
  3706. if (ctx->command->group)
  3707. done_pipe(ctx, PIPE_SEQ);
  3708. }
  3709. ctx->ctx_res_w = r->res;
  3710. ctx->old_flag = r->flag;
  3711. ctx->is_assignment = r->assignment_flag;
  3712. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3713. if (ctx->old_flag & FLAG_END) {
  3714. struct parse_context *old;
  3715. done_pipe(ctx, PIPE_SEQ);
  3716. debug_printf_parse("pop stack %p\n", ctx->stack);
  3717. old = ctx->stack;
  3718. old->command->group = ctx->list_head;
  3719. old->command->cmd_type = CMD_NORMAL;
  3720. # if !BB_MMU
  3721. /* At this point, the compound command's string is in
  3722. * ctx->as_string... except for the leading keyword!
  3723. * Consider this example: "echo a | if true; then echo a; fi"
  3724. * ctx->as_string will contain "true; then echo a; fi",
  3725. * with "if " remaining in old->as_string!
  3726. */
  3727. {
  3728. char *str;
  3729. int len = old->as_string.length;
  3730. /* Concatenate halves */
  3731. o_addstr(&old->as_string, ctx->as_string.data);
  3732. o_free(&ctx->as_string);
  3733. /* Find where leading keyword starts in first half */
  3734. str = old->as_string.data + len;
  3735. if (str > old->as_string.data)
  3736. str--; /* skip whitespace after keyword */
  3737. while (str > old->as_string.data && isalpha(str[-1]))
  3738. str--;
  3739. /* Ugh, we're done with this horrid hack */
  3740. old->command->group_as_string = xstrdup(str);
  3741. debug_printf_parse("pop, remembering as:'%s'\n",
  3742. old->command->group_as_string);
  3743. }
  3744. # endif
  3745. *ctx = *old; /* physical copy */
  3746. free(old);
  3747. }
  3748. return r;
  3749. }
  3750. #endif /* HAS_KEYWORDS */
  3751. /* Word is complete, look at it and update parsing context.
  3752. * Normal return is 0. Syntax errors return 1.
  3753. * Note: on return, word is reset, but not o_free'd!
  3754. */
  3755. static int done_word(struct parse_context *ctx)
  3756. {
  3757. struct command *command = ctx->command;
  3758. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3759. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3760. debug_printf_parse("done_word return 0: true null, ignored\n");
  3761. return 0;
  3762. }
  3763. if (ctx->pending_redirect) {
  3764. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3765. * only if run as "bash", not "sh" */
  3766. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3767. * "2.7 Redirection
  3768. * If the redirection operator is "<<" or "<<-", the word
  3769. * that follows the redirection operator shall be
  3770. * subjected to quote removal; it is unspecified whether
  3771. * any of the other expansions occur. For the other
  3772. * redirection operators, the word that follows the
  3773. * redirection operator shall be subjected to tilde
  3774. * expansion, parameter expansion, command substitution,
  3775. * arithmetic expansion, and quote removal.
  3776. * Pathname expansion shall not be performed
  3777. * on the word by a non-interactive shell; an interactive
  3778. * shell may perform it, but shall do so only when
  3779. * the expansion would result in one word."
  3780. */
  3781. //bash does not do parameter/command substitution or arithmetic expansion
  3782. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3783. // as written:
  3784. // <<EOF$t
  3785. // <<EOF$((1))
  3786. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3787. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3788. /* Cater for >\file case:
  3789. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3790. * Same with heredocs:
  3791. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3792. */
  3793. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3794. unbackslash(ctx->pending_redirect->rd_filename);
  3795. /* Is it <<"HEREDOC"? */
  3796. if (ctx->word.has_quoted_part) {
  3797. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3798. }
  3799. }
  3800. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3801. ctx->pending_redirect = NULL;
  3802. } else {
  3803. #if HAS_KEYWORDS
  3804. # if ENABLE_HUSH_CASE
  3805. if (ctx->ctx_dsemicolon
  3806. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3807. ) {
  3808. /* already done when ctx_dsemicolon was set to 1: */
  3809. /* ctx->ctx_res_w = RES_MATCH; */
  3810. ctx->ctx_dsemicolon = 0;
  3811. } else
  3812. # endif
  3813. if (!command->argv /* if it's the first word... */
  3814. # if ENABLE_HUSH_LOOPS
  3815. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3816. && ctx->ctx_res_w != RES_IN
  3817. # endif
  3818. # if ENABLE_HUSH_CASE
  3819. && ctx->ctx_res_w != RES_CASE
  3820. # endif
  3821. ) {
  3822. const struct reserved_combo *reserved;
  3823. reserved = reserved_word(ctx);
  3824. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3825. if (reserved) {
  3826. # if ENABLE_HUSH_LINENO_VAR
  3827. /* Case:
  3828. * "while ...; do
  3829. * cmd ..."
  3830. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3831. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3832. */
  3833. if (0
  3834. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3835. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3836. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3837. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3838. ) {
  3839. done_pipe(ctx, PIPE_SEQ);
  3840. }
  3841. # endif
  3842. o_reset_to_empty_unquoted(&ctx->word);
  3843. debug_printf_parse("done_word return %d\n",
  3844. (ctx->ctx_res_w == RES_SNTX));
  3845. return (ctx->ctx_res_w == RES_SNTX);
  3846. }
  3847. # if defined(CMD_SINGLEWORD_NOGLOB)
  3848. if (0
  3849. # if BASH_TEST2
  3850. || strcmp(ctx->word.data, "[[") == 0
  3851. # endif
  3852. /* In bash, local/export/readonly are special, args
  3853. * are assignments and therefore expansion of them
  3854. * should be "one-word" expansion:
  3855. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3856. * compare with:
  3857. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3858. * ls: cannot access i=a: No such file or directory
  3859. * ls: cannot access b: No such file or directory
  3860. * Note: bash 3.2.33(1) does this only if export word
  3861. * itself is not quoted:
  3862. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3863. * aaa bbb
  3864. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3865. * aaa
  3866. */
  3867. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3868. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3869. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3870. ) {
  3871. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3872. }
  3873. /* fall through */
  3874. # endif
  3875. }
  3876. #endif /* HAS_KEYWORDS */
  3877. if (command->group) {
  3878. /* "{ echo foo; } echo bar" - bad */
  3879. syntax_error_at(ctx->word.data);
  3880. debug_printf_parse("done_word return 1: syntax error, "
  3881. "groups and arglists don't mix\n");
  3882. return 1;
  3883. }
  3884. /* If this word wasn't an assignment, next ones definitely
  3885. * can't be assignments. Even if they look like ones. */
  3886. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3887. && ctx->is_assignment != WORD_IS_KEYWORD
  3888. ) {
  3889. ctx->is_assignment = NOT_ASSIGNMENT;
  3890. } else {
  3891. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3892. command->assignment_cnt++;
  3893. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3894. }
  3895. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3896. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3897. }
  3898. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3899. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3900. debug_print_strings("word appended to argv", command->argv);
  3901. }
  3902. #if ENABLE_HUSH_LOOPS
  3903. if (ctx->ctx_res_w == RES_FOR) {
  3904. if (ctx->word.has_quoted_part
  3905. || endofname(command->argv[0])[0] != '\0'
  3906. ) {
  3907. /* bash says just "not a valid identifier" */
  3908. syntax_error("not a valid identifier in for");
  3909. return 1;
  3910. }
  3911. /* Force FOR to have just one word (variable name) */
  3912. /* NB: basically, this makes hush see "for v in ..."
  3913. * syntax as if it is "for v; in ...". FOR and IN become
  3914. * two pipe structs in parse tree. */
  3915. done_pipe(ctx, PIPE_SEQ);
  3916. }
  3917. #endif
  3918. #if ENABLE_HUSH_CASE
  3919. /* Force CASE to have just one word */
  3920. if (ctx->ctx_res_w == RES_CASE) {
  3921. done_pipe(ctx, PIPE_SEQ);
  3922. }
  3923. #endif
  3924. o_reset_to_empty_unquoted(&ctx->word);
  3925. debug_printf_parse("done_word return 0\n");
  3926. return 0;
  3927. }
  3928. /* Peek ahead in the input to find out if we have a "&n" construct,
  3929. * as in "2>&1", that represents duplicating a file descriptor.
  3930. * Return:
  3931. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3932. * REDIRFD_SYNTAX_ERR if syntax error,
  3933. * REDIRFD_TO_FILE if no & was seen,
  3934. * or the number found.
  3935. */
  3936. #if BB_MMU
  3937. #define parse_redir_right_fd(as_string, input) \
  3938. parse_redir_right_fd(input)
  3939. #endif
  3940. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3941. {
  3942. int ch, d, ok;
  3943. ch = i_peek(input);
  3944. if (ch != '&')
  3945. return REDIRFD_TO_FILE;
  3946. ch = i_getch(input); /* get the & */
  3947. nommu_addchr(as_string, ch);
  3948. ch = i_peek(input);
  3949. if (ch == '-') {
  3950. ch = i_getch(input);
  3951. nommu_addchr(as_string, ch);
  3952. return REDIRFD_CLOSE;
  3953. }
  3954. d = 0;
  3955. ok = 0;
  3956. while (ch != EOF && isdigit(ch)) {
  3957. d = d*10 + (ch-'0');
  3958. ok = 1;
  3959. ch = i_getch(input);
  3960. nommu_addchr(as_string, ch);
  3961. ch = i_peek(input);
  3962. }
  3963. if (ok) return d;
  3964. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3965. bb_simple_error_msg("ambiguous redirect");
  3966. return REDIRFD_SYNTAX_ERR;
  3967. }
  3968. /* Return code is 0 normal, 1 if a syntax error is detected
  3969. */
  3970. static int parse_redirect(struct parse_context *ctx,
  3971. int fd,
  3972. redir_type style,
  3973. struct in_str *input)
  3974. {
  3975. struct command *command = ctx->command;
  3976. struct redir_struct *redir;
  3977. struct redir_struct **redirp;
  3978. int dup_num;
  3979. dup_num = REDIRFD_TO_FILE;
  3980. if (style != REDIRECT_HEREDOC) {
  3981. /* Check for a '>&1' type redirect */
  3982. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3983. if (dup_num == REDIRFD_SYNTAX_ERR)
  3984. return 1;
  3985. } else {
  3986. int ch = i_peek_and_eat_bkslash_nl(input);
  3987. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3988. if (dup_num) { /* <<-... */
  3989. ch = i_getch(input);
  3990. nommu_addchr(&ctx->as_string, ch);
  3991. ch = i_peek(input);
  3992. }
  3993. }
  3994. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3995. int ch = i_peek_and_eat_bkslash_nl(input);
  3996. if (ch == '|') {
  3997. /* >|FILE redirect ("clobbering" >).
  3998. * Since we do not support "set -o noclobber" yet,
  3999. * >| and > are the same for now. Just eat |.
  4000. */
  4001. ch = i_getch(input);
  4002. nommu_addchr(&ctx->as_string, ch);
  4003. }
  4004. }
  4005. /* Create a new redir_struct and append it to the linked list */
  4006. redirp = &command->redirects;
  4007. while ((redir = *redirp) != NULL) {
  4008. redirp = &(redir->next);
  4009. }
  4010. *redirp = redir = xzalloc(sizeof(*redir));
  4011. /* redir->next = NULL; */
  4012. /* redir->rd_filename = NULL; */
  4013. redir->rd_type = style;
  4014. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4015. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4016. redir_table[style].descrip);
  4017. redir->rd_dup = dup_num;
  4018. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4019. /* Erik had a check here that the file descriptor in question
  4020. * is legit; I postpone that to "run time"
  4021. * A "-" representation of "close me" shows up as a -3 here */
  4022. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4023. redir->rd_fd, redir->rd_dup);
  4024. } else {
  4025. #if 0 /* Instead we emit error message at run time */
  4026. if (ctx->pending_redirect) {
  4027. /* For example, "cmd > <file" */
  4028. syntax_error("invalid redirect");
  4029. }
  4030. #endif
  4031. /* Set ctx->pending_redirect, so we know what to do at the
  4032. * end of the next parsed word. */
  4033. ctx->pending_redirect = redir;
  4034. }
  4035. return 0;
  4036. }
  4037. /* If a redirect is immediately preceded by a number, that number is
  4038. * supposed to tell which file descriptor to redirect. This routine
  4039. * looks for such preceding numbers. In an ideal world this routine
  4040. * needs to handle all the following classes of redirects...
  4041. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4042. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4043. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4044. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4045. *
  4046. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4047. * "2.7 Redirection
  4048. * ... If n is quoted, the number shall not be recognized as part of
  4049. * the redirection expression. For example:
  4050. * echo \2>a
  4051. * writes the character 2 into file a"
  4052. * We are getting it right by setting ->has_quoted_part on any \<char>
  4053. *
  4054. * A -1 return means no valid number was found,
  4055. * the caller should use the appropriate default for this redirection.
  4056. */
  4057. static int redirect_opt_num(o_string *o)
  4058. {
  4059. int num;
  4060. if (o->data == NULL)
  4061. return -1;
  4062. num = bb_strtou(o->data, NULL, 10);
  4063. if (errno || num < 0)
  4064. return -1;
  4065. o_reset_to_empty_unquoted(o);
  4066. return num;
  4067. }
  4068. #if BB_MMU
  4069. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4070. fetch_till_str(input, word, skip_tabs)
  4071. #endif
  4072. static char *fetch_till_str(o_string *as_string,
  4073. struct in_str *input,
  4074. const char *word,
  4075. int heredoc_flags)
  4076. {
  4077. o_string heredoc = NULL_O_STRING;
  4078. unsigned past_EOL;
  4079. int prev = 0; /* not \ */
  4080. int ch;
  4081. /* Starting with "" is necessary for this case:
  4082. * cat <<EOF
  4083. *
  4084. * xxx
  4085. * EOF
  4086. */
  4087. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4088. goto jump_in;
  4089. while (1) {
  4090. ch = i_getch(input);
  4091. if (ch != EOF)
  4092. nommu_addchr(as_string, ch);
  4093. if (ch == '\n' || ch == EOF) {
  4094. check_heredoc_end:
  4095. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4096. /* End-of-line, and not a line continuation */
  4097. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4098. heredoc.data[past_EOL] = '\0';
  4099. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4100. return heredoc.data;
  4101. }
  4102. if (ch == '\n') {
  4103. /* This is a new line.
  4104. * Remember position and backslash-escaping status.
  4105. */
  4106. o_addchr(&heredoc, ch);
  4107. prev = ch;
  4108. jump_in:
  4109. past_EOL = heredoc.length;
  4110. /* Get 1st char of next line, possibly skipping leading tabs */
  4111. do {
  4112. ch = i_getch(input);
  4113. if (ch != EOF)
  4114. nommu_addchr(as_string, ch);
  4115. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4116. /* If this immediately ended the line,
  4117. * go back to end-of-line checks.
  4118. */
  4119. if (ch == '\n')
  4120. goto check_heredoc_end;
  4121. }
  4122. } else {
  4123. /* Backslash-line continuation in an unquoted
  4124. * heredoc. This does not need special handling
  4125. * for heredoc body (unquoted heredocs are
  4126. * expanded on "execution" and that would take
  4127. * care of this case too), but not the case
  4128. * of line continuation *in terminator*:
  4129. * cat <<EOF
  4130. * Ok1
  4131. * EO\
  4132. * F
  4133. */
  4134. heredoc.data[--heredoc.length] = '\0';
  4135. prev = 0; /* not '\' */
  4136. continue;
  4137. }
  4138. }
  4139. if (ch == EOF) {
  4140. o_free(&heredoc);
  4141. return NULL; /* error */
  4142. }
  4143. o_addchr(&heredoc, ch);
  4144. nommu_addchr(as_string, ch);
  4145. if (prev == '\\' && ch == '\\')
  4146. /* Correctly handle foo\\<eol> (not a line cont.) */
  4147. prev = 0; /* not '\' */
  4148. else
  4149. prev = ch;
  4150. }
  4151. }
  4152. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4153. * and load them all. There should be exactly heredoc_cnt of them.
  4154. */
  4155. #if BB_MMU
  4156. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4157. fetch_heredocs(pi, heredoc_cnt, input)
  4158. #endif
  4159. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4160. {
  4161. while (pi && heredoc_cnt) {
  4162. int i;
  4163. struct command *cmd = pi->cmds;
  4164. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4165. pi->num_cmds,
  4166. cmd->argv ? cmd->argv[0] : "NONE"
  4167. );
  4168. for (i = 0; i < pi->num_cmds; i++) {
  4169. struct redir_struct *redir = cmd->redirects;
  4170. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4171. i, cmd->argv ? cmd->argv[0] : "NONE");
  4172. while (redir) {
  4173. if (redir->rd_type == REDIRECT_HEREDOC) {
  4174. char *p;
  4175. redir->rd_type = REDIRECT_HEREDOC2;
  4176. /* redir->rd_dup is (ab)used to indicate <<- */
  4177. p = fetch_till_str(as_string, input,
  4178. redir->rd_filename, redir->rd_dup);
  4179. if (!p) {
  4180. syntax_error("unexpected EOF in here document");
  4181. return -1;
  4182. }
  4183. free(redir->rd_filename);
  4184. redir->rd_filename = p;
  4185. heredoc_cnt--;
  4186. }
  4187. redir = redir->next;
  4188. }
  4189. if (cmd->group) {
  4190. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4191. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4192. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4193. if (heredoc_cnt < 0)
  4194. return heredoc_cnt; /* error */
  4195. }
  4196. cmd++;
  4197. }
  4198. pi = pi->next;
  4199. }
  4200. return heredoc_cnt;
  4201. }
  4202. static int run_list(struct pipe *pi);
  4203. #if BB_MMU
  4204. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4205. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4206. #endif
  4207. static struct pipe *parse_stream(char **pstring,
  4208. int *heredoc_cnt_ptr,
  4209. struct in_str *input,
  4210. int end_trigger);
  4211. /* Returns number of heredocs not yet consumed,
  4212. * or -1 on error.
  4213. */
  4214. static int parse_group(struct parse_context *ctx,
  4215. struct in_str *input, int ch)
  4216. {
  4217. /* ctx->word contains characters seen prior to ( or {.
  4218. * Typically it's empty, but for function defs,
  4219. * it contains function name (without '()'). */
  4220. #if BB_MMU
  4221. # define as_string NULL
  4222. #else
  4223. char *as_string = NULL;
  4224. #endif
  4225. struct pipe *pipe_list;
  4226. int heredoc_cnt = 0;
  4227. int endch;
  4228. struct command *command = ctx->command;
  4229. debug_printf_parse("parse_group entered\n");
  4230. #if ENABLE_HUSH_FUNCTIONS
  4231. if (ch == '(' && !ctx->word.has_quoted_part) {
  4232. if (ctx->word.length)
  4233. if (done_word(ctx))
  4234. return -1;
  4235. if (!command->argv)
  4236. goto skip; /* (... */
  4237. if (command->argv[1]) { /* word word ... (... */
  4238. syntax_error_unexpected_ch('(');
  4239. return -1;
  4240. }
  4241. /* it is "word(..." or "word (..." */
  4242. do
  4243. ch = i_getch(input);
  4244. while (ch == ' ' || ch == '\t');
  4245. if (ch != ')') {
  4246. syntax_error_unexpected_ch(ch);
  4247. return -1;
  4248. }
  4249. nommu_addchr(&ctx->as_string, ch);
  4250. do
  4251. ch = i_getch(input);
  4252. while (ch == ' ' || ch == '\t' || ch == '\n');
  4253. if (ch != '{' && ch != '(') {
  4254. syntax_error_unexpected_ch(ch);
  4255. return -1;
  4256. }
  4257. nommu_addchr(&ctx->as_string, ch);
  4258. command->cmd_type = CMD_FUNCDEF;
  4259. goto skip;
  4260. }
  4261. #endif
  4262. #if 0 /* Prevented by caller */
  4263. if (command->argv /* word [word]{... */
  4264. || ctx->word.length /* word{... */
  4265. || ctx->word.has_quoted_part /* ""{... */
  4266. ) {
  4267. syntax_error(NULL);
  4268. debug_printf_parse("parse_group return -1: "
  4269. "syntax error, groups and arglists don't mix\n");
  4270. return -1;
  4271. }
  4272. #endif
  4273. IF_HUSH_FUNCTIONS(skip:)
  4274. endch = '}';
  4275. if (ch == '(') {
  4276. endch = ')';
  4277. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4278. command->cmd_type = CMD_SUBSHELL;
  4279. } else {
  4280. /* bash does not allow "{echo...", requires whitespace */
  4281. ch = i_peek(input);
  4282. if (ch != ' ' && ch != '\t' && ch != '\n'
  4283. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4284. ) {
  4285. syntax_error_unexpected_ch(ch);
  4286. return -1;
  4287. }
  4288. if (ch != '(') {
  4289. ch = i_getch(input);
  4290. nommu_addchr(&ctx->as_string, ch);
  4291. }
  4292. }
  4293. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4294. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4295. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4296. #if !BB_MMU
  4297. if (as_string)
  4298. o_addstr(&ctx->as_string, as_string);
  4299. #endif
  4300. /* empty ()/{} or parse error? */
  4301. if (!pipe_list || pipe_list == ERR_PTR) {
  4302. /* parse_stream already emitted error msg */
  4303. if (!BB_MMU)
  4304. free(as_string);
  4305. debug_printf_parse("parse_group return -1: "
  4306. "parse_stream returned %p\n", pipe_list);
  4307. return -1;
  4308. }
  4309. #if !BB_MMU
  4310. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4311. command->group_as_string = as_string;
  4312. debug_printf_parse("end of group, remembering as:'%s'\n",
  4313. command->group_as_string);
  4314. #endif
  4315. #if ENABLE_HUSH_FUNCTIONS
  4316. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4317. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4318. struct command *cmd2;
  4319. cmd2 = xzalloc(sizeof(*cmd2));
  4320. cmd2->cmd_type = CMD_SUBSHELL;
  4321. cmd2->group = pipe_list;
  4322. # if !BB_MMU
  4323. //UNTESTED!
  4324. cmd2->group_as_string = command->group_as_string;
  4325. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4326. # endif
  4327. pipe_list = new_pipe();
  4328. pipe_list->cmds = cmd2;
  4329. pipe_list->num_cmds = 1;
  4330. }
  4331. #endif
  4332. command->group = pipe_list;
  4333. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4334. return heredoc_cnt;
  4335. /* command remains "open", available for possible redirects */
  4336. #undef as_string
  4337. }
  4338. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4339. /* Subroutines for copying $(...) and `...` things */
  4340. /* '...' */
  4341. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4342. {
  4343. while (1) {
  4344. int ch = i_getch(input);
  4345. if (ch == EOF) {
  4346. syntax_error_unterm_ch('\'');
  4347. return 0;
  4348. }
  4349. if (ch == '\'')
  4350. return 1;
  4351. o_addchr(dest, ch);
  4352. }
  4353. }
  4354. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4355. {
  4356. while (1) {
  4357. int ch = i_getch(input);
  4358. if (ch == EOF) {
  4359. syntax_error_unterm_ch('\'');
  4360. return 0;
  4361. }
  4362. if (ch == '\'')
  4363. return 1;
  4364. o_addqchr(dest, ch);
  4365. }
  4366. }
  4367. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4368. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4369. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4370. {
  4371. while (1) {
  4372. int ch = i_getch(input);
  4373. if (ch == EOF) {
  4374. syntax_error_unterm_ch('"');
  4375. return 0;
  4376. }
  4377. if (ch == '"')
  4378. return 1;
  4379. if (ch == '\\') { /* \x. Copy both chars. */
  4380. o_addchr(dest, ch);
  4381. ch = i_getch(input);
  4382. }
  4383. o_addchr(dest, ch);
  4384. if (ch == '`') {
  4385. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4386. return 0;
  4387. o_addchr(dest, ch);
  4388. continue;
  4389. }
  4390. //if (ch == '$') ...
  4391. }
  4392. }
  4393. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4394. * \` quoting.
  4395. * "Within the backquoted style of command substitution, backslash
  4396. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4397. * The search for the matching backquote shall be satisfied by the first
  4398. * backquote found without a preceding backslash; during this search,
  4399. * if a non-escaped backquote is encountered within a shell comment,
  4400. * a here-document, an embedded command substitution of the $(command)
  4401. * form, or a quoted string, undefined results occur. A single-quoted
  4402. * or double-quoted string that begins, but does not end, within the
  4403. * "`...`" sequence produces undefined results."
  4404. * Example Output
  4405. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4406. */
  4407. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4408. {
  4409. while (1) {
  4410. int ch = i_getch(input);
  4411. if (ch == '`')
  4412. return 1;
  4413. if (ch == '\\') {
  4414. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4415. ch = i_getch(input);
  4416. if (ch != '`'
  4417. && ch != '$'
  4418. && ch != '\\'
  4419. && (!in_dquote || ch != '"')
  4420. ) {
  4421. o_addchr(dest, '\\');
  4422. }
  4423. }
  4424. if (ch == EOF) {
  4425. syntax_error_unterm_ch('`');
  4426. return 0;
  4427. }
  4428. o_addchr(dest, ch);
  4429. }
  4430. }
  4431. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4432. * quoting and nested ()s.
  4433. * "With the $(command) style of command substitution, all characters
  4434. * following the open parenthesis to the matching closing parenthesis
  4435. * constitute the command. Any valid shell script can be used for command,
  4436. * except a script consisting solely of redirections which produces
  4437. * unspecified results."
  4438. * Example Output
  4439. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4440. * echo $(echo 'TEST)' BEST) TEST) BEST
  4441. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4442. *
  4443. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4444. * can contain arbitrary constructs, just like $(cmd).
  4445. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4446. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4447. */
  4448. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4449. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4450. {
  4451. int ch;
  4452. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4453. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4454. char end_char2 = end_ch >> 8;
  4455. # endif
  4456. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4457. #if ENABLE_HUSH_INTERACTIVE
  4458. G.promptmode = 1; /* PS2 */
  4459. #endif
  4460. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4461. while (1) {
  4462. ch = i_getch(input);
  4463. if (ch == EOF) {
  4464. syntax_error_unterm_ch(end_ch);
  4465. return 0;
  4466. }
  4467. if (ch == end_ch
  4468. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4469. || ch == end_char2
  4470. # endif
  4471. ) {
  4472. if (!dbl)
  4473. break;
  4474. /* we look for closing )) of $((EXPR)) */
  4475. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4476. i_getch(input); /* eat second ')' */
  4477. break;
  4478. }
  4479. }
  4480. o_addchr(dest, ch);
  4481. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4482. if (ch == '(' || ch == '{') {
  4483. ch = (ch == '(' ? ')' : '}');
  4484. if (!add_till_closing_bracket(dest, input, ch))
  4485. return 0;
  4486. o_addchr(dest, ch);
  4487. continue;
  4488. }
  4489. if (ch == '\'') {
  4490. if (!add_till_single_quote(dest, input))
  4491. return 0;
  4492. o_addchr(dest, ch);
  4493. continue;
  4494. }
  4495. if (ch == '"') {
  4496. if (!add_till_double_quote(dest, input))
  4497. return 0;
  4498. o_addchr(dest, ch);
  4499. continue;
  4500. }
  4501. if (ch == '`') {
  4502. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4503. return 0;
  4504. o_addchr(dest, ch);
  4505. continue;
  4506. }
  4507. if (ch == '\\') {
  4508. /* \x. Copy verbatim. Important for \(, \) */
  4509. ch = i_getch(input);
  4510. if (ch == EOF) {
  4511. syntax_error_unterm_ch(end_ch);
  4512. return 0;
  4513. }
  4514. #if 0
  4515. if (ch == '\n') {
  4516. /* "backslash+newline", ignore both */
  4517. o_delchr(dest); /* undo insertion of '\' */
  4518. continue;
  4519. }
  4520. #endif
  4521. o_addchr(dest, ch);
  4522. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4523. continue;
  4524. }
  4525. }
  4526. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4527. return ch;
  4528. }
  4529. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4530. /* Return code: 0 for OK, 1 for syntax error */
  4531. #if BB_MMU
  4532. #define parse_dollar(as_string, dest, input, quote_mask) \
  4533. parse_dollar(dest, input, quote_mask)
  4534. #define as_string NULL
  4535. #endif
  4536. static int parse_dollar(o_string *as_string,
  4537. o_string *dest,
  4538. struct in_str *input, unsigned char quote_mask)
  4539. {
  4540. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4541. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4542. if (isalpha(ch)) {
  4543. make_var:
  4544. ch = i_getch(input);
  4545. nommu_addchr(as_string, ch);
  4546. /*make_var1:*/
  4547. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4548. while (1) {
  4549. debug_printf_parse(": '%c'\n", ch);
  4550. o_addchr(dest, ch | quote_mask);
  4551. quote_mask = 0;
  4552. ch = i_peek_and_eat_bkslash_nl(input);
  4553. if (!isalnum(ch) && ch != '_') {
  4554. /* End of variable name reached */
  4555. break;
  4556. }
  4557. ch = i_getch(input);
  4558. nommu_addchr(as_string, ch);
  4559. }
  4560. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4561. } else if (isdigit(ch)) {
  4562. make_one_char_var:
  4563. ch = i_getch(input);
  4564. nommu_addchr(as_string, ch);
  4565. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4566. debug_printf_parse(": '%c'\n", ch);
  4567. o_addchr(dest, ch | quote_mask);
  4568. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4569. } else switch (ch) {
  4570. case '$': /* pid */
  4571. case '!': /* last bg pid */
  4572. case '?': /* last exit code */
  4573. case '#': /* number of args */
  4574. case '*': /* args */
  4575. case '@': /* args */
  4576. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4577. goto make_one_char_var;
  4578. case '{': {
  4579. char len_single_ch;
  4580. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4581. ch = i_getch(input); /* eat '{' */
  4582. nommu_addchr(as_string, ch);
  4583. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4584. /* It should be ${?}, or ${#var},
  4585. * or even ${?+subst} - operator acting on a special variable,
  4586. * or the beginning of variable name.
  4587. */
  4588. if (ch == EOF
  4589. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4590. ) {
  4591. bad_dollar_syntax:
  4592. syntax_error_unterm_str("${name}");
  4593. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4594. return 0;
  4595. }
  4596. nommu_addchr(as_string, ch);
  4597. len_single_ch = ch;
  4598. ch |= quote_mask;
  4599. /* It's possible to just call add_till_closing_bracket() at this point.
  4600. * However, this regresses some of our testsuite cases
  4601. * which check invalid constructs like ${%}.
  4602. * Oh well... let's check that the var name part is fine... */
  4603. while (1) {
  4604. unsigned pos;
  4605. o_addchr(dest, ch);
  4606. debug_printf_parse(": '%c'\n", ch);
  4607. ch = i_getch(input);
  4608. nommu_addchr(as_string, ch);
  4609. if (ch == '}')
  4610. break;
  4611. if (!isalnum(ch) && ch != '_') {
  4612. unsigned end_ch;
  4613. unsigned char last_ch;
  4614. /* handle parameter expansions
  4615. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4616. */
  4617. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4618. if (len_single_ch != '#'
  4619. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4620. || i_peek(input) != '}'
  4621. ) {
  4622. goto bad_dollar_syntax;
  4623. }
  4624. /* else: it's "length of C" ${#C} op,
  4625. * where C is a single char
  4626. * special var name, e.g. ${#!}.
  4627. */
  4628. }
  4629. /* Eat everything until closing '}' (or ':') */
  4630. end_ch = '}';
  4631. if (BASH_SUBSTR
  4632. && ch == ':'
  4633. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4634. ) {
  4635. /* It's ${var:N[:M]} thing */
  4636. end_ch = '}' * 0x100 + ':';
  4637. }
  4638. if (BASH_PATTERN_SUBST
  4639. && ch == '/'
  4640. ) {
  4641. /* It's ${var/[/]pattern[/repl]} thing */
  4642. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4643. i_getch(input);
  4644. nommu_addchr(as_string, '/');
  4645. ch = '\\';
  4646. }
  4647. end_ch = '}' * 0x100 + '/';
  4648. }
  4649. o_addchr(dest, ch);
  4650. /* The pattern can't be empty.
  4651. * IOW: if the first char after "${v//" is a slash,
  4652. * it does not terminate the pattern - it's the first char of the pattern:
  4653. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4654. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4655. */
  4656. if (i_peek(input) == '/') {
  4657. o_addchr(dest, i_getch(input));
  4658. }
  4659. again:
  4660. if (!BB_MMU)
  4661. pos = dest->length;
  4662. #if ENABLE_HUSH_DOLLAR_OPS
  4663. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4664. if (last_ch == 0) /* error? */
  4665. return 0;
  4666. #else
  4667. #error Simple code to only allow ${var} is not implemented
  4668. #endif
  4669. if (as_string) {
  4670. o_addstr(as_string, dest->data + pos);
  4671. o_addchr(as_string, last_ch);
  4672. }
  4673. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4674. && (end_ch & 0xff00)
  4675. ) {
  4676. /* close the first block: */
  4677. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4678. /* while parsing N from ${var:N[:M]}
  4679. * or pattern from ${var/[/]pattern[/repl]} */
  4680. if ((end_ch & 0xff) == last_ch) {
  4681. /* got ':' or '/'- parse the rest */
  4682. end_ch = '}';
  4683. goto again;
  4684. }
  4685. /* got '}' */
  4686. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4687. /* it's ${var:N} - emulate :999999999 */
  4688. o_addstr(dest, "999999999");
  4689. } /* else: it's ${var/[/]pattern} */
  4690. }
  4691. break;
  4692. }
  4693. len_single_ch = 0; /* it can't be ${#C} op */
  4694. }
  4695. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4696. break;
  4697. }
  4698. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4699. case '(': {
  4700. unsigned pos;
  4701. ch = i_getch(input);
  4702. nommu_addchr(as_string, ch);
  4703. # if ENABLE_FEATURE_SH_MATH
  4704. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4705. ch = i_getch(input);
  4706. nommu_addchr(as_string, ch);
  4707. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4708. o_addchr(dest, /*quote_mask |*/ '+');
  4709. if (!BB_MMU)
  4710. pos = dest->length;
  4711. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4712. return 0; /* error */
  4713. if (as_string) {
  4714. o_addstr(as_string, dest->data + pos);
  4715. o_addchr(as_string, ')');
  4716. o_addchr(as_string, ')');
  4717. }
  4718. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4719. break;
  4720. }
  4721. # endif
  4722. # if ENABLE_HUSH_TICK
  4723. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4724. o_addchr(dest, quote_mask | '`');
  4725. if (!BB_MMU)
  4726. pos = dest->length;
  4727. if (!add_till_closing_bracket(dest, input, ')'))
  4728. return 0; /* error */
  4729. if (as_string) {
  4730. o_addstr(as_string, dest->data + pos);
  4731. o_addchr(as_string, ')');
  4732. }
  4733. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4734. # endif
  4735. break;
  4736. }
  4737. #endif
  4738. case '_':
  4739. goto make_var;
  4740. #if 0
  4741. /* TODO: $_: */
  4742. /* $_ Shell or shell script name; or last argument of last command
  4743. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4744. * but in command's env, set to full pathname used to invoke it */
  4745. ch = i_getch(input);
  4746. nommu_addchr(as_string, ch);
  4747. ch = i_peek_and_eat_bkslash_nl(input);
  4748. if (isalnum(ch)) { /* it's $_name or $_123 */
  4749. ch = '_';
  4750. goto make_var1;
  4751. }
  4752. /* else: it's $_ */
  4753. #endif
  4754. default:
  4755. o_addQchr(dest, '$');
  4756. }
  4757. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4758. return 1;
  4759. #undef as_string
  4760. }
  4761. #if BB_MMU
  4762. #define encode_string(as_string, dest, input, dquote_end) \
  4763. encode_string(dest, input, dquote_end)
  4764. #define as_string NULL
  4765. #endif
  4766. static int encode_string(o_string *as_string,
  4767. o_string *dest,
  4768. struct in_str *input,
  4769. int dquote_end)
  4770. {
  4771. int ch;
  4772. int next;
  4773. again:
  4774. ch = i_getch(input);
  4775. if (ch != EOF)
  4776. nommu_addchr(as_string, ch);
  4777. if (ch == dquote_end) { /* may be only '"' or EOF */
  4778. debug_printf_parse("encode_string return 1 (ok)\n");
  4779. return 1;
  4780. }
  4781. /* note: can't move it above ch == dquote_end check! */
  4782. if (ch == EOF) {
  4783. syntax_error_unterm_ch('"');
  4784. return 0; /* error */
  4785. }
  4786. next = '\0';
  4787. if (ch != '\n') {
  4788. next = i_peek(input);
  4789. }
  4790. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4791. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4792. if (ch == '\\') {
  4793. if (next == EOF) {
  4794. /* Testcase: in interactive shell a file with
  4795. * echo "unterminated string\<eof>
  4796. * is sourced.
  4797. */
  4798. syntax_error_unterm_ch('"');
  4799. return 0; /* error */
  4800. }
  4801. /* bash:
  4802. * "The backslash retains its special meaning [in "..."]
  4803. * only when followed by one of the following characters:
  4804. * $, `, ", \, or <newline>. A double quote may be quoted
  4805. * within double quotes by preceding it with a backslash."
  4806. * NB: in (unquoted) heredoc, above does not apply to ",
  4807. * therefore we check for it by "next == dquote_end" cond.
  4808. */
  4809. if (next == dquote_end || strchr("$`\\\n", next)) {
  4810. ch = i_getch(input); /* eat next */
  4811. if (ch == '\n')
  4812. goto again; /* skip \<newline> */
  4813. } /* else: ch remains == '\\', and we double it below: */
  4814. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4815. nommu_addchr(as_string, ch);
  4816. goto again;
  4817. }
  4818. if (ch == '$') {
  4819. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4820. debug_printf_parse("encode_string return 0: "
  4821. "parse_dollar returned 0 (error)\n");
  4822. return 0;
  4823. }
  4824. goto again;
  4825. }
  4826. #if ENABLE_HUSH_TICK
  4827. if (ch == '`') {
  4828. //unsigned pos = dest->length;
  4829. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4830. o_addchr(dest, 0x80 | '`');
  4831. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4832. return 0; /* error */
  4833. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4834. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4835. goto again;
  4836. }
  4837. #endif
  4838. o_addQchr(dest, ch);
  4839. goto again;
  4840. #undef as_string
  4841. }
  4842. /*
  4843. * Scan input until EOF or end_trigger char.
  4844. * Return a list of pipes to execute, or NULL on EOF
  4845. * or if end_trigger character is met.
  4846. * On syntax error, exit if shell is not interactive,
  4847. * reset parsing machinery and start parsing anew,
  4848. * or return ERR_PTR.
  4849. */
  4850. static struct pipe *parse_stream(char **pstring,
  4851. int *heredoc_cnt_ptr,
  4852. struct in_str *input,
  4853. int end_trigger)
  4854. {
  4855. struct parse_context ctx;
  4856. int heredoc_cnt;
  4857. /* Single-quote triggers a bypass of the main loop until its mate is
  4858. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4859. */
  4860. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4861. end_trigger ? end_trigger : 'X');
  4862. debug_enter();
  4863. initialize_context(&ctx);
  4864. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4865. * Preventing this:
  4866. */
  4867. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4868. /* We used to separate words on $IFS here. This was wrong.
  4869. * $IFS is used only for word splitting when $var is expanded,
  4870. * here we should use blank chars as separators, not $IFS
  4871. */
  4872. heredoc_cnt = 0;
  4873. while (1) {
  4874. const char *is_blank;
  4875. const char *is_special;
  4876. int ch;
  4877. int next;
  4878. int redir_fd;
  4879. redir_type redir_style;
  4880. ch = i_getch(input);
  4881. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4882. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4883. if (ch == EOF) {
  4884. struct pipe *pi;
  4885. if (heredoc_cnt) {
  4886. syntax_error_unterm_str("here document");
  4887. goto parse_error;
  4888. }
  4889. if (end_trigger == ')') {
  4890. syntax_error_unterm_ch('(');
  4891. goto parse_error;
  4892. }
  4893. if (end_trigger == '}') {
  4894. syntax_error_unterm_ch('{');
  4895. goto parse_error;
  4896. }
  4897. if (done_word(&ctx)) {
  4898. goto parse_error;
  4899. }
  4900. o_free_and_set_NULL(&ctx.word);
  4901. done_pipe(&ctx, PIPE_SEQ);
  4902. pi = ctx.list_head;
  4903. /* If we got nothing... */
  4904. /* (this makes bare "&" cmd a no-op.
  4905. * bash says: "syntax error near unexpected token '&'") */
  4906. if (pi->num_cmds == 0
  4907. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4908. ) {
  4909. free_pipe_list(pi);
  4910. pi = NULL;
  4911. }
  4912. #if !BB_MMU
  4913. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4914. if (pstring)
  4915. *pstring = ctx.as_string.data;
  4916. else
  4917. o_free(&ctx.as_string);
  4918. #endif
  4919. // heredoc_cnt must be 0 here anyway
  4920. //if (heredoc_cnt_ptr)
  4921. // *heredoc_cnt_ptr = heredoc_cnt;
  4922. debug_leave();
  4923. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4924. debug_printf_parse("parse_stream return %p\n", pi);
  4925. return pi;
  4926. }
  4927. /* Handle "'" and "\" first, as they won't play nice with
  4928. * i_peek_and_eat_bkslash_nl() anyway:
  4929. * echo z\\
  4930. * and
  4931. * echo '\
  4932. * '
  4933. * would break.
  4934. */
  4935. if (ch == '\\') {
  4936. ch = i_getch(input);
  4937. if (ch == '\n')
  4938. continue; /* drop \<newline>, get next char */
  4939. nommu_addchr(&ctx.as_string, '\\');
  4940. o_addchr(&ctx.word, '\\');
  4941. if (ch == EOF) {
  4942. /* Testcase: eval 'echo Ok\' */
  4943. /* bash-4.3.43 was removing backslash,
  4944. * but 4.4.19 retains it, most other shells too
  4945. */
  4946. continue; /* get next char */
  4947. }
  4948. /* Example: echo Hello \2>file
  4949. * we need to know that word 2 is quoted
  4950. */
  4951. ctx.word.has_quoted_part = 1;
  4952. nommu_addchr(&ctx.as_string, ch);
  4953. o_addchr(&ctx.word, ch);
  4954. continue; /* get next char */
  4955. }
  4956. nommu_addchr(&ctx.as_string, ch);
  4957. if (ch == '\'') {
  4958. ctx.word.has_quoted_part = 1;
  4959. next = i_getch(input);
  4960. if (next == '\'' && !ctx.pending_redirect)
  4961. goto insert_empty_quoted_str_marker;
  4962. ch = next;
  4963. while (1) {
  4964. if (ch == EOF) {
  4965. syntax_error_unterm_ch('\'');
  4966. goto parse_error;
  4967. }
  4968. nommu_addchr(&ctx.as_string, ch);
  4969. if (ch == '\'')
  4970. break;
  4971. if (ch == SPECIAL_VAR_SYMBOL) {
  4972. /* Convert raw ^C to corresponding special variable reference */
  4973. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4974. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4975. }
  4976. o_addqchr(&ctx.word, ch);
  4977. ch = i_getch(input);
  4978. }
  4979. continue; /* get next char */
  4980. }
  4981. next = '\0';
  4982. if (ch != '\n')
  4983. next = i_peek_and_eat_bkslash_nl(input);
  4984. is_special = "{}<>;&|()#" /* special outside of "str" */
  4985. "$\"" IF_HUSH_TICK("`") /* always special */
  4986. SPECIAL_VAR_SYMBOL_STR;
  4987. /* Are { and } special here? */
  4988. if (ctx.command->argv /* word [word]{... - non-special */
  4989. || ctx.word.length /* word{... - non-special */
  4990. || ctx.word.has_quoted_part /* ""{... - non-special */
  4991. || (next != ';' /* }; - special */
  4992. && next != ')' /* }) - special */
  4993. && next != '(' /* {( - special */
  4994. && next != '&' /* }& and }&& ... - special */
  4995. && next != '|' /* }|| ... - special */
  4996. && !strchr(defifs, next) /* {word - non-special */
  4997. )
  4998. ) {
  4999. /* They are not special, skip "{}" */
  5000. is_special += 2;
  5001. }
  5002. is_special = strchr(is_special, ch);
  5003. is_blank = strchr(defifs, ch);
  5004. if (!is_special && !is_blank) { /* ordinary char */
  5005. ordinary_char:
  5006. o_addQchr(&ctx.word, ch);
  5007. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5008. || ctx.is_assignment == WORD_IS_KEYWORD)
  5009. && ch == '='
  5010. && endofname(ctx.word.data)[0] == '='
  5011. ) {
  5012. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5013. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5014. }
  5015. continue;
  5016. }
  5017. if (is_blank) {
  5018. #if ENABLE_HUSH_LINENO_VAR
  5019. /* Case:
  5020. * "while ...; do<whitespace><newline>
  5021. * cmd ..."
  5022. * would think that "cmd" starts in <whitespace> -
  5023. * i.e., at the previous line.
  5024. * We need to skip all whitespace before newlines.
  5025. */
  5026. while (ch != '\n') {
  5027. next = i_peek(input);
  5028. if (next != ' ' && next != '\t' && next != '\n')
  5029. break; /* next char is not ws */
  5030. ch = i_getch(input);
  5031. }
  5032. /* ch == last eaten whitespace char */
  5033. #endif
  5034. if (done_word(&ctx)) {
  5035. goto parse_error;
  5036. }
  5037. if (ch == '\n') {
  5038. /* Is this a case when newline is simply ignored?
  5039. * Some examples:
  5040. * "cmd | <newline> cmd ..."
  5041. * "case ... in <newline> word) ..."
  5042. */
  5043. if (IS_NULL_CMD(ctx.command)
  5044. && ctx.word.length == 0
  5045. && !ctx.word.has_quoted_part
  5046. && heredoc_cnt == 0
  5047. ) {
  5048. /* This newline can be ignored. But...
  5049. * Without check #1, interactive shell
  5050. * ignores even bare <newline>,
  5051. * and shows the continuation prompt:
  5052. * ps1_prompt$ <enter>
  5053. * ps2> _ <=== wrong, should be ps1
  5054. * Without check #2, "cmd & <newline>"
  5055. * is similarly mistreated.
  5056. * (BTW, this makes "cmd & cmd"
  5057. * and "cmd && cmd" non-orthogonal.
  5058. * Really, ask yourself, why
  5059. * "cmd && <newline>" doesn't start
  5060. * cmd but waits for more input?
  5061. * The only reason is that it might be
  5062. * a "cmd1 && <nl> cmd2 &" construct,
  5063. * cmd1 may need to run in BG).
  5064. */
  5065. struct pipe *pi = ctx.list_head;
  5066. if (pi->num_cmds != 0 /* check #1 */
  5067. && pi->followup != PIPE_BG /* check #2 */
  5068. ) {
  5069. continue;
  5070. }
  5071. }
  5072. /* Treat newline as a command separator. */
  5073. done_pipe(&ctx, PIPE_SEQ);
  5074. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5075. if (heredoc_cnt) {
  5076. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5077. if (heredoc_cnt != 0)
  5078. goto parse_error;
  5079. }
  5080. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5081. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5082. ch = ';';
  5083. /* note: if (is_blank) continue;
  5084. * will still trigger for us */
  5085. }
  5086. }
  5087. /* "cmd}" or "cmd }..." without semicolon or &:
  5088. * } is an ordinary char in this case, even inside { cmd; }
  5089. * Pathological example: { ""}; } should exec "}" cmd
  5090. */
  5091. if (ch == '}') {
  5092. if (ctx.word.length != 0 /* word} */
  5093. || ctx.word.has_quoted_part /* ""} */
  5094. ) {
  5095. goto ordinary_char;
  5096. }
  5097. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5098. /* Generally, there should be semicolon: "cmd; }"
  5099. * However, bash allows to omit it if "cmd" is
  5100. * a group. Examples:
  5101. * { { echo 1; } }
  5102. * {(echo 1)}
  5103. * { echo 0 >&2 | { echo 1; } }
  5104. * { while false; do :; done }
  5105. * { case a in b) ;; esac }
  5106. */
  5107. if (ctx.command->group)
  5108. goto term_group;
  5109. goto ordinary_char;
  5110. }
  5111. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5112. /* Can't be an end of {cmd}, skip the check */
  5113. goto skip_end_trigger;
  5114. /* else: } does terminate a group */
  5115. }
  5116. term_group:
  5117. if (end_trigger && end_trigger == ch
  5118. && (ch != ';' || heredoc_cnt == 0)
  5119. #if ENABLE_HUSH_CASE
  5120. && (ch != ')'
  5121. || ctx.ctx_res_w != RES_MATCH
  5122. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5123. )
  5124. #endif
  5125. ) {
  5126. if (done_word(&ctx)) {
  5127. goto parse_error;
  5128. }
  5129. done_pipe(&ctx, PIPE_SEQ);
  5130. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5131. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5132. /* Do we sit outside of any if's, loops or case's? */
  5133. if (!HAS_KEYWORDS
  5134. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5135. ) {
  5136. o_free_and_set_NULL(&ctx.word);
  5137. #if !BB_MMU
  5138. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5139. if (pstring)
  5140. *pstring = ctx.as_string.data;
  5141. else
  5142. o_free(&ctx.as_string);
  5143. #endif
  5144. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5145. /* Example: bare "{ }", "()" */
  5146. G.last_exitcode = 2; /* bash compat */
  5147. syntax_error_unexpected_ch(ch);
  5148. goto parse_error2;
  5149. }
  5150. if (heredoc_cnt_ptr)
  5151. *heredoc_cnt_ptr = heredoc_cnt;
  5152. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5153. debug_printf_parse("parse_stream return %p: "
  5154. "end_trigger char found\n",
  5155. ctx.list_head);
  5156. debug_leave();
  5157. return ctx.list_head;
  5158. }
  5159. }
  5160. if (is_blank)
  5161. continue;
  5162. /* Catch <, > before deciding whether this word is
  5163. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5164. switch (ch) {
  5165. case '>':
  5166. redir_fd = redirect_opt_num(&ctx.word);
  5167. if (done_word(&ctx)) {
  5168. goto parse_error;
  5169. }
  5170. redir_style = REDIRECT_OVERWRITE;
  5171. if (next == '>') {
  5172. redir_style = REDIRECT_APPEND;
  5173. ch = i_getch(input);
  5174. nommu_addchr(&ctx.as_string, ch);
  5175. }
  5176. #if 0
  5177. else if (next == '(') {
  5178. syntax_error(">(process) not supported");
  5179. goto parse_error;
  5180. }
  5181. #endif
  5182. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5183. goto parse_error;
  5184. continue; /* get next char */
  5185. case '<':
  5186. redir_fd = redirect_opt_num(&ctx.word);
  5187. if (done_word(&ctx)) {
  5188. goto parse_error;
  5189. }
  5190. redir_style = REDIRECT_INPUT;
  5191. if (next == '<') {
  5192. redir_style = REDIRECT_HEREDOC;
  5193. heredoc_cnt++;
  5194. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5195. ch = i_getch(input);
  5196. nommu_addchr(&ctx.as_string, ch);
  5197. } else if (next == '>') {
  5198. redir_style = REDIRECT_IO;
  5199. ch = i_getch(input);
  5200. nommu_addchr(&ctx.as_string, ch);
  5201. }
  5202. #if 0
  5203. else if (next == '(') {
  5204. syntax_error("<(process) not supported");
  5205. goto parse_error;
  5206. }
  5207. #endif
  5208. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5209. goto parse_error;
  5210. continue; /* get next char */
  5211. case '#':
  5212. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5213. /* skip "#comment" */
  5214. /* note: we do not add it to &ctx.as_string */
  5215. /* TODO: in bash:
  5216. * comment inside $() goes to the next \n, even inside quoted string (!):
  5217. * cmd "$(cmd2 #comment)" - syntax error
  5218. * cmd "`cmd2 #comment`" - ok
  5219. * We accept both (comment ends where command subst ends, in both cases).
  5220. */
  5221. while (1) {
  5222. ch = i_peek(input);
  5223. if (ch == '\n') {
  5224. nommu_addchr(&ctx.as_string, '\n');
  5225. break;
  5226. }
  5227. ch = i_getch(input);
  5228. if (ch == EOF)
  5229. break;
  5230. }
  5231. continue; /* get next char */
  5232. }
  5233. break;
  5234. }
  5235. skip_end_trigger:
  5236. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5237. /* check that we are not in word in "a=1 2>word b=1": */
  5238. && !ctx.pending_redirect
  5239. ) {
  5240. /* ch is a special char and thus this word
  5241. * cannot be an assignment */
  5242. ctx.is_assignment = NOT_ASSIGNMENT;
  5243. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5244. }
  5245. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5246. switch (ch) {
  5247. case SPECIAL_VAR_SYMBOL:
  5248. /* Convert raw ^C to corresponding special variable reference */
  5249. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5250. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5251. /* fall through */
  5252. case '#':
  5253. /* non-comment #: "echo a#b" etc */
  5254. o_addchr(&ctx.word, ch);
  5255. continue; /* get next char */
  5256. case '$':
  5257. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5258. debug_printf_parse("parse_stream parse error: "
  5259. "parse_dollar returned 0 (error)\n");
  5260. goto parse_error;
  5261. }
  5262. continue; /* get next char */
  5263. case '"':
  5264. ctx.word.has_quoted_part = 1;
  5265. if (next == '"' && !ctx.pending_redirect) {
  5266. i_getch(input); /* eat second " */
  5267. insert_empty_quoted_str_marker:
  5268. nommu_addchr(&ctx.as_string, next);
  5269. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5270. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5271. continue; /* get next char */
  5272. }
  5273. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5274. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5275. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5276. goto parse_error;
  5277. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5278. continue; /* get next char */
  5279. #if ENABLE_HUSH_TICK
  5280. case '`': {
  5281. USE_FOR_NOMMU(unsigned pos;)
  5282. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5283. o_addchr(&ctx.word, '`');
  5284. USE_FOR_NOMMU(pos = ctx.word.length;)
  5285. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5286. goto parse_error;
  5287. # if !BB_MMU
  5288. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5289. o_addchr(&ctx.as_string, '`');
  5290. # endif
  5291. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5292. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5293. continue; /* get next char */
  5294. }
  5295. #endif
  5296. case ';':
  5297. #if ENABLE_HUSH_CASE
  5298. case_semi:
  5299. #endif
  5300. if (done_word(&ctx)) {
  5301. goto parse_error;
  5302. }
  5303. done_pipe(&ctx, PIPE_SEQ);
  5304. #if ENABLE_HUSH_CASE
  5305. /* Eat multiple semicolons, detect
  5306. * whether it means something special */
  5307. while (1) {
  5308. ch = i_peek_and_eat_bkslash_nl(input);
  5309. if (ch != ';')
  5310. break;
  5311. ch = i_getch(input);
  5312. nommu_addchr(&ctx.as_string, ch);
  5313. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5314. ctx.ctx_dsemicolon = 1;
  5315. ctx.ctx_res_w = RES_MATCH;
  5316. break;
  5317. }
  5318. }
  5319. #endif
  5320. new_cmd:
  5321. /* We just finished a cmd. New one may start
  5322. * with an assignment */
  5323. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5324. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5325. continue; /* get next char */
  5326. case '&':
  5327. if (done_word(&ctx)) {
  5328. goto parse_error;
  5329. }
  5330. if (next == '&') {
  5331. ch = i_getch(input);
  5332. nommu_addchr(&ctx.as_string, ch);
  5333. done_pipe(&ctx, PIPE_AND);
  5334. } else {
  5335. done_pipe(&ctx, PIPE_BG);
  5336. }
  5337. goto new_cmd;
  5338. case '|':
  5339. if (done_word(&ctx)) {
  5340. goto parse_error;
  5341. }
  5342. #if ENABLE_HUSH_CASE
  5343. if (ctx.ctx_res_w == RES_MATCH)
  5344. break; /* we are in case's "word | word)" */
  5345. #endif
  5346. if (next == '|') { /* || */
  5347. ch = i_getch(input);
  5348. nommu_addchr(&ctx.as_string, ch);
  5349. done_pipe(&ctx, PIPE_OR);
  5350. } else {
  5351. /* we could pick up a file descriptor choice here
  5352. * with redirect_opt_num(), but bash doesn't do it.
  5353. * "echo foo 2| cat" yields "foo 2". */
  5354. done_command(&ctx);
  5355. }
  5356. goto new_cmd;
  5357. case '(':
  5358. #if ENABLE_HUSH_CASE
  5359. /* "case... in [(]word)..." - skip '(' */
  5360. if (ctx.ctx_res_w == RES_MATCH
  5361. && ctx.command->argv == NULL /* not (word|(... */
  5362. && ctx.word.length == 0 /* not word(... */
  5363. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5364. ) {
  5365. continue; /* get next char */
  5366. }
  5367. #endif
  5368. /* fall through */
  5369. case '{': {
  5370. int n = parse_group(&ctx, input, ch);
  5371. if (n < 0) {
  5372. goto parse_error;
  5373. }
  5374. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5375. heredoc_cnt += n;
  5376. goto new_cmd;
  5377. }
  5378. case ')':
  5379. #if ENABLE_HUSH_CASE
  5380. if (ctx.ctx_res_w == RES_MATCH)
  5381. goto case_semi;
  5382. #endif
  5383. case '}':
  5384. /* proper use of this character is caught by end_trigger:
  5385. * if we see {, we call parse_group(..., end_trigger='}')
  5386. * and it will match } earlier (not here). */
  5387. G.last_exitcode = 2;
  5388. syntax_error_unexpected_ch(ch);
  5389. goto parse_error2;
  5390. default:
  5391. if (HUSH_DEBUG)
  5392. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5393. }
  5394. } /* while (1) */
  5395. parse_error:
  5396. G.last_exitcode = 1;
  5397. parse_error2:
  5398. {
  5399. struct parse_context *pctx;
  5400. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5401. /* Clean up allocated tree.
  5402. * Sample for finding leaks on syntax error recovery path.
  5403. * Run it from interactive shell, watch pmap `pidof hush`.
  5404. * while if false; then false; fi; do break; fi
  5405. * Samples to catch leaks at execution:
  5406. * while if (true | { true;}); then echo ok; fi; do break; done
  5407. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5408. */
  5409. pctx = &ctx;
  5410. do {
  5411. /* Update pipe/command counts,
  5412. * otherwise freeing may miss some */
  5413. done_pipe(pctx, PIPE_SEQ);
  5414. debug_printf_clean("freeing list %p from ctx %p\n",
  5415. pctx->list_head, pctx);
  5416. debug_print_tree(pctx->list_head, 0);
  5417. free_pipe_list(pctx->list_head);
  5418. debug_printf_clean("freed list %p\n", pctx->list_head);
  5419. #if !BB_MMU
  5420. o_free(&pctx->as_string);
  5421. #endif
  5422. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5423. if (pctx != &ctx) {
  5424. free(pctx);
  5425. }
  5426. IF_HAS_KEYWORDS(pctx = p2;)
  5427. } while (HAS_KEYWORDS && pctx);
  5428. o_free(&ctx.word);
  5429. #if !BB_MMU
  5430. if (pstring)
  5431. *pstring = NULL;
  5432. #endif
  5433. debug_leave();
  5434. return ERR_PTR;
  5435. }
  5436. }
  5437. /*** Execution routines ***/
  5438. /* Expansion can recurse, need forward decls: */
  5439. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5440. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5441. expand_string_to_string(str)
  5442. #endif
  5443. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5444. #if ENABLE_HUSH_TICK
  5445. static int process_command_subs(o_string *dest, const char *s);
  5446. #endif
  5447. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5448. /* expand_strvec_to_strvec() takes a list of strings, expands
  5449. * all variable references within and returns a pointer to
  5450. * a list of expanded strings, possibly with larger number
  5451. * of strings. (Think VAR="a b"; echo $VAR).
  5452. * This new list is allocated as a single malloc block.
  5453. * NULL-terminated list of char* pointers is at the beginning of it,
  5454. * followed by strings themselves.
  5455. * Caller can deallocate entire list by single free(list). */
  5456. /* A horde of its helpers come first: */
  5457. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5458. {
  5459. while (--len >= 0) {
  5460. char c = *str++;
  5461. #if ENABLE_HUSH_BRACE_EXPANSION
  5462. if (c == '{' || c == '}') {
  5463. /* { -> \{, } -> \} */
  5464. o_addchr(o, '\\');
  5465. /* And now we want to add { or } and continue:
  5466. * o_addchr(o, c);
  5467. * continue;
  5468. * luckily, just falling through achieves this.
  5469. */
  5470. }
  5471. #endif
  5472. o_addchr(o, c);
  5473. if (c == '\\') {
  5474. /* \z -> \\\z; \<eol> -> \\<eol> */
  5475. o_addchr(o, '\\');
  5476. if (len) {
  5477. len--;
  5478. o_addchr(o, '\\');
  5479. o_addchr(o, *str++);
  5480. }
  5481. }
  5482. }
  5483. }
  5484. /* Store given string, finalizing the word and starting new one whenever
  5485. * we encounter IFS char(s). This is used for expanding variable values.
  5486. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5487. * Return in output->ended_in_ifs:
  5488. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5489. */
  5490. static int expand_on_ifs(o_string *output, int n, const char *str)
  5491. {
  5492. int last_is_ifs = 0;
  5493. while (1) {
  5494. int word_len;
  5495. if (!*str) /* EOL - do not finalize word */
  5496. break;
  5497. word_len = strcspn(str, G.ifs);
  5498. if (word_len) {
  5499. /* We have WORD_LEN leading non-IFS chars */
  5500. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5501. o_addblock(output, str, word_len);
  5502. } else {
  5503. /* Protect backslashes against globbing up :)
  5504. * Example: "v='\*'; echo b$v" prints "b\*"
  5505. * (and does not try to glob on "*")
  5506. */
  5507. o_addblock_duplicate_backslash(output, str, word_len);
  5508. /*/ Why can't we do it easier? */
  5509. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5510. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5511. }
  5512. last_is_ifs = 0;
  5513. str += word_len;
  5514. if (!*str) /* EOL - do not finalize word */
  5515. break;
  5516. }
  5517. /* We know str here points to at least one IFS char */
  5518. last_is_ifs = 1;
  5519. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5520. if (!*str) /* EOL - do not finalize word */
  5521. break;
  5522. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5523. && strchr(G.ifs, *str) /* the second check would fail */
  5524. ) {
  5525. /* This is a non-whitespace $IFS char */
  5526. /* Skip it and IFS whitespace chars, start new word */
  5527. str++;
  5528. str += strspn(str, G.ifs_whitespace);
  5529. goto new_word;
  5530. }
  5531. /* Start new word... but not always! */
  5532. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5533. if (output->has_quoted_part
  5534. /*
  5535. * Case "v=' a'; echo $v":
  5536. * here nothing precedes the space in $v expansion,
  5537. * therefore we should not finish the word
  5538. * (IOW: if there *is* word to finalize, only then do it):
  5539. * It's okay if this accesses the byte before first argv[]:
  5540. * past call to o_save_ptr() cleared it to zero byte
  5541. * (grep for -prev-ifs-check-).
  5542. */
  5543. || output->data[output->length - 1]
  5544. ) {
  5545. new_word:
  5546. o_addchr(output, '\0');
  5547. debug_print_list("expand_on_ifs", output, n);
  5548. n = o_save_ptr(output, n);
  5549. }
  5550. }
  5551. output->ended_in_ifs = last_is_ifs;
  5552. debug_print_list("expand_on_ifs[1]", output, n);
  5553. return n;
  5554. }
  5555. /* Helper to expand $((...)) and heredoc body. These act as if
  5556. * they are in double quotes, with the exception that they are not :).
  5557. * Just the rules are similar: "expand only $var and `cmd`"
  5558. *
  5559. * Returns malloced string.
  5560. * As an optimization, we return NULL if expansion is not needed.
  5561. */
  5562. static char *encode_then_expand_string(const char *str)
  5563. {
  5564. char *exp_str;
  5565. struct in_str input;
  5566. o_string dest = NULL_O_STRING;
  5567. const char *cp;
  5568. cp = str;
  5569. for (;;) {
  5570. if (!*cp) return NULL; /* string has no special chars */
  5571. if (*cp == '$') break;
  5572. if (*cp == '\\') break;
  5573. #if ENABLE_HUSH_TICK
  5574. if (*cp == '`') break;
  5575. #endif
  5576. cp++;
  5577. }
  5578. /* We need to expand. Example:
  5579. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5580. */
  5581. setup_string_in_str(&input, str);
  5582. encode_string(NULL, &dest, &input, EOF);
  5583. //TODO: error check (encode_string returns 0 on error)?
  5584. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5585. exp_str = expand_string_to_string(dest.data,
  5586. EXP_FLAG_ESC_GLOB_CHARS,
  5587. /*unbackslash:*/ 1
  5588. );
  5589. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5590. o_free(&dest);
  5591. return exp_str;
  5592. }
  5593. static const char *first_special_char_in_vararg(const char *cp)
  5594. {
  5595. for (;;) {
  5596. if (!*cp) return NULL; /* string has no special chars */
  5597. if (*cp == '$') return cp;
  5598. if (*cp == '\\') return cp;
  5599. if (*cp == '\'') return cp;
  5600. if (*cp == '"') return cp;
  5601. #if ENABLE_HUSH_TICK
  5602. if (*cp == '`') return cp;
  5603. #endif
  5604. /* dquoted "${x:+ARG}" should not glob, therefore
  5605. * '*' et al require some non-literal processing: */
  5606. if (*cp == '*') return cp;
  5607. if (*cp == '?') return cp;
  5608. if (*cp == '[') return cp;
  5609. cp++;
  5610. }
  5611. }
  5612. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5613. * These can contain single- and double-quoted strings,
  5614. * and treated as if the ARG string is initially unquoted. IOW:
  5615. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5616. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5617. * (word splitting and globbing of the ${var...} result).
  5618. */
  5619. #if !BASH_PATTERN_SUBST
  5620. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5621. encode_then_expand_vararg(str, handle_squotes)
  5622. #endif
  5623. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5624. {
  5625. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5626. const int do_unbackslash = 0;
  5627. #endif
  5628. char *exp_str;
  5629. struct in_str input;
  5630. o_string dest = NULL_O_STRING;
  5631. if (!first_special_char_in_vararg(str)) {
  5632. /* string has no special chars */
  5633. return NULL;
  5634. }
  5635. setup_string_in_str(&input, str);
  5636. dest.data = xzalloc(1); /* start as "", not as NULL */
  5637. exp_str = NULL;
  5638. for (;;) {
  5639. int ch;
  5640. ch = i_getch(&input);
  5641. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5642. __func__, ch, ch, !!dest.o_expflags);
  5643. if (!dest.o_expflags) {
  5644. if (ch == EOF)
  5645. break;
  5646. if (handle_squotes && ch == '\'') {
  5647. if (!add_till_single_quote_dquoted(&dest, &input))
  5648. goto ret; /* error */
  5649. continue;
  5650. }
  5651. }
  5652. if (ch == EOF) {
  5653. syntax_error_unterm_ch('"');
  5654. goto ret; /* error */
  5655. }
  5656. if (ch == '"') {
  5657. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5658. continue;
  5659. }
  5660. if (ch == '\\') {
  5661. ch = i_getch(&input);
  5662. if (ch == EOF) {
  5663. //example? error message? syntax_error_unterm_ch('"');
  5664. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5665. goto ret;
  5666. }
  5667. o_addqchr(&dest, ch);
  5668. continue;
  5669. }
  5670. if (ch == '$') {
  5671. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5672. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5673. goto ret;
  5674. }
  5675. continue;
  5676. }
  5677. #if ENABLE_HUSH_TICK
  5678. if (ch == '`') {
  5679. //unsigned pos = dest->length;
  5680. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5681. o_addchr(&dest, 0x80 | '`');
  5682. if (!add_till_backquote(&dest, &input,
  5683. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5684. )
  5685. ) {
  5686. goto ret; /* error */
  5687. }
  5688. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5689. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5690. continue;
  5691. }
  5692. #endif
  5693. o_addQchr(&dest, ch);
  5694. } /* for (;;) */
  5695. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5696. exp_str = expand_string_to_string(dest.data,
  5697. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5698. do_unbackslash
  5699. );
  5700. ret:
  5701. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5702. o_free(&dest);
  5703. return exp_str;
  5704. }
  5705. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5706. */
  5707. static int encode_then_append_var_plusminus(o_string *output, int n,
  5708. char *str, int dquoted)
  5709. {
  5710. struct in_str input;
  5711. o_string dest = NULL_O_STRING;
  5712. if (!first_special_char_in_vararg(str)
  5713. && '\0' == str[strcspn(str, G.ifs)]
  5714. ) {
  5715. /* string has no special chars
  5716. * && string has no $IFS chars
  5717. */
  5718. if (dquoted) {
  5719. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5720. * set -- "${notexist-}"; echo $#
  5721. */
  5722. output->has_quoted_part = 1;
  5723. }
  5724. return expand_vars_to_list(output, n, str);
  5725. }
  5726. setup_string_in_str(&input, str);
  5727. for (;;) {
  5728. int ch;
  5729. ch = i_getch(&input);
  5730. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5731. __func__, ch, ch, dest.o_expflags);
  5732. if (!dest.o_expflags) {
  5733. if (ch == EOF)
  5734. break;
  5735. if (!dquoted && strchr(G.ifs, ch)) {
  5736. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5737. * do not assume we are at the start of the word (PREFIX above).
  5738. */
  5739. if (dest.data) {
  5740. n = expand_vars_to_list(output, n, dest.data);
  5741. o_free_and_set_NULL(&dest);
  5742. o_addchr(output, '\0');
  5743. n = o_save_ptr(output, n); /* create next word */
  5744. } else
  5745. if (output->length != o_get_last_ptr(output, n)
  5746. || output->has_quoted_part
  5747. ) {
  5748. /* For these cases:
  5749. * f() { for i; do echo "|$i|"; done; }; x=x
  5750. * f a${x:+ }b # 1st condition
  5751. * |a|
  5752. * |b|
  5753. * f ""${x:+ }b # 2nd condition
  5754. * ||
  5755. * |b|
  5756. */
  5757. o_addchr(output, '\0');
  5758. n = o_save_ptr(output, n); /* create next word */
  5759. }
  5760. continue;
  5761. }
  5762. if (!dquoted && ch == '\'') {
  5763. if (!add_till_single_quote_dquoted(&dest, &input))
  5764. goto ret; /* error */
  5765. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5766. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5767. continue;
  5768. }
  5769. }
  5770. if (ch == EOF) {
  5771. syntax_error_unterm_ch('"');
  5772. goto ret; /* error */
  5773. }
  5774. if (ch == '"') {
  5775. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5776. if (dest.o_expflags) {
  5777. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5778. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5779. }
  5780. continue;
  5781. }
  5782. if (ch == '\\') {
  5783. ch = i_getch(&input);
  5784. if (ch == EOF) {
  5785. //example? error message? syntax_error_unterm_ch('"');
  5786. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5787. goto ret;
  5788. }
  5789. o_addqchr(&dest, ch);
  5790. continue;
  5791. }
  5792. if (ch == '$') {
  5793. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5794. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5795. goto ret;
  5796. }
  5797. continue;
  5798. }
  5799. #if ENABLE_HUSH_TICK
  5800. if (ch == '`') {
  5801. //unsigned pos = dest->length;
  5802. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5803. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5804. if (!add_till_backquote(&dest, &input,
  5805. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5806. )
  5807. ) {
  5808. goto ret; /* error */
  5809. }
  5810. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5811. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5812. continue;
  5813. }
  5814. #endif
  5815. if (dquoted) {
  5816. /* Always glob-protect if in dquotes:
  5817. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5818. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5819. */
  5820. o_addqchr(&dest, ch);
  5821. } else {
  5822. /* Glob-protect only if char is quoted:
  5823. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5824. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5825. */
  5826. o_addQchr(&dest, ch);
  5827. }
  5828. } /* for (;;) */
  5829. if (dest.data) {
  5830. n = expand_vars_to_list(output, n, dest.data);
  5831. }
  5832. ret:
  5833. o_free(&dest);
  5834. return n;
  5835. }
  5836. #if ENABLE_FEATURE_SH_MATH
  5837. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5838. {
  5839. arith_state_t math_state;
  5840. arith_t res;
  5841. char *exp_str;
  5842. math_state.lookupvar = get_local_var_value;
  5843. math_state.setvar = set_local_var_from_halves;
  5844. //math_state.endofname = endofname;
  5845. exp_str = encode_then_expand_string(arg);
  5846. res = arith(&math_state, exp_str ? exp_str : arg);
  5847. free(exp_str);
  5848. if (errmsg_p)
  5849. *errmsg_p = math_state.errmsg;
  5850. if (math_state.errmsg)
  5851. msg_and_die_if_script(math_state.errmsg);
  5852. return res;
  5853. }
  5854. #endif
  5855. #if BASH_PATTERN_SUBST
  5856. /* ${var/[/]pattern[/repl]} helpers */
  5857. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5858. {
  5859. while (1) {
  5860. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5861. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5862. if (end) {
  5863. *size = end - val;
  5864. return val;
  5865. }
  5866. if (*val == '\0')
  5867. return NULL;
  5868. /* Optimization: if "*pat" did not match the start of "string",
  5869. * we know that "tring", "ring" etc will not match too:
  5870. */
  5871. if (pattern[0] == '*')
  5872. return NULL;
  5873. val++;
  5874. }
  5875. }
  5876. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5877. {
  5878. char *result = NULL;
  5879. unsigned res_len = 0;
  5880. unsigned repl_len = strlen(repl);
  5881. /* Null pattern never matches, including if "var" is empty */
  5882. if (!pattern[0])
  5883. return result; /* NULL, no replaces happened */
  5884. while (1) {
  5885. int size;
  5886. char *s = strstr_pattern(val, pattern, &size);
  5887. if (!s)
  5888. break;
  5889. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5890. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5891. res_len += (s - val) + repl_len;
  5892. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5893. val = s + size;
  5894. if (exp_op == '/')
  5895. break;
  5896. }
  5897. if (*val && result) {
  5898. result = xrealloc(result, res_len + strlen(val) + 1);
  5899. strcpy(result + res_len, val);
  5900. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5901. }
  5902. debug_printf_varexp("result:'%s'\n", result);
  5903. return result;
  5904. }
  5905. #endif /* BASH_PATTERN_SUBST */
  5906. static int append_str_maybe_ifs_split(o_string *output, int n,
  5907. int first_ch, const char *val)
  5908. {
  5909. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5910. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5911. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5912. if (val && val[0])
  5913. n = expand_on_ifs(output, n, val);
  5914. } else { /* quoted "$VAR" */
  5915. output->has_quoted_part = 1;
  5916. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5917. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5918. if (val && val[0])
  5919. o_addQstr(output, val);
  5920. }
  5921. return n;
  5922. }
  5923. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5924. */
  5925. static NOINLINE int expand_one_var(o_string *output, int n,
  5926. int first_ch, char *arg, char **pp)
  5927. {
  5928. const char *val;
  5929. char *to_be_freed;
  5930. char *p;
  5931. char *var;
  5932. char exp_op;
  5933. char exp_save = exp_save; /* for compiler */
  5934. char *exp_saveptr; /* points to expansion operator */
  5935. char *exp_word = exp_word; /* for compiler */
  5936. char arg0;
  5937. val = NULL;
  5938. to_be_freed = NULL;
  5939. p = *pp;
  5940. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5941. var = arg;
  5942. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5943. arg0 = arg[0];
  5944. arg[0] = (arg0 & 0x7f);
  5945. exp_op = 0;
  5946. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5947. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5948. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5949. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5950. ) {
  5951. /* It must be length operator: ${#var} */
  5952. var++;
  5953. exp_op = 'L';
  5954. } else {
  5955. /* Maybe handle parameter expansion */
  5956. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5957. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5958. ) {
  5959. /* ${?:0}, ${#[:]%0} etc */
  5960. exp_saveptr = var + 1;
  5961. } else {
  5962. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5963. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5964. }
  5965. exp_op = exp_save = *exp_saveptr;
  5966. if (exp_op) {
  5967. exp_word = exp_saveptr + 1;
  5968. if (exp_op == ':') {
  5969. exp_op = *exp_word++;
  5970. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5971. if (BASH_SUBSTR
  5972. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5973. ) {
  5974. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5975. exp_op = ':';
  5976. exp_word--;
  5977. }
  5978. }
  5979. *exp_saveptr = '\0';
  5980. } /* else: it's not an expansion op, but bare ${var} */
  5981. }
  5982. /* Look up the variable in question */
  5983. if (isdigit(var[0])) {
  5984. /* parse_dollar should have vetted var for us */
  5985. int nn = xatoi_positive(var);
  5986. if (nn < G.global_argc)
  5987. val = G.global_argv[nn];
  5988. /* else val remains NULL: $N with too big N */
  5989. } else {
  5990. switch (var[0]) {
  5991. case '$': /* pid */
  5992. val = utoa(G.root_pid);
  5993. break;
  5994. case '!': /* bg pid */
  5995. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  5996. break;
  5997. case '?': /* exitcode */
  5998. val = utoa(G.last_exitcode);
  5999. break;
  6000. case '#': /* argc */
  6001. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6002. break;
  6003. case '-': { /* active options */
  6004. /* Check set_mode() to see what option chars we support */
  6005. char *cp;
  6006. val = cp = G.optstring_buf;
  6007. if (G.o_opt[OPT_O_ERREXIT])
  6008. *cp++ = 'e';
  6009. if (G_interactive_fd)
  6010. *cp++ = 'i';
  6011. if (G_x_mode)
  6012. *cp++ = 'x';
  6013. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6014. * commands read but are not executed,
  6015. * so $- can not execute too, 'n' is never seen in $-.
  6016. */
  6017. if (G.opt_c)
  6018. *cp++ = 'c';
  6019. if (G.opt_s)
  6020. *cp++ = 's';
  6021. *cp = '\0';
  6022. break;
  6023. }
  6024. default:
  6025. val = get_local_var_value(var);
  6026. }
  6027. }
  6028. /* Handle any expansions */
  6029. if (exp_op == 'L') {
  6030. reinit_unicode_for_hush();
  6031. debug_printf_expand("expand: length(%s)=", val);
  6032. val = utoa(val ? unicode_strlen(val) : 0);
  6033. debug_printf_expand("%s\n", val);
  6034. } else if (exp_op) {
  6035. if (exp_op == '%' || exp_op == '#') {
  6036. /* Standard-mandated substring removal ops:
  6037. * ${parameter%word} - remove smallest suffix pattern
  6038. * ${parameter%%word} - remove largest suffix pattern
  6039. * ${parameter#word} - remove smallest prefix pattern
  6040. * ${parameter##word} - remove largest prefix pattern
  6041. *
  6042. * Word is expanded to produce a glob pattern.
  6043. * Then var's value is matched to it and matching part removed.
  6044. */
  6045. //FIXME: ${x#...${...}...}
  6046. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6047. //inner ${...} may have side effects!
  6048. if (val && val[0]) {
  6049. char *t;
  6050. char *exp_exp_word;
  6051. char *loc;
  6052. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6053. if (exp_op == *exp_word) /* ## or %% */
  6054. exp_word++;
  6055. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6056. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6057. if (exp_exp_word)
  6058. exp_word = exp_exp_word;
  6059. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6060. /*
  6061. * HACK ALERT. We depend here on the fact that
  6062. * G.global_argv and results of utoa and get_local_var_value
  6063. * are actually in writable memory:
  6064. * scan_and_match momentarily stores NULs there.
  6065. */
  6066. t = (char*)val;
  6067. loc = scan_and_match(t, exp_word, scan_flags);
  6068. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6069. free(exp_exp_word);
  6070. if (loc) { /* match was found */
  6071. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6072. val = loc; /* take right part */
  6073. else /* %[%] */
  6074. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6075. }
  6076. }
  6077. }
  6078. #if BASH_PATTERN_SUBST
  6079. else if (exp_op == '/' || exp_op == '\\') {
  6080. /* It's ${var/[/]pattern[/repl]} thing.
  6081. * Note that in encoded form it has TWO parts:
  6082. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6083. * and if // is used, it is encoded as \:
  6084. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6085. */
  6086. if (val && val[0]) {
  6087. /* pattern uses non-standard expansion.
  6088. * repl should be unbackslashed and globbed
  6089. * by the usual expansion rules:
  6090. * >az >bz
  6091. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6092. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6093. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6094. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6095. * (note that a*z _pattern_ is never globbed!)
  6096. */
  6097. char *pattern, *repl, *t;
  6098. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6099. if (!pattern)
  6100. pattern = xstrdup(exp_word);
  6101. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6102. *p++ = SPECIAL_VAR_SYMBOL;
  6103. exp_word = p;
  6104. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6105. *p = '\0';
  6106. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6107. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6108. /* HACK ALERT. We depend here on the fact that
  6109. * G.global_argv and results of utoa and get_local_var_value
  6110. * are actually in writable memory:
  6111. * replace_pattern momentarily stores NULs there. */
  6112. t = (char*)val;
  6113. to_be_freed = replace_pattern(t,
  6114. pattern,
  6115. (repl ? repl : exp_word),
  6116. exp_op);
  6117. if (to_be_freed) /* at least one replace happened */
  6118. val = to_be_freed;
  6119. free(pattern);
  6120. free(repl);
  6121. } else {
  6122. /* Empty variable always gives nothing */
  6123. // "v=''; echo ${v/*/w}" prints "", not "w"
  6124. /* Just skip "replace" part */
  6125. *p++ = SPECIAL_VAR_SYMBOL;
  6126. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6127. *p = '\0';
  6128. }
  6129. }
  6130. #endif /* BASH_PATTERN_SUBST */
  6131. else if (exp_op == ':') {
  6132. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6133. /* It's ${var:N[:M]} bashism.
  6134. * Note that in encoded form it has TWO parts:
  6135. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6136. */
  6137. arith_t beg, len;
  6138. const char *errmsg;
  6139. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6140. if (errmsg)
  6141. goto arith_err;
  6142. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6143. *p++ = SPECIAL_VAR_SYMBOL;
  6144. exp_word = p;
  6145. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6146. *p = '\0';
  6147. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6148. if (errmsg)
  6149. goto arith_err;
  6150. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6151. if (beg < 0) {
  6152. /* negative beg counts from the end */
  6153. beg = (arith_t)strlen(val) + beg;
  6154. if (beg < 0) /* ${v: -999999} is "" */
  6155. beg = len = 0;
  6156. }
  6157. debug_printf_varexp("from val:'%s'\n", val);
  6158. if (len < 0) {
  6159. /* in bash, len=-n means strlen()-n */
  6160. len = (arith_t)strlen(val) - beg + len;
  6161. if (len < 0) /* bash compat */
  6162. msg_and_die_if_script("%s: substring expression < 0", var);
  6163. }
  6164. if (len <= 0 || !val || beg >= strlen(val)) {
  6165. arith_err:
  6166. val = NULL;
  6167. } else {
  6168. /* Paranoia. What if user entered 9999999999999
  6169. * which fits in arith_t but not int? */
  6170. if (len >= INT_MAX)
  6171. len = INT_MAX;
  6172. val = to_be_freed = xstrndup(val + beg, len);
  6173. }
  6174. debug_printf_varexp("val:'%s'\n", val);
  6175. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6176. msg_and_die_if_script("malformed ${%s:...}", var);
  6177. val = NULL;
  6178. #endif
  6179. } else { /* one of "-=+?" */
  6180. /* Standard-mandated substitution ops:
  6181. * ${var?word} - indicate error if unset
  6182. * If var is unset, word (or a message indicating it is unset
  6183. * if word is null) is written to standard error
  6184. * and the shell exits with a non-zero exit status.
  6185. * Otherwise, the value of var is substituted.
  6186. * ${var-word} - use default value
  6187. * If var is unset, word is substituted.
  6188. * ${var=word} - assign and use default value
  6189. * If var is unset, word is assigned to var.
  6190. * In all cases, final value of var is substituted.
  6191. * ${var+word} - use alternative value
  6192. * If var is unset, null is substituted.
  6193. * Otherwise, word is substituted.
  6194. *
  6195. * Word is subjected to tilde expansion, parameter expansion,
  6196. * command substitution, and arithmetic expansion.
  6197. * If word is not needed, it is not expanded.
  6198. *
  6199. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6200. * but also treat null var as if it is unset.
  6201. *
  6202. * Word-splitting and single quote behavior:
  6203. *
  6204. * $ f() { for i; do echo "|$i|"; done; };
  6205. *
  6206. * $ x=; f ${x:?'x y' z}
  6207. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6208. * $ x=; f "${x:?'x y' z}"
  6209. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6210. *
  6211. * $ x=; f ${x:='x y' z}
  6212. * |x|
  6213. * |y|
  6214. * |z|
  6215. * $ x=; f "${x:='x y' z}"
  6216. * |'x y' z|
  6217. *
  6218. * $ x=x; f ${x:+'x y' z}
  6219. * |x y|
  6220. * |z|
  6221. * $ x=x; f "${x:+'x y' z}"
  6222. * |'x y' z|
  6223. *
  6224. * $ x=; f ${x:-'x y' z}
  6225. * |x y|
  6226. * |z|
  6227. * $ x=; f "${x:-'x y' z}"
  6228. * |'x y' z|
  6229. */
  6230. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6231. if (exp_op == '+')
  6232. use_word = !use_word;
  6233. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6234. (exp_save == ':') ? "true" : "false", use_word);
  6235. if (use_word) {
  6236. if (exp_op == '+' || exp_op == '-') {
  6237. /* ${var+word} - use alternative value */
  6238. /* ${var-word} - use default value */
  6239. n = encode_then_append_var_plusminus(output, n, exp_word,
  6240. /*dquoted:*/ (arg0 & 0x80)
  6241. );
  6242. val = NULL;
  6243. } else {
  6244. /* ${var?word} - indicate error if unset */
  6245. /* ${var=word} - assign and use default value */
  6246. to_be_freed = encode_then_expand_vararg(exp_word,
  6247. /*handle_squotes:*/ !(arg0 & 0x80),
  6248. /*unbackslash:*/ 0
  6249. );
  6250. if (to_be_freed)
  6251. exp_word = to_be_freed;
  6252. if (exp_op == '?') {
  6253. /* mimic bash message */
  6254. msg_and_die_if_script("%s: %s",
  6255. var,
  6256. exp_word[0]
  6257. ? exp_word
  6258. : "parameter null or not set"
  6259. /* ash has more specific messages, a-la: */
  6260. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6261. );
  6262. //TODO: how interactive bash aborts expansion mid-command?
  6263. //It aborts the entire line, returns to prompt:
  6264. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6265. // bash: x: x y z
  6266. // $
  6267. // ("echo YO" is not executed, neither the f function call)
  6268. } else {
  6269. val = exp_word;
  6270. }
  6271. if (exp_op == '=') {
  6272. /* ${var=[word]} or ${var:=[word]} */
  6273. if (isdigit(var[0]) || var[0] == '#') {
  6274. /* mimic bash message */
  6275. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6276. val = NULL;
  6277. } else {
  6278. char *new_var = xasprintf("%s=%s", var, val);
  6279. set_local_var(new_var, /*flag:*/ 0);
  6280. }
  6281. }
  6282. }
  6283. }
  6284. } /* one of "-=+?" */
  6285. *exp_saveptr = exp_save;
  6286. } /* if (exp_op) */
  6287. arg[0] = arg0;
  6288. *pp = p;
  6289. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6290. free(to_be_freed);
  6291. return n;
  6292. }
  6293. /* Expand all variable references in given string, adding words to list[]
  6294. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6295. * to be filled). This routine is extremely tricky: has to deal with
  6296. * variables/parameters with whitespace, $* and $@, and constructs like
  6297. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6298. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6299. {
  6300. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6301. * expansion of right-hand side of assignment == 1-element expand.
  6302. */
  6303. char cant_be_null = 0; /* only bit 0x80 matters */
  6304. char *p;
  6305. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6306. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6307. debug_print_list("expand_vars_to_list[0]", output, n);
  6308. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6309. char first_ch;
  6310. #if ENABLE_FEATURE_SH_MATH
  6311. char arith_buf[sizeof(arith_t)*3 + 2];
  6312. #endif
  6313. if (output->ended_in_ifs) {
  6314. o_addchr(output, '\0');
  6315. n = o_save_ptr(output, n);
  6316. output->ended_in_ifs = 0;
  6317. }
  6318. o_addblock(output, arg, p - arg);
  6319. debug_print_list("expand_vars_to_list[1]", output, n);
  6320. arg = ++p;
  6321. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6322. /* Fetch special var name (if it is indeed one of them)
  6323. * and quote bit, force the bit on if singleword expansion -
  6324. * important for not getting v=$@ expand to many words. */
  6325. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6326. /* Is this variable quoted and thus expansion can't be null?
  6327. * "$@" is special. Even if quoted, it can still
  6328. * expand to nothing (not even an empty string),
  6329. * thus it is excluded. */
  6330. if ((first_ch & 0x7f) != '@')
  6331. cant_be_null |= first_ch;
  6332. switch (first_ch & 0x7f) {
  6333. /* Highest bit in first_ch indicates that var is double-quoted */
  6334. case '*':
  6335. case '@': {
  6336. int i;
  6337. if (!G.global_argv[1])
  6338. break;
  6339. i = 1;
  6340. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6341. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6342. while (G.global_argv[i]) {
  6343. n = expand_on_ifs(output, n, G.global_argv[i]);
  6344. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6345. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6346. /* this argv[] is not empty and not last:
  6347. * put terminating NUL, start new word */
  6348. o_addchr(output, '\0');
  6349. debug_print_list("expand_vars_to_list[2]", output, n);
  6350. n = o_save_ptr(output, n);
  6351. debug_print_list("expand_vars_to_list[3]", output, n);
  6352. }
  6353. }
  6354. } else
  6355. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6356. * and in this case should treat it like '$*' - see 'else...' below */
  6357. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6358. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6359. ) {
  6360. while (1) {
  6361. o_addQstr(output, G.global_argv[i]);
  6362. if (++i >= G.global_argc)
  6363. break;
  6364. o_addchr(output, '\0');
  6365. debug_print_list("expand_vars_to_list[4]", output, n);
  6366. n = o_save_ptr(output, n);
  6367. }
  6368. } else { /* quoted $* (or v="$@" case): add as one word */
  6369. while (1) {
  6370. o_addQstr(output, G.global_argv[i]);
  6371. if (!G.global_argv[++i])
  6372. break;
  6373. if (G.ifs[0])
  6374. o_addchr(output, G.ifs[0]);
  6375. }
  6376. output->has_quoted_part = 1;
  6377. }
  6378. break;
  6379. }
  6380. case SPECIAL_VAR_SYMBOL: {
  6381. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6382. /* "Empty variable", used to make "" etc to not disappear */
  6383. output->has_quoted_part = 1;
  6384. cant_be_null = 0x80;
  6385. arg++;
  6386. break;
  6387. }
  6388. case SPECIAL_VAR_QUOTED_SVS:
  6389. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6390. /* "^C variable", represents literal ^C char (possible in scripts) */
  6391. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6392. arg++;
  6393. break;
  6394. #if ENABLE_HUSH_TICK
  6395. case '`': {
  6396. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6397. o_string subst_result = NULL_O_STRING;
  6398. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6399. arg++;
  6400. /* Can't just stuff it into output o_string,
  6401. * expanded result may need to be globbed
  6402. * and $IFS-split */
  6403. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6404. G.last_exitcode = process_command_subs(&subst_result, arg);
  6405. G.expand_exitcode = G.last_exitcode;
  6406. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6407. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6408. o_free(&subst_result);
  6409. break;
  6410. }
  6411. #endif
  6412. #if ENABLE_FEATURE_SH_MATH
  6413. case '+': {
  6414. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6415. arith_t res;
  6416. arg++; /* skip '+' */
  6417. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6418. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6419. res = expand_and_evaluate_arith(arg, NULL);
  6420. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6421. sprintf(arith_buf, ARITH_FMT, res);
  6422. o_addstr(output, arith_buf);
  6423. break;
  6424. }
  6425. #endif
  6426. default:
  6427. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6428. n = expand_one_var(output, n, first_ch, arg, &p);
  6429. break;
  6430. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6431. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6432. * Do the check to avoid writing to a const string. */
  6433. if (*p != SPECIAL_VAR_SYMBOL)
  6434. *p = SPECIAL_VAR_SYMBOL;
  6435. arg = ++p;
  6436. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6437. if (*arg) {
  6438. /* handle trailing string */
  6439. if (output->ended_in_ifs) {
  6440. o_addchr(output, '\0');
  6441. n = o_save_ptr(output, n);
  6442. }
  6443. debug_print_list("expand_vars_to_list[a]", output, n);
  6444. /* this part is literal, and it was already pre-quoted
  6445. * if needed (much earlier), do not use o_addQstr here!
  6446. */
  6447. o_addstr(output, arg);
  6448. debug_print_list("expand_vars_to_list[b]", output, n);
  6449. } else
  6450. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6451. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6452. && !output->has_quoted_part
  6453. ) {
  6454. n--;
  6455. /* allow to reuse list[n] later without re-growth */
  6456. output->has_empty_slot = 1;
  6457. }
  6458. return n;
  6459. }
  6460. static char **expand_variables(char **argv, unsigned expflags)
  6461. {
  6462. int n;
  6463. char **list;
  6464. o_string output = NULL_O_STRING;
  6465. output.o_expflags = expflags;
  6466. n = 0;
  6467. for (;;) {
  6468. /* go to next list[n] */
  6469. output.ended_in_ifs = 0;
  6470. n = o_save_ptr(&output, n);
  6471. if (!*argv)
  6472. break;
  6473. /* expand argv[i] */
  6474. n = expand_vars_to_list(&output, n, *argv++);
  6475. /* if (!output->has_empty_slot) -- need this?? */
  6476. o_addchr(&output, '\0');
  6477. }
  6478. debug_print_list("expand_variables", &output, n);
  6479. /* output.data (malloced in one block) gets returned in "list" */
  6480. list = o_finalize_list(&output, n);
  6481. debug_print_strings("expand_variables[1]", list);
  6482. return list;
  6483. }
  6484. static char **expand_strvec_to_strvec(char **argv)
  6485. {
  6486. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6487. }
  6488. #if defined(CMD_SINGLEWORD_NOGLOB)
  6489. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6490. {
  6491. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6492. }
  6493. #endif
  6494. /* Used for expansion of right hand of assignments,
  6495. * $((...)), heredocs, variable expansion parts.
  6496. *
  6497. * NB: should NOT do globbing!
  6498. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6499. */
  6500. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6501. {
  6502. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6503. const int do_unbackslash = 1;
  6504. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6505. #endif
  6506. char *argv[2], **list;
  6507. debug_printf_expand("string_to_string<='%s'\n", str);
  6508. /* This is generally an optimization, but it also
  6509. * handles "", which otherwise trips over !list[0] check below.
  6510. * (is this ever happens that we actually get str="" here?)
  6511. */
  6512. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6513. //TODO: Can use on strings with \ too, just unbackslash() them?
  6514. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6515. return xstrdup(str);
  6516. }
  6517. argv[0] = (char*)str;
  6518. argv[1] = NULL;
  6519. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6520. if (!list[0]) {
  6521. /* Example where it happens:
  6522. * x=; echo ${x:-"$@"}
  6523. */
  6524. ((char*)list)[0] = '\0';
  6525. } else {
  6526. if (HUSH_DEBUG)
  6527. if (list[1])
  6528. bb_simple_error_msg_and_die("BUG in varexp2");
  6529. /* actually, just move string 2*sizeof(char*) bytes back */
  6530. overlapping_strcpy((char*)list, list[0]);
  6531. if (do_unbackslash)
  6532. unbackslash((char*)list);
  6533. }
  6534. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6535. return (char*)list;
  6536. }
  6537. #if 0
  6538. static char* expand_strvec_to_string(char **argv)
  6539. {
  6540. char **list;
  6541. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6542. /* Convert all NULs to spaces */
  6543. if (list[0]) {
  6544. int n = 1;
  6545. while (list[n]) {
  6546. if (HUSH_DEBUG)
  6547. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6548. bb_error_msg_and_die("BUG in varexp3");
  6549. /* bash uses ' ' regardless of $IFS contents */
  6550. list[n][-1] = ' ';
  6551. n++;
  6552. }
  6553. }
  6554. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6555. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6556. return (char*)list;
  6557. }
  6558. #endif
  6559. static char **expand_assignments(char **argv, int count)
  6560. {
  6561. int i;
  6562. char **p;
  6563. G.expanded_assignments = p = NULL;
  6564. /* Expand assignments into one string each */
  6565. for (i = 0; i < count; i++) {
  6566. p = add_string_to_strings(p,
  6567. expand_string_to_string(argv[i],
  6568. EXP_FLAG_ESC_GLOB_CHARS,
  6569. /*unbackslash:*/ 1
  6570. )
  6571. );
  6572. G.expanded_assignments = p;
  6573. }
  6574. G.expanded_assignments = NULL;
  6575. return p;
  6576. }
  6577. static void switch_off_special_sigs(unsigned mask)
  6578. {
  6579. unsigned sig = 0;
  6580. while ((mask >>= 1) != 0) {
  6581. sig++;
  6582. if (!(mask & 1))
  6583. continue;
  6584. #if ENABLE_HUSH_TRAP
  6585. if (G_traps) {
  6586. if (G_traps[sig] && !G_traps[sig][0])
  6587. /* trap is '', has to remain SIG_IGN */
  6588. continue;
  6589. free(G_traps[sig]);
  6590. G_traps[sig] = NULL;
  6591. }
  6592. #endif
  6593. /* We are here only if no trap or trap was not '' */
  6594. install_sighandler(sig, SIG_DFL);
  6595. }
  6596. }
  6597. #if BB_MMU
  6598. /* never called */
  6599. void re_execute_shell(char ***to_free, const char *s,
  6600. char *g_argv0, char **g_argv,
  6601. char **builtin_argv) NORETURN;
  6602. static void reset_traps_to_defaults(void)
  6603. {
  6604. /* This function is always called in a child shell
  6605. * after fork (not vfork, NOMMU doesn't use this function).
  6606. */
  6607. IF_HUSH_TRAP(unsigned sig;)
  6608. unsigned mask;
  6609. /* Child shells are not interactive.
  6610. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6611. * Testcase: (while :; do :; done) + ^Z should background.
  6612. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6613. */
  6614. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6615. if (!G_traps && !mask)
  6616. return; /* already no traps and no special sigs */
  6617. /* Switch off special sigs */
  6618. switch_off_special_sigs(mask);
  6619. # if ENABLE_HUSH_JOB
  6620. G_fatal_sig_mask = 0;
  6621. # endif
  6622. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6623. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6624. * remain set in G.special_sig_mask */
  6625. # if ENABLE_HUSH_TRAP
  6626. if (!G_traps)
  6627. return;
  6628. /* Reset all sigs to default except ones with empty traps */
  6629. for (sig = 0; sig < NSIG; sig++) {
  6630. if (!G_traps[sig])
  6631. continue; /* no trap: nothing to do */
  6632. if (!G_traps[sig][0])
  6633. continue; /* empty trap: has to remain SIG_IGN */
  6634. /* sig has non-empty trap, reset it: */
  6635. free(G_traps[sig]);
  6636. G_traps[sig] = NULL;
  6637. /* There is no signal for trap 0 (EXIT) */
  6638. if (sig == 0)
  6639. continue;
  6640. install_sighandler(sig, pick_sighandler(sig));
  6641. }
  6642. # endif
  6643. }
  6644. #else /* !BB_MMU */
  6645. static void re_execute_shell(char ***to_free, const char *s,
  6646. char *g_argv0, char **g_argv,
  6647. char **builtin_argv) NORETURN;
  6648. static void re_execute_shell(char ***to_free, const char *s,
  6649. char *g_argv0, char **g_argv,
  6650. char **builtin_argv)
  6651. {
  6652. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6653. /* delims + 2 * (number of bytes in printed hex numbers) */
  6654. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6655. char *heredoc_argv[4];
  6656. struct variable *cur;
  6657. # if ENABLE_HUSH_FUNCTIONS
  6658. struct function *funcp;
  6659. # endif
  6660. char **argv, **pp;
  6661. unsigned cnt;
  6662. unsigned long long empty_trap_mask;
  6663. if (!g_argv0) { /* heredoc */
  6664. argv = heredoc_argv;
  6665. argv[0] = (char *) G.argv0_for_re_execing;
  6666. argv[1] = (char *) "-<";
  6667. argv[2] = (char *) s;
  6668. argv[3] = NULL;
  6669. pp = &argv[3]; /* used as pointer to empty environment */
  6670. goto do_exec;
  6671. }
  6672. cnt = 0;
  6673. pp = builtin_argv;
  6674. if (pp) while (*pp++)
  6675. cnt++;
  6676. empty_trap_mask = 0;
  6677. if (G_traps) {
  6678. int sig;
  6679. for (sig = 1; sig < NSIG; sig++) {
  6680. if (G_traps[sig] && !G_traps[sig][0])
  6681. empty_trap_mask |= 1LL << sig;
  6682. }
  6683. }
  6684. sprintf(param_buf, NOMMU_HACK_FMT
  6685. , (unsigned) G.root_pid
  6686. , (unsigned) G.root_ppid
  6687. , (unsigned) G.last_bg_pid
  6688. , (unsigned) G.last_exitcode
  6689. , cnt
  6690. , empty_trap_mask
  6691. IF_HUSH_LOOPS(, G.depth_of_loop)
  6692. );
  6693. # undef NOMMU_HACK_FMT
  6694. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6695. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6696. */
  6697. cnt += 6;
  6698. for (cur = G.top_var; cur; cur = cur->next) {
  6699. if (!cur->flg_export || cur->flg_read_only)
  6700. cnt += 2;
  6701. }
  6702. # if ENABLE_HUSH_FUNCTIONS
  6703. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6704. cnt += 3;
  6705. # endif
  6706. pp = g_argv;
  6707. while (*pp++)
  6708. cnt++;
  6709. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6710. *pp++ = (char *) G.argv0_for_re_execing;
  6711. *pp++ = param_buf;
  6712. for (cur = G.top_var; cur; cur = cur->next) {
  6713. if (strcmp(cur->varstr, hush_version_str) == 0)
  6714. continue;
  6715. if (cur->flg_read_only) {
  6716. *pp++ = (char *) "-R";
  6717. *pp++ = cur->varstr;
  6718. } else if (!cur->flg_export) {
  6719. *pp++ = (char *) "-V";
  6720. *pp++ = cur->varstr;
  6721. }
  6722. }
  6723. # if ENABLE_HUSH_FUNCTIONS
  6724. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6725. *pp++ = (char *) "-F";
  6726. *pp++ = funcp->name;
  6727. *pp++ = funcp->body_as_string;
  6728. }
  6729. # endif
  6730. /* We can pass activated traps here. Say, -Tnn:trap_string
  6731. *
  6732. * However, POSIX says that subshells reset signals with traps
  6733. * to SIG_DFL.
  6734. * I tested bash-3.2 and it not only does that with true subshells
  6735. * of the form ( list ), but with any forked children shells.
  6736. * I set trap "echo W" WINCH; and then tried:
  6737. *
  6738. * { echo 1; sleep 20; echo 2; } &
  6739. * while true; do echo 1; sleep 20; echo 2; break; done &
  6740. * true | { echo 1; sleep 20; echo 2; } | cat
  6741. *
  6742. * In all these cases sending SIGWINCH to the child shell
  6743. * did not run the trap. If I add trap "echo V" WINCH;
  6744. * _inside_ group (just before echo 1), it works.
  6745. *
  6746. * I conclude it means we don't need to pass active traps here.
  6747. */
  6748. *pp++ = (char *) "-c";
  6749. *pp++ = (char *) s;
  6750. if (builtin_argv) {
  6751. while (*++builtin_argv)
  6752. *pp++ = *builtin_argv;
  6753. *pp++ = (char *) "";
  6754. }
  6755. *pp++ = g_argv0;
  6756. while (*g_argv)
  6757. *pp++ = *g_argv++;
  6758. /* *pp = NULL; - is already there */
  6759. pp = environ;
  6760. do_exec:
  6761. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6762. /* Don't propagate SIG_IGN to the child */
  6763. if (SPECIAL_JOBSTOP_SIGS != 0)
  6764. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6765. execve(bb_busybox_exec_path, argv, pp);
  6766. /* Fallback. Useful for init=/bin/hush usage etc */
  6767. if (argv[0][0] == '/')
  6768. execve(argv[0], argv, pp);
  6769. xfunc_error_retval = 127;
  6770. bb_simple_error_msg_and_die("can't re-execute the shell");
  6771. }
  6772. #endif /* !BB_MMU */
  6773. static int run_and_free_list(struct pipe *pi);
  6774. /* Executing from string: eval, sh -c '...'
  6775. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6776. * end_trigger controls how often we stop parsing
  6777. * NUL: parse all, execute, return
  6778. * ';': parse till ';' or newline, execute, repeat till EOF
  6779. */
  6780. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6781. {
  6782. /* Why we need empty flag?
  6783. * An obscure corner case "false; ``; echo $?":
  6784. * empty command in `` should still set $? to 0.
  6785. * But we can't just set $? to 0 at the start,
  6786. * this breaks "false; echo `echo $?`" case.
  6787. */
  6788. bool empty = 1;
  6789. while (1) {
  6790. struct pipe *pipe_list;
  6791. #if ENABLE_HUSH_INTERACTIVE
  6792. if (end_trigger == ';') {
  6793. G.promptmode = 0; /* PS1 */
  6794. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6795. }
  6796. #endif
  6797. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6798. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6799. /* If we are in "big" script
  6800. * (not in `cmd` or something similar)...
  6801. */
  6802. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6803. /* Discard cached input (rest of line) */
  6804. int ch = inp->last_char;
  6805. while (ch != EOF && ch != '\n') {
  6806. //bb_error_msg("Discarded:'%c'", ch);
  6807. ch = i_getch(inp);
  6808. }
  6809. /* Force prompt */
  6810. inp->p = NULL;
  6811. /* This stream isn't empty */
  6812. empty = 0;
  6813. continue;
  6814. }
  6815. if (!pipe_list && empty)
  6816. G.last_exitcode = 0;
  6817. break;
  6818. }
  6819. debug_print_tree(pipe_list, 0);
  6820. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6821. run_and_free_list(pipe_list);
  6822. empty = 0;
  6823. if (G_flag_return_in_progress == 1)
  6824. break;
  6825. }
  6826. }
  6827. static void parse_and_run_string(const char *s)
  6828. {
  6829. struct in_str input;
  6830. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6831. setup_string_in_str(&input, s);
  6832. parse_and_run_stream(&input, '\0');
  6833. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6834. }
  6835. static void parse_and_run_file(HFILE *fp)
  6836. {
  6837. struct in_str input;
  6838. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6839. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6840. setup_file_in_str(&input, fp);
  6841. parse_and_run_stream(&input, ';');
  6842. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6843. }
  6844. #if ENABLE_HUSH_TICK
  6845. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6846. {
  6847. pid_t pid;
  6848. int channel[2];
  6849. # if !BB_MMU
  6850. char **to_free = NULL;
  6851. # endif
  6852. xpipe(channel);
  6853. pid = BB_MMU ? xfork() : xvfork();
  6854. if (pid == 0) { /* child */
  6855. disable_restore_tty_pgrp_on_exit();
  6856. /* Process substitution is not considered to be usual
  6857. * 'command execution'.
  6858. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6859. */
  6860. bb_signals(0
  6861. + (1 << SIGTSTP)
  6862. + (1 << SIGTTIN)
  6863. + (1 << SIGTTOU)
  6864. , SIG_IGN);
  6865. close(channel[0]); /* NB: close _first_, then move fd! */
  6866. xmove_fd(channel[1], 1);
  6867. # if ENABLE_HUSH_TRAP
  6868. /* Awful hack for `trap` or $(trap).
  6869. *
  6870. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6871. * contains an example where "trap" is executed in a subshell:
  6872. *
  6873. * save_traps=$(trap)
  6874. * ...
  6875. * eval "$save_traps"
  6876. *
  6877. * Standard does not say that "trap" in subshell shall print
  6878. * parent shell's traps. It only says that its output
  6879. * must have suitable form, but then, in the above example
  6880. * (which is not supposed to be normative), it implies that.
  6881. *
  6882. * bash (and probably other shell) does implement it
  6883. * (traps are reset to defaults, but "trap" still shows them),
  6884. * but as a result, "trap" logic is hopelessly messed up:
  6885. *
  6886. * # trap
  6887. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6888. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6889. * # true | trap <--- trap is in subshell - no output (ditto)
  6890. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6891. * trap -- 'echo Ho' SIGWINCH
  6892. * # echo `(trap)` <--- in subshell in subshell - output
  6893. * trap -- 'echo Ho' SIGWINCH
  6894. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6895. * trap -- 'echo Ho' SIGWINCH
  6896. *
  6897. * The rules when to forget and when to not forget traps
  6898. * get really complex and nonsensical.
  6899. *
  6900. * Our solution: ONLY bare $(trap) or `trap` is special.
  6901. */
  6902. s = skip_whitespace(s);
  6903. if (is_prefixed_with(s, "trap")
  6904. && skip_whitespace(s + 4)[0] == '\0'
  6905. ) {
  6906. static const char *const argv[] = { NULL, NULL };
  6907. builtin_trap((char**)argv);
  6908. fflush_all(); /* important */
  6909. _exit(0);
  6910. }
  6911. # endif
  6912. # if BB_MMU
  6913. /* Prevent it from trying to handle ctrl-z etc */
  6914. IF_HUSH_JOB(G.run_list_level = 1;)
  6915. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6916. reset_traps_to_defaults();
  6917. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6918. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6919. parse_and_run_string(s);
  6920. _exit(G.last_exitcode);
  6921. # else
  6922. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6923. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6924. * huge=`cat BIG` # was blocking here forever
  6925. * echo OK
  6926. */
  6927. re_execute_shell(&to_free,
  6928. s,
  6929. G.global_argv[0],
  6930. G.global_argv + 1,
  6931. NULL);
  6932. # endif
  6933. }
  6934. /* parent */
  6935. *pid_p = pid;
  6936. # if ENABLE_HUSH_FAST
  6937. G.count_SIGCHLD++;
  6938. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6939. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6940. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6941. # endif
  6942. enable_restore_tty_pgrp_on_exit();
  6943. # if !BB_MMU
  6944. free(to_free);
  6945. # endif
  6946. close(channel[1]);
  6947. return channel[0];
  6948. }
  6949. /* Return code is exit status of the process that is run. */
  6950. static int process_command_subs(o_string *dest, const char *s)
  6951. {
  6952. FILE *fp;
  6953. pid_t pid;
  6954. int status, ch, eol_cnt;
  6955. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6956. /* Now send results of command back into original context */
  6957. eol_cnt = 0;
  6958. while ((ch = getc(fp)) != EOF) {
  6959. if (ch == '\0')
  6960. continue;
  6961. if (ch == '\n') {
  6962. eol_cnt++;
  6963. continue;
  6964. }
  6965. while (eol_cnt) {
  6966. o_addchr(dest, '\n');
  6967. eol_cnt--;
  6968. }
  6969. o_addQchr(dest, ch);
  6970. }
  6971. debug_printf("done reading from `cmd` pipe, closing it\n");
  6972. fclose(fp);
  6973. /* We need to extract exitcode. Test case
  6974. * "true; echo `sleep 1; false` $?"
  6975. * should print 1 */
  6976. safe_waitpid(pid, &status, 0);
  6977. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6978. return WEXITSTATUS(status);
  6979. }
  6980. #endif /* ENABLE_HUSH_TICK */
  6981. static void setup_heredoc(struct redir_struct *redir)
  6982. {
  6983. struct fd_pair pair;
  6984. pid_t pid;
  6985. int len, written;
  6986. /* the _body_ of heredoc (misleading field name) */
  6987. const char *heredoc = redir->rd_filename;
  6988. char *expanded;
  6989. #if !BB_MMU
  6990. char **to_free;
  6991. #endif
  6992. expanded = NULL;
  6993. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6994. expanded = encode_then_expand_string(heredoc);
  6995. if (expanded)
  6996. heredoc = expanded;
  6997. }
  6998. len = strlen(heredoc);
  6999. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7000. xpiped_pair(pair);
  7001. xmove_fd(pair.rd, redir->rd_fd);
  7002. /* Try writing without forking. Newer kernels have
  7003. * dynamically growing pipes. Must use non-blocking write! */
  7004. ndelay_on(pair.wr);
  7005. while (1) {
  7006. written = write(pair.wr, heredoc, len);
  7007. if (written <= 0)
  7008. break;
  7009. len -= written;
  7010. if (len == 0) {
  7011. close(pair.wr);
  7012. free(expanded);
  7013. return;
  7014. }
  7015. heredoc += written;
  7016. }
  7017. ndelay_off(pair.wr);
  7018. /* Okay, pipe buffer was not big enough */
  7019. /* Note: we must not create a stray child (bastard? :)
  7020. * for the unsuspecting parent process. Child creates a grandchild
  7021. * and exits before parent execs the process which consumes heredoc
  7022. * (that exec happens after we return from this function) */
  7023. #if !BB_MMU
  7024. to_free = NULL;
  7025. #endif
  7026. pid = xvfork();
  7027. if (pid == 0) {
  7028. /* child */
  7029. disable_restore_tty_pgrp_on_exit();
  7030. pid = BB_MMU ? xfork() : xvfork();
  7031. if (pid != 0)
  7032. _exit(0);
  7033. /* grandchild */
  7034. close(redir->rd_fd); /* read side of the pipe */
  7035. #if BB_MMU
  7036. full_write(pair.wr, heredoc, len); /* may loop or block */
  7037. _exit(0);
  7038. #else
  7039. /* Delegate blocking writes to another process */
  7040. xmove_fd(pair.wr, STDOUT_FILENO);
  7041. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7042. #endif
  7043. }
  7044. /* parent */
  7045. #if ENABLE_HUSH_FAST
  7046. G.count_SIGCHLD++;
  7047. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7048. #endif
  7049. enable_restore_tty_pgrp_on_exit();
  7050. #if !BB_MMU
  7051. free(to_free);
  7052. #endif
  7053. close(pair.wr);
  7054. free(expanded);
  7055. wait(NULL); /* wait till child has died */
  7056. }
  7057. struct squirrel {
  7058. int orig_fd;
  7059. int moved_to;
  7060. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7061. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7062. };
  7063. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7064. {
  7065. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7066. sq[i].orig_fd = orig;
  7067. sq[i].moved_to = moved;
  7068. sq[i+1].orig_fd = -1; /* end marker */
  7069. return sq;
  7070. }
  7071. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7072. {
  7073. int moved_to;
  7074. int i;
  7075. i = 0;
  7076. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7077. /* If we collide with an already moved fd... */
  7078. if (fd == sq[i].moved_to) {
  7079. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7080. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7081. if (sq[i].moved_to < 0) /* what? */
  7082. xfunc_die();
  7083. return sq;
  7084. }
  7085. if (fd == sq[i].orig_fd) {
  7086. /* Example: echo Hello >/dev/null 1>&2 */
  7087. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7088. return sq;
  7089. }
  7090. }
  7091. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7092. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7093. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7094. if (moved_to < 0 && errno != EBADF)
  7095. xfunc_die();
  7096. return append_squirrel(sq, i, fd, moved_to);
  7097. }
  7098. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7099. {
  7100. int i;
  7101. i = 0;
  7102. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7103. /* If we collide with an already moved fd... */
  7104. if (fd == sq[i].orig_fd) {
  7105. /* Examples:
  7106. * "echo 3>FILE 3>&- 3>FILE"
  7107. * "echo 3>&- 3>FILE"
  7108. * No need for last redirect to insert
  7109. * another "need to close 3" indicator.
  7110. */
  7111. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7112. return sq;
  7113. }
  7114. }
  7115. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7116. return append_squirrel(sq, i, fd, -1);
  7117. }
  7118. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7119. * Move all conflicting internally used fds,
  7120. * and remember them so that we can restore them later.
  7121. */
  7122. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7123. {
  7124. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7125. avoid_fd = 9;
  7126. #if ENABLE_HUSH_INTERACTIVE
  7127. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7128. && fd == G_interactive_fd
  7129. ) {
  7130. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7131. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7132. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7133. return 1; /* "we closed fd" */
  7134. }
  7135. #endif
  7136. /* Are we called from setup_redirects(squirrel==NULL)
  7137. * in redirect in a [v]forked child?
  7138. */
  7139. if (sqp == NULL) {
  7140. /* No need to move script fds.
  7141. * For NOMMU case, it's actively wrong: we'd change ->fd
  7142. * fields in memory for the parent, but parent's fds
  7143. * aren't moved, it would use wrong fd!
  7144. * Reproducer: "cmd 3>FILE" in script.
  7145. * If we would call move_HFILEs_on_redirect(), child would:
  7146. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7147. * close(3) = 0
  7148. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7149. */
  7150. //bb_error_msg("sqp == NULL: [v]forked child");
  7151. return 0;
  7152. }
  7153. /* If this one of script's fds? */
  7154. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7155. return 1; /* yes. "we closed fd" (actually moved it) */
  7156. /* Are we called for "exec 3>FILE"? Came through
  7157. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7158. * This case used to fail for this script:
  7159. * exec 3>FILE
  7160. * echo Ok
  7161. * ...100000 more lines...
  7162. * echo Ok
  7163. * as follows:
  7164. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7165. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7166. * dup2(4, 3) = 3
  7167. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7168. * close(4) = 0
  7169. * write(1, "Ok\n", 3) = 3
  7170. * ... = 3
  7171. * write(1, "Ok\n", 3) = 3
  7172. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7173. * ^^^^^^^^ oops, wrong fd!!!
  7174. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7175. * it now works:
  7176. */
  7177. if (sqp == ERR_PTR) {
  7178. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7179. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7180. return 0;
  7181. }
  7182. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7183. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7184. return 0; /* "we did not close fd" */
  7185. }
  7186. static void restore_redirects(struct squirrel *sq)
  7187. {
  7188. if (sq) {
  7189. int i;
  7190. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7191. if (sq[i].moved_to >= 0) {
  7192. /* We simply die on error */
  7193. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7194. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7195. } else {
  7196. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7197. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7198. close(sq[i].orig_fd);
  7199. }
  7200. }
  7201. free(sq);
  7202. }
  7203. if (G.HFILE_stdin
  7204. && G.HFILE_stdin->fd != STDIN_FILENO
  7205. ) {
  7206. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7207. * Redirect moves ->fd to e.g. 10,
  7208. * and it is not restored above (we do not restore script fds
  7209. * after redirects, we just use new, "moved" fds).
  7210. * However for stdin, get_user_input() -> read_line_input(),
  7211. * and read builtin, depend on fd == STDIN_FILENO.
  7212. */
  7213. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7214. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7215. G.HFILE_stdin->fd = STDIN_FILENO;
  7216. }
  7217. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7218. }
  7219. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7220. static void close_saved_fds_and_FILE_fds(void)
  7221. {
  7222. if (G_interactive_fd)
  7223. close(G_interactive_fd);
  7224. close_all_HFILE_list();
  7225. }
  7226. #endif
  7227. static int internally_opened_fd(int fd, struct squirrel *sq)
  7228. {
  7229. int i;
  7230. #if ENABLE_HUSH_INTERACTIVE
  7231. if (fd == G_interactive_fd)
  7232. return 1;
  7233. #endif
  7234. /* If this one of script's fds? */
  7235. if (fd_in_HFILEs(fd))
  7236. return 1;
  7237. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7238. if (fd == sq[i].moved_to)
  7239. return 1;
  7240. }
  7241. return 0;
  7242. }
  7243. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7244. * and stderr if they are redirected. */
  7245. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7246. {
  7247. struct redir_struct *redir;
  7248. for (redir = prog->redirects; redir; redir = redir->next) {
  7249. int newfd;
  7250. int closed;
  7251. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7252. /* "rd_fd<<HERE" case */
  7253. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7254. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7255. * of the heredoc */
  7256. debug_printf_redir("set heredoc '%s'\n",
  7257. redir->rd_filename);
  7258. setup_heredoc(redir);
  7259. continue;
  7260. }
  7261. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7262. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7263. char *p;
  7264. int mode;
  7265. if (redir->rd_filename == NULL) {
  7266. /* Examples:
  7267. * "cmd >" (no filename)
  7268. * "cmd > <file" (2nd redirect starts too early)
  7269. */
  7270. syntax_error("invalid redirect");
  7271. continue;
  7272. }
  7273. mode = redir_table[redir->rd_type].mode;
  7274. p = expand_string_to_string(redir->rd_filename,
  7275. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7276. newfd = open_or_warn(p, mode);
  7277. free(p);
  7278. if (newfd < 0) {
  7279. /* Error message from open_or_warn can be lost
  7280. * if stderr has been redirected, but bash
  7281. * and ash both lose it as well
  7282. * (though zsh doesn't!)
  7283. */
  7284. return 1;
  7285. }
  7286. if (newfd == redir->rd_fd && sqp) {
  7287. /* open() gave us precisely the fd we wanted.
  7288. * This means that this fd was not busy
  7289. * (not opened to anywhere).
  7290. * Remember to close it on restore:
  7291. */
  7292. *sqp = add_squirrel_closed(*sqp, newfd);
  7293. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7294. }
  7295. } else {
  7296. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7297. newfd = redir->rd_dup;
  7298. }
  7299. if (newfd == redir->rd_fd)
  7300. continue;
  7301. /* if "N>FILE": move newfd to redir->rd_fd */
  7302. /* if "N>&M": dup newfd to redir->rd_fd */
  7303. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7304. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7305. if (newfd == REDIRFD_CLOSE) {
  7306. /* "N>&-" means "close me" */
  7307. if (!closed) {
  7308. /* ^^^ optimization: saving may already
  7309. * have closed it. If not... */
  7310. close(redir->rd_fd);
  7311. }
  7312. /* Sometimes we do another close on restore, getting EBADF.
  7313. * Consider "echo 3>FILE 3>&-"
  7314. * first redirect remembers "need to close 3",
  7315. * and second redirect closes 3! Restore code then closes 3 again.
  7316. */
  7317. } else {
  7318. /* if newfd is a script fd or saved fd, simulate EBADF */
  7319. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7320. //errno = EBADF;
  7321. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7322. newfd = -1; /* same effect as code above */
  7323. }
  7324. xdup2(newfd, redir->rd_fd);
  7325. if (redir->rd_dup == REDIRFD_TO_FILE)
  7326. /* "rd_fd > FILE" */
  7327. close(newfd);
  7328. /* else: "rd_fd > rd_dup" */
  7329. }
  7330. }
  7331. return 0;
  7332. }
  7333. static char *find_in_path(const char *arg)
  7334. {
  7335. char *ret = NULL;
  7336. const char *PATH = get_local_var_value("PATH");
  7337. if (!PATH)
  7338. return NULL;
  7339. while (1) {
  7340. const char *end = strchrnul(PATH, ':');
  7341. int sz = end - PATH; /* must be int! */
  7342. free(ret);
  7343. if (sz != 0) {
  7344. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7345. } else {
  7346. /* We have xxx::yyyy in $PATH,
  7347. * it means "use current dir" */
  7348. ret = xstrdup(arg);
  7349. }
  7350. if (access(ret, F_OK) == 0)
  7351. break;
  7352. if (*end == '\0') {
  7353. free(ret);
  7354. return NULL;
  7355. }
  7356. PATH = end + 1;
  7357. }
  7358. return ret;
  7359. }
  7360. static const struct built_in_command *find_builtin_helper(const char *name,
  7361. const struct built_in_command *x,
  7362. const struct built_in_command *end)
  7363. {
  7364. while (x != end) {
  7365. if (strcmp(name, x->b_cmd) != 0) {
  7366. x++;
  7367. continue;
  7368. }
  7369. debug_printf_exec("found builtin '%s'\n", name);
  7370. return x;
  7371. }
  7372. return NULL;
  7373. }
  7374. static const struct built_in_command *find_builtin1(const char *name)
  7375. {
  7376. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7377. }
  7378. static const struct built_in_command *find_builtin(const char *name)
  7379. {
  7380. const struct built_in_command *x = find_builtin1(name);
  7381. if (x)
  7382. return x;
  7383. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7384. }
  7385. static void remove_nested_vars(void)
  7386. {
  7387. struct variable *cur;
  7388. struct variable **cur_pp;
  7389. cur_pp = &G.top_var;
  7390. while ((cur = *cur_pp) != NULL) {
  7391. if (cur->var_nest_level <= G.var_nest_level) {
  7392. cur_pp = &cur->next;
  7393. continue;
  7394. }
  7395. /* Unexport */
  7396. if (cur->flg_export) {
  7397. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7398. bb_unsetenv(cur->varstr);
  7399. }
  7400. /* Remove from global list */
  7401. *cur_pp = cur->next;
  7402. /* Free */
  7403. if (!cur->max_len) {
  7404. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7405. free(cur->varstr);
  7406. }
  7407. free(cur);
  7408. }
  7409. }
  7410. static void enter_var_nest_level(void)
  7411. {
  7412. G.var_nest_level++;
  7413. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7414. /* Try: f() { echo -n .; f; }; f
  7415. * struct variable::var_nest_level is uint16_t,
  7416. * thus limiting recursion to < 2^16.
  7417. * In any case, with 8 Mbyte stack SEGV happens
  7418. * not too long after 2^16 recursions anyway.
  7419. */
  7420. if (G.var_nest_level > 0xff00)
  7421. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7422. }
  7423. static void leave_var_nest_level(void)
  7424. {
  7425. G.var_nest_level--;
  7426. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7427. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7428. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7429. remove_nested_vars();
  7430. }
  7431. #if ENABLE_HUSH_FUNCTIONS
  7432. static struct function **find_function_slot(const char *name)
  7433. {
  7434. struct function *funcp;
  7435. struct function **funcpp = &G.top_func;
  7436. while ((funcp = *funcpp) != NULL) {
  7437. if (strcmp(name, funcp->name) == 0) {
  7438. debug_printf_exec("found function '%s'\n", name);
  7439. break;
  7440. }
  7441. funcpp = &funcp->next;
  7442. }
  7443. return funcpp;
  7444. }
  7445. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7446. {
  7447. const struct function *funcp = *find_function_slot(name);
  7448. return funcp;
  7449. }
  7450. /* Note: takes ownership on name ptr */
  7451. static struct function *new_function(char *name)
  7452. {
  7453. struct function **funcpp = find_function_slot(name);
  7454. struct function *funcp = *funcpp;
  7455. if (funcp != NULL) {
  7456. struct command *cmd = funcp->parent_cmd;
  7457. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7458. if (!cmd) {
  7459. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7460. free(funcp->name);
  7461. /* Note: if !funcp->body, do not free body_as_string!
  7462. * This is a special case of "-F name body" function:
  7463. * body_as_string was not malloced! */
  7464. if (funcp->body) {
  7465. free_pipe_list(funcp->body);
  7466. # if !BB_MMU
  7467. free(funcp->body_as_string);
  7468. # endif
  7469. }
  7470. } else {
  7471. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7472. cmd->argv[0] = funcp->name;
  7473. cmd->group = funcp->body;
  7474. # if !BB_MMU
  7475. cmd->group_as_string = funcp->body_as_string;
  7476. # endif
  7477. }
  7478. } else {
  7479. debug_printf_exec("remembering new function '%s'\n", name);
  7480. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7481. /*funcp->next = NULL;*/
  7482. }
  7483. funcp->name = name;
  7484. return funcp;
  7485. }
  7486. # if ENABLE_HUSH_UNSET
  7487. static void unset_func(const char *name)
  7488. {
  7489. struct function **funcpp = find_function_slot(name);
  7490. struct function *funcp = *funcpp;
  7491. if (funcp != NULL) {
  7492. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7493. *funcpp = funcp->next;
  7494. /* funcp is unlinked now, deleting it.
  7495. * Note: if !funcp->body, the function was created by
  7496. * "-F name body", do not free ->body_as_string
  7497. * and ->name as they were not malloced. */
  7498. if (funcp->body) {
  7499. free_pipe_list(funcp->body);
  7500. free(funcp->name);
  7501. # if !BB_MMU
  7502. free(funcp->body_as_string);
  7503. # endif
  7504. }
  7505. free(funcp);
  7506. }
  7507. }
  7508. # endif
  7509. # if BB_MMU
  7510. #define exec_function(to_free, funcp, argv) \
  7511. exec_function(funcp, argv)
  7512. # endif
  7513. static void exec_function(char ***to_free,
  7514. const struct function *funcp,
  7515. char **argv) NORETURN;
  7516. static void exec_function(char ***to_free,
  7517. const struct function *funcp,
  7518. char **argv)
  7519. {
  7520. # if BB_MMU
  7521. int n;
  7522. argv[0] = G.global_argv[0];
  7523. G.global_argv = argv;
  7524. G.global_argc = n = 1 + string_array_len(argv + 1);
  7525. // Example when we are here: "cmd | func"
  7526. // func will run with saved-redirect fds open.
  7527. // $ f() { echo /proc/self/fd/*; }
  7528. // $ true | f
  7529. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7530. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7531. // Same in script:
  7532. // $ . ./SCRIPT
  7533. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7534. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7535. // They are CLOEXEC so external programs won't see them, but
  7536. // for "more correctness" we might want to close those extra fds here:
  7537. //? close_saved_fds_and_FILE_fds();
  7538. /* "we are in a function, ok to use return" */
  7539. G_flag_return_in_progress = -1;
  7540. enter_var_nest_level();
  7541. IF_HUSH_LOCAL(G.func_nest_level++;)
  7542. /* On MMU, funcp->body is always non-NULL */
  7543. n = run_list(funcp->body);
  7544. fflush_all();
  7545. _exit(n);
  7546. # else
  7547. //? close_saved_fds_and_FILE_fds();
  7548. //TODO: check whether "true | func_with_return" works
  7549. re_execute_shell(to_free,
  7550. funcp->body_as_string,
  7551. G.global_argv[0],
  7552. argv + 1,
  7553. NULL);
  7554. # endif
  7555. }
  7556. static int run_function(const struct function *funcp, char **argv)
  7557. {
  7558. int rc;
  7559. save_arg_t sv;
  7560. smallint sv_flg;
  7561. save_and_replace_G_args(&sv, argv);
  7562. /* "We are in function, ok to use return" */
  7563. sv_flg = G_flag_return_in_progress;
  7564. G_flag_return_in_progress = -1;
  7565. /* Make "local" variables properly shadow previous ones */
  7566. IF_HUSH_LOCAL(enter_var_nest_level();)
  7567. IF_HUSH_LOCAL(G.func_nest_level++;)
  7568. /* On MMU, funcp->body is always non-NULL */
  7569. # if !BB_MMU
  7570. if (!funcp->body) {
  7571. /* Function defined by -F */
  7572. parse_and_run_string(funcp->body_as_string);
  7573. rc = G.last_exitcode;
  7574. } else
  7575. # endif
  7576. {
  7577. rc = run_list(funcp->body);
  7578. }
  7579. IF_HUSH_LOCAL(G.func_nest_level--;)
  7580. IF_HUSH_LOCAL(leave_var_nest_level();)
  7581. G_flag_return_in_progress = sv_flg;
  7582. restore_G_args(&sv, argv);
  7583. return rc;
  7584. }
  7585. #endif /* ENABLE_HUSH_FUNCTIONS */
  7586. #if BB_MMU
  7587. #define exec_builtin(to_free, x, argv) \
  7588. exec_builtin(x, argv)
  7589. #else
  7590. #define exec_builtin(to_free, x, argv) \
  7591. exec_builtin(to_free, argv)
  7592. #endif
  7593. static void exec_builtin(char ***to_free,
  7594. const struct built_in_command *x,
  7595. char **argv) NORETURN;
  7596. static void exec_builtin(char ***to_free,
  7597. const struct built_in_command *x,
  7598. char **argv)
  7599. {
  7600. #if BB_MMU
  7601. int rcode;
  7602. fflush_all();
  7603. //? close_saved_fds_and_FILE_fds();
  7604. rcode = x->b_function(argv);
  7605. fflush_all();
  7606. _exit(rcode);
  7607. #else
  7608. fflush_all();
  7609. /* On NOMMU, we must never block!
  7610. * Example: { sleep 99 | read line; } & echo Ok
  7611. */
  7612. re_execute_shell(to_free,
  7613. argv[0],
  7614. G.global_argv[0],
  7615. G.global_argv + 1,
  7616. argv);
  7617. #endif
  7618. }
  7619. static void execvp_or_die(char **argv) NORETURN;
  7620. static void execvp_or_die(char **argv)
  7621. {
  7622. int e;
  7623. debug_printf_exec("execing '%s'\n", argv[0]);
  7624. /* Don't propagate SIG_IGN to the child */
  7625. if (SPECIAL_JOBSTOP_SIGS != 0)
  7626. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7627. execvp(argv[0], argv);
  7628. e = 2;
  7629. if (errno == EACCES) e = 126;
  7630. if (errno == ENOENT) e = 127;
  7631. bb_perror_msg("can't execute '%s'", argv[0]);
  7632. _exit(e);
  7633. }
  7634. #if ENABLE_HUSH_MODE_X
  7635. static void x_mode_print_optionally_squoted(const char *str)
  7636. {
  7637. unsigned len;
  7638. const char *cp;
  7639. cp = str;
  7640. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7641. /* test a char with: bash -c 'set -x; echo "CH"' */
  7642. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7643. " " "\001\002\003\004\005\006\007"
  7644. "\010\011\012\013\014\015\016\017"
  7645. "\020\021\022\023\024\025\026\027"
  7646. "\030\031\032\033\034\035\036\037"
  7647. )
  7648. ] == '\0'
  7649. ) {
  7650. /* string has no special chars */
  7651. x_mode_addstr(str);
  7652. return;
  7653. }
  7654. cp = str;
  7655. for (;;) {
  7656. /* print '....' up to EOL or first squote */
  7657. len = (int)(strchrnul(cp, '\'') - cp);
  7658. if (len != 0) {
  7659. x_mode_addchr('\'');
  7660. x_mode_addblock(cp, len);
  7661. x_mode_addchr('\'');
  7662. cp += len;
  7663. }
  7664. if (*cp == '\0')
  7665. break;
  7666. /* string contains squote(s), print them as \' */
  7667. x_mode_addchr('\\');
  7668. x_mode_addchr('\'');
  7669. cp++;
  7670. }
  7671. }
  7672. static void dump_cmd_in_x_mode(char **argv)
  7673. {
  7674. if (G_x_mode && argv) {
  7675. unsigned n;
  7676. /* "+[+++...][ cmd...]\n\0" */
  7677. x_mode_prefix();
  7678. n = 0;
  7679. while (argv[n]) {
  7680. x_mode_addchr(' ');
  7681. if (argv[n][0] == '\0') {
  7682. x_mode_addchr('\'');
  7683. x_mode_addchr('\'');
  7684. } else {
  7685. x_mode_print_optionally_squoted(argv[n]);
  7686. }
  7687. n++;
  7688. }
  7689. x_mode_flush();
  7690. }
  7691. }
  7692. #else
  7693. # define dump_cmd_in_x_mode(argv) ((void)0)
  7694. #endif
  7695. #if ENABLE_HUSH_COMMAND
  7696. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7697. {
  7698. char *to_free;
  7699. if (!opt_vV)
  7700. return;
  7701. to_free = NULL;
  7702. if (!explanation) {
  7703. char *path = getenv("PATH");
  7704. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7705. if (!explanation)
  7706. _exit(1); /* PROG was not found */
  7707. if (opt_vV != 'V')
  7708. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7709. }
  7710. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7711. free(to_free);
  7712. fflush_all();
  7713. _exit(0);
  7714. }
  7715. #else
  7716. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7717. #endif
  7718. #if BB_MMU
  7719. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7720. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7721. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7722. pseudo_exec(command, argv_expanded)
  7723. #endif
  7724. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7725. * Never returns.
  7726. * Don't exit() here. If you don't exec, use _exit instead.
  7727. * The at_exit handlers apparently confuse the calling process,
  7728. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7729. */
  7730. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7731. char **argv, int assignment_cnt,
  7732. char **argv_expanded) NORETURN;
  7733. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7734. char **argv, int assignment_cnt,
  7735. char **argv_expanded)
  7736. {
  7737. const struct built_in_command *x;
  7738. struct variable **sv_shadowed;
  7739. char **new_env;
  7740. IF_HUSH_COMMAND(char opt_vV = 0;)
  7741. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7742. new_env = expand_assignments(argv, assignment_cnt);
  7743. dump_cmd_in_x_mode(new_env);
  7744. if (!argv[assignment_cnt]) {
  7745. /* Case when we are here: ... | var=val | ...
  7746. * (note that we do not exit early, i.e., do not optimize out
  7747. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7748. */
  7749. free_strings(new_env);
  7750. _exit(EXIT_SUCCESS);
  7751. }
  7752. sv_shadowed = G.shadowed_vars_pp;
  7753. #if BB_MMU
  7754. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7755. #else
  7756. G.shadowed_vars_pp = &nommu_save->old_vars;
  7757. G.var_nest_level++;
  7758. #endif
  7759. set_vars_and_save_old(new_env);
  7760. G.shadowed_vars_pp = sv_shadowed;
  7761. if (argv_expanded) {
  7762. argv = argv_expanded;
  7763. } else {
  7764. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7765. #if !BB_MMU
  7766. nommu_save->argv = argv;
  7767. #endif
  7768. }
  7769. dump_cmd_in_x_mode(argv);
  7770. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7771. if (strchr(argv[0], '/') != NULL)
  7772. goto skip;
  7773. #endif
  7774. #if ENABLE_HUSH_FUNCTIONS
  7775. /* Check if the command matches any functions (this goes before bltins) */
  7776. funcp = find_function(argv[0]);
  7777. if (funcp)
  7778. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7779. #endif
  7780. #if ENABLE_HUSH_COMMAND
  7781. /* "command BAR": run BAR without looking it up among functions
  7782. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7783. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7784. */
  7785. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7786. char *p;
  7787. argv++;
  7788. p = *argv;
  7789. if (p[0] != '-' || !p[1])
  7790. continue; /* bash allows "command command command [-OPT] BAR" */
  7791. for (;;) {
  7792. p++;
  7793. switch (*p) {
  7794. case '\0':
  7795. argv++;
  7796. p = *argv;
  7797. if (p[0] != '-' || !p[1])
  7798. goto after_opts;
  7799. continue; /* next arg is also -opts, process it too */
  7800. case 'v':
  7801. case 'V':
  7802. opt_vV = *p;
  7803. continue;
  7804. default:
  7805. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7806. }
  7807. }
  7808. }
  7809. after_opts:
  7810. # if ENABLE_HUSH_FUNCTIONS
  7811. if (opt_vV && find_function(argv[0]))
  7812. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7813. # endif
  7814. #endif
  7815. /* Check if the command matches any of the builtins.
  7816. * Depending on context, this might be redundant. But it's
  7817. * easier to waste a few CPU cycles than it is to figure out
  7818. * if this is one of those cases.
  7819. */
  7820. /* Why "BB_MMU ? :" difference in logic? -
  7821. * On NOMMU, it is more expensive to re-execute shell
  7822. * just in order to run echo or test builtin.
  7823. * It's better to skip it here and run corresponding
  7824. * non-builtin later. */
  7825. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7826. if (x) {
  7827. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7828. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7829. }
  7830. #if ENABLE_FEATURE_SH_STANDALONE
  7831. /* Check if the command matches any busybox applets */
  7832. {
  7833. int a = find_applet_by_name(argv[0]);
  7834. if (a >= 0) {
  7835. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7836. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7837. if (APPLET_IS_NOEXEC(a)) {
  7838. /* Do not leak open fds from opened script files etc.
  7839. * Testcase: interactive "ls -l /proc/self/fd"
  7840. * should not show tty fd open.
  7841. */
  7842. close_saved_fds_and_FILE_fds();
  7843. //FIXME: should also close saved redir fds
  7844. //This casuses test failures in
  7845. //redir_children_should_not_see_saved_fd_2.tests
  7846. //redir_children_should_not_see_saved_fd_3.tests
  7847. //if you replace "busybox find" with just "find" in them
  7848. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7849. switch_off_special_sigs(G.special_sig_mask);
  7850. debug_printf_exec("running applet '%s'\n", argv[0]);
  7851. run_noexec_applet_and_exit(a, argv[0], argv);
  7852. }
  7853. # endif
  7854. /* Re-exec ourselves */
  7855. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7856. /* Don't propagate SIG_IGN to the child */
  7857. if (SPECIAL_JOBSTOP_SIGS != 0)
  7858. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7859. execv(bb_busybox_exec_path, argv);
  7860. /* If they called chroot or otherwise made the binary no longer
  7861. * executable, fall through */
  7862. }
  7863. }
  7864. #endif
  7865. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7866. skip:
  7867. #endif
  7868. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7869. execvp_or_die(argv);
  7870. }
  7871. /* Called after [v]fork() in run_pipe
  7872. */
  7873. static void pseudo_exec(nommu_save_t *nommu_save,
  7874. struct command *command,
  7875. char **argv_expanded) NORETURN;
  7876. static void pseudo_exec(nommu_save_t *nommu_save,
  7877. struct command *command,
  7878. char **argv_expanded)
  7879. {
  7880. #if ENABLE_HUSH_FUNCTIONS
  7881. if (command->cmd_type == CMD_FUNCDEF) {
  7882. /* Ignore funcdefs in pipes:
  7883. * true | f() { cmd }
  7884. */
  7885. _exit(0);
  7886. }
  7887. #endif
  7888. if (command->argv) {
  7889. pseudo_exec_argv(nommu_save, command->argv,
  7890. command->assignment_cnt, argv_expanded);
  7891. }
  7892. if (command->group) {
  7893. /* Cases when we are here:
  7894. * ( list )
  7895. * { list } &
  7896. * ... | ( list ) | ...
  7897. * ... | { list } | ...
  7898. */
  7899. #if BB_MMU
  7900. int rcode;
  7901. debug_printf_exec("pseudo_exec: run_list\n");
  7902. reset_traps_to_defaults();
  7903. rcode = run_list(command->group);
  7904. /* OK to leak memory by not calling free_pipe_list,
  7905. * since this process is about to exit */
  7906. _exit(rcode);
  7907. #else
  7908. re_execute_shell(&nommu_save->argv_from_re_execing,
  7909. command->group_as_string,
  7910. G.global_argv[0],
  7911. G.global_argv + 1,
  7912. NULL);
  7913. #endif
  7914. }
  7915. /* Case when we are here: ... | >file */
  7916. debug_printf_exec("pseudo_exec'ed null command\n");
  7917. _exit(EXIT_SUCCESS);
  7918. }
  7919. #if ENABLE_HUSH_JOB
  7920. static const char *get_cmdtext(struct pipe *pi)
  7921. {
  7922. char **argv;
  7923. char *p;
  7924. int len;
  7925. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7926. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7927. * On subsequent bg argv is trashed, but we won't use it */
  7928. if (pi->cmdtext)
  7929. return pi->cmdtext;
  7930. argv = pi->cmds[0].argv;
  7931. if (!argv) {
  7932. pi->cmdtext = xzalloc(1);
  7933. return pi->cmdtext;
  7934. }
  7935. len = 0;
  7936. do {
  7937. len += strlen(*argv) + 1;
  7938. } while (*++argv);
  7939. p = xmalloc(len);
  7940. pi->cmdtext = p;
  7941. argv = pi->cmds[0].argv;
  7942. do {
  7943. p = stpcpy(p, *argv);
  7944. *p++ = ' ';
  7945. } while (*++argv);
  7946. p[-1] = '\0';
  7947. return pi->cmdtext;
  7948. }
  7949. static void remove_job_from_table(struct pipe *pi)
  7950. {
  7951. struct pipe *prev_pipe;
  7952. if (pi == G.job_list) {
  7953. G.job_list = pi->next;
  7954. } else {
  7955. prev_pipe = G.job_list;
  7956. while (prev_pipe->next != pi)
  7957. prev_pipe = prev_pipe->next;
  7958. prev_pipe->next = pi->next;
  7959. }
  7960. G.last_jobid = 0;
  7961. if (G.job_list)
  7962. G.last_jobid = G.job_list->jobid;
  7963. }
  7964. static void delete_finished_job(struct pipe *pi)
  7965. {
  7966. remove_job_from_table(pi);
  7967. free_pipe(pi);
  7968. }
  7969. static void clean_up_last_dead_job(void)
  7970. {
  7971. if (G.job_list && !G.job_list->alive_cmds)
  7972. delete_finished_job(G.job_list);
  7973. }
  7974. static void insert_job_into_table(struct pipe *pi)
  7975. {
  7976. struct pipe *job, **jobp;
  7977. int i;
  7978. clean_up_last_dead_job();
  7979. /* Find the end of the list, and find next job ID to use */
  7980. i = 0;
  7981. jobp = &G.job_list;
  7982. while ((job = *jobp) != NULL) {
  7983. if (job->jobid > i)
  7984. i = job->jobid;
  7985. jobp = &job->next;
  7986. }
  7987. pi->jobid = i + 1;
  7988. /* Create a new job struct at the end */
  7989. job = *jobp = xmemdup(pi, sizeof(*pi));
  7990. job->next = NULL;
  7991. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7992. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7993. for (i = 0; i < pi->num_cmds; i++) {
  7994. job->cmds[i].pid = pi->cmds[i].pid;
  7995. /* all other fields are not used and stay zero */
  7996. }
  7997. job->cmdtext = xstrdup(get_cmdtext(pi));
  7998. if (G_interactive_fd)
  7999. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8000. G.last_jobid = job->jobid;
  8001. }
  8002. #endif /* JOB */
  8003. static int job_exited_or_stopped(struct pipe *pi)
  8004. {
  8005. int rcode, i;
  8006. if (pi->alive_cmds != pi->stopped_cmds)
  8007. return -1;
  8008. /* All processes in fg pipe have exited or stopped */
  8009. rcode = 0;
  8010. i = pi->num_cmds;
  8011. while (--i >= 0) {
  8012. rcode = pi->cmds[i].cmd_exitcode;
  8013. /* usually last process gives overall exitstatus,
  8014. * but with "set -o pipefail", last *failed* process does */
  8015. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8016. break;
  8017. }
  8018. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8019. return rcode;
  8020. }
  8021. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8022. {
  8023. #if ENABLE_HUSH_JOB
  8024. struct pipe *pi;
  8025. #endif
  8026. int i, dead;
  8027. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8028. #if DEBUG_JOBS
  8029. if (WIFSTOPPED(status))
  8030. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8031. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8032. if (WIFSIGNALED(status))
  8033. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8034. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8035. if (WIFEXITED(status))
  8036. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8037. childpid, WEXITSTATUS(status));
  8038. #endif
  8039. /* Were we asked to wait for a fg pipe? */
  8040. if (fg_pipe) {
  8041. i = fg_pipe->num_cmds;
  8042. while (--i >= 0) {
  8043. int rcode;
  8044. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8045. if (fg_pipe->cmds[i].pid != childpid)
  8046. continue;
  8047. if (dead) {
  8048. int ex;
  8049. fg_pipe->cmds[i].pid = 0;
  8050. fg_pipe->alive_cmds--;
  8051. ex = WEXITSTATUS(status);
  8052. /* bash prints killer signal's name for *last*
  8053. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8054. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8055. */
  8056. if (WIFSIGNALED(status)) {
  8057. int sig = WTERMSIG(status);
  8058. if (i == fg_pipe->num_cmds-1)
  8059. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8060. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8061. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8062. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8063. * Maybe we need to use sig | 128? */
  8064. ex = sig + 128;
  8065. }
  8066. fg_pipe->cmds[i].cmd_exitcode = ex;
  8067. } else {
  8068. fg_pipe->stopped_cmds++;
  8069. }
  8070. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8071. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8072. rcode = job_exited_or_stopped(fg_pipe);
  8073. if (rcode >= 0) {
  8074. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8075. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8076. * and "killall -STOP cat" */
  8077. if (G_interactive_fd) {
  8078. #if ENABLE_HUSH_JOB
  8079. if (fg_pipe->alive_cmds != 0)
  8080. insert_job_into_table(fg_pipe);
  8081. #endif
  8082. return rcode;
  8083. }
  8084. if (fg_pipe->alive_cmds == 0)
  8085. return rcode;
  8086. }
  8087. /* There are still running processes in the fg_pipe */
  8088. return -1;
  8089. }
  8090. /* It wasn't in fg_pipe, look for process in bg pipes */
  8091. }
  8092. #if ENABLE_HUSH_JOB
  8093. /* We were asked to wait for bg or orphaned children */
  8094. /* No need to remember exitcode in this case */
  8095. for (pi = G.job_list; pi; pi = pi->next) {
  8096. for (i = 0; i < pi->num_cmds; i++) {
  8097. if (pi->cmds[i].pid == childpid)
  8098. goto found_pi_and_prognum;
  8099. }
  8100. }
  8101. /* Happens when shell is used as init process (init=/bin/sh) */
  8102. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8103. return -1; /* this wasn't a process from fg_pipe */
  8104. found_pi_and_prognum:
  8105. if (dead) {
  8106. /* child exited */
  8107. int rcode = WEXITSTATUS(status);
  8108. if (WIFSIGNALED(status))
  8109. rcode = 128 + WTERMSIG(status);
  8110. pi->cmds[i].cmd_exitcode = rcode;
  8111. if (G.last_bg_pid == pi->cmds[i].pid)
  8112. G.last_bg_pid_exitcode = rcode;
  8113. pi->cmds[i].pid = 0;
  8114. pi->alive_cmds--;
  8115. if (!pi->alive_cmds) {
  8116. #if ENABLE_HUSH_BASH_COMPAT
  8117. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8118. #endif
  8119. if (G_interactive_fd) {
  8120. printf(JOB_STATUS_FORMAT, pi->jobid,
  8121. "Done", pi->cmdtext);
  8122. delete_finished_job(pi);
  8123. } else {
  8124. /*
  8125. * bash deletes finished jobs from job table only in interactive mode,
  8126. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8127. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8128. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8129. * We only retain one "dead" job, if it's the single job on the list.
  8130. * This covers most of real-world scenarios where this is useful.
  8131. */
  8132. if (pi != G.job_list)
  8133. delete_finished_job(pi);
  8134. }
  8135. }
  8136. } else {
  8137. /* child stopped */
  8138. pi->stopped_cmds++;
  8139. }
  8140. #endif
  8141. return -1; /* this wasn't a process from fg_pipe */
  8142. }
  8143. /* Check to see if any processes have exited -- if they have,
  8144. * figure out why and see if a job has completed.
  8145. *
  8146. * If non-NULL fg_pipe: wait for its completion or stop.
  8147. * Return its exitcode or zero if stopped.
  8148. *
  8149. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8150. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8151. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8152. * or 0 if no children changed status.
  8153. *
  8154. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8155. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8156. * or 0 if no children changed status.
  8157. */
  8158. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8159. {
  8160. int attributes;
  8161. int status;
  8162. int rcode = 0;
  8163. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8164. attributes = WUNTRACED;
  8165. if (fg_pipe == NULL)
  8166. attributes |= WNOHANG;
  8167. errno = 0;
  8168. #if ENABLE_HUSH_FAST
  8169. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8170. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8171. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8172. /* There was neither fork nor SIGCHLD since last waitpid */
  8173. /* Avoid doing waitpid syscall if possible */
  8174. if (!G.we_have_children) {
  8175. errno = ECHILD;
  8176. return -1;
  8177. }
  8178. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8179. /* We have children, but they did not exit
  8180. * or stop yet (we saw no SIGCHLD) */
  8181. return 0;
  8182. }
  8183. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8184. }
  8185. #endif
  8186. /* Do we do this right?
  8187. * bash-3.00# sleep 20 | false
  8188. * <ctrl-Z pressed>
  8189. * [3]+ Stopped sleep 20 | false
  8190. * bash-3.00# echo $?
  8191. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8192. * [hush 1.14.0: yes we do it right]
  8193. */
  8194. while (1) {
  8195. pid_t childpid;
  8196. #if ENABLE_HUSH_FAST
  8197. int i;
  8198. i = G.count_SIGCHLD;
  8199. #endif
  8200. childpid = waitpid(-1, &status, attributes);
  8201. if (childpid <= 0) {
  8202. if (childpid && errno != ECHILD)
  8203. bb_simple_perror_msg("waitpid");
  8204. #if ENABLE_HUSH_FAST
  8205. else { /* Until next SIGCHLD, waitpid's are useless */
  8206. G.we_have_children = (childpid == 0);
  8207. G.handled_SIGCHLD = i;
  8208. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8209. }
  8210. #endif
  8211. /* ECHILD (no children), or 0 (no change in children status) */
  8212. rcode = childpid;
  8213. break;
  8214. }
  8215. rcode = process_wait_result(fg_pipe, childpid, status);
  8216. if (rcode >= 0) {
  8217. /* fg_pipe exited or stopped */
  8218. break;
  8219. }
  8220. if (childpid == waitfor_pid) { /* "wait PID" */
  8221. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8222. rcode = WEXITSTATUS(status);
  8223. if (WIFSIGNALED(status))
  8224. rcode = 128 + WTERMSIG(status);
  8225. if (WIFSTOPPED(status))
  8226. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8227. rcode = 128 + WSTOPSIG(status);
  8228. rcode++;
  8229. break; /* "wait PID" called us, give it exitcode+1 */
  8230. }
  8231. #if ENABLE_HUSH_BASH_COMPAT
  8232. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8233. && G.dead_job_exitcode >= 0 /* some job did finish */
  8234. ) {
  8235. debug_printf_exec("waitfor_pid:-1\n");
  8236. rcode = G.dead_job_exitcode + 1;
  8237. break;
  8238. }
  8239. #endif
  8240. /* This wasn't one of our processes, or */
  8241. /* fg_pipe still has running processes, do waitpid again */
  8242. } /* while (waitpid succeeds)... */
  8243. return rcode;
  8244. }
  8245. #if ENABLE_HUSH_JOB
  8246. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8247. {
  8248. pid_t p;
  8249. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8250. if (G_saved_tty_pgrp) {
  8251. /* Job finished, move the shell to the foreground */
  8252. p = getpgrp(); /* our process group id */
  8253. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8254. tcsetpgrp(G_interactive_fd, p);
  8255. }
  8256. return rcode;
  8257. }
  8258. #endif
  8259. /* Start all the jobs, but don't wait for anything to finish.
  8260. * See checkjobs().
  8261. *
  8262. * Return code is normally -1, when the caller has to wait for children
  8263. * to finish to determine the exit status of the pipe. If the pipe
  8264. * is a simple builtin command, however, the action is done by the
  8265. * time run_pipe returns, and the exit code is provided as the
  8266. * return value.
  8267. *
  8268. * Returns -1 only if started some children. IOW: we have to
  8269. * mask out retvals of builtins etc with 0xff!
  8270. *
  8271. * The only case when we do not need to [v]fork is when the pipe
  8272. * is single, non-backgrounded, non-subshell command. Examples:
  8273. * cmd ; ... { list } ; ...
  8274. * cmd && ... { list } && ...
  8275. * cmd || ... { list } || ...
  8276. * If it is, then we can run cmd as a builtin, NOFORK,
  8277. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8278. * with run_list. If it isn't one of these, we fork and exec cmd.
  8279. *
  8280. * Cases when we must fork:
  8281. * non-single: cmd | cmd
  8282. * backgrounded: cmd & { list } &
  8283. * subshell: ( list ) [&]
  8284. */
  8285. #if !ENABLE_HUSH_MODE_X
  8286. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8287. redirect_and_varexp_helper(command, sqp)
  8288. #endif
  8289. static int redirect_and_varexp_helper(
  8290. struct command *command,
  8291. struct squirrel **sqp,
  8292. char **argv_expanded)
  8293. {
  8294. /* Assignments occur before redirects. Try:
  8295. * a=`sleep 1` sleep 2 3>/qwe/rty
  8296. */
  8297. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8298. dump_cmd_in_x_mode(new_env);
  8299. dump_cmd_in_x_mode(argv_expanded);
  8300. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8301. set_vars_and_save_old(new_env);
  8302. return setup_redirects(command, sqp);
  8303. }
  8304. static NOINLINE int run_pipe(struct pipe *pi)
  8305. {
  8306. static const char *const null_ptr = NULL;
  8307. int cmd_no;
  8308. int next_infd;
  8309. struct command *command;
  8310. char **argv_expanded;
  8311. char **argv;
  8312. struct squirrel *squirrel = NULL;
  8313. int rcode;
  8314. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8315. debug_enter();
  8316. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8317. * Result should be 3 lines: q w e, qwe, q w e
  8318. */
  8319. if (G.ifs_whitespace != G.ifs)
  8320. free(G.ifs_whitespace);
  8321. G.ifs = get_local_var_value("IFS");
  8322. if (G.ifs) {
  8323. char *p;
  8324. G.ifs_whitespace = (char*)G.ifs;
  8325. p = skip_whitespace(G.ifs);
  8326. if (*p) {
  8327. /* Not all $IFS is whitespace */
  8328. char *d;
  8329. int len = p - G.ifs;
  8330. p = skip_non_whitespace(p);
  8331. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8332. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8333. while (*p) {
  8334. if (isspace(*p))
  8335. *d++ = *p;
  8336. p++;
  8337. }
  8338. *d = '\0';
  8339. }
  8340. } else {
  8341. G.ifs = defifs;
  8342. G.ifs_whitespace = (char*)G.ifs;
  8343. }
  8344. IF_HUSH_JOB(pi->pgrp = -1;)
  8345. pi->stopped_cmds = 0;
  8346. command = &pi->cmds[0];
  8347. argv_expanded = NULL;
  8348. if (pi->num_cmds != 1
  8349. || pi->followup == PIPE_BG
  8350. || command->cmd_type == CMD_SUBSHELL
  8351. ) {
  8352. goto must_fork;
  8353. }
  8354. pi->alive_cmds = 1;
  8355. debug_printf_exec(": group:%p argv:'%s'\n",
  8356. command->group, command->argv ? command->argv[0] : "NONE");
  8357. if (command->group) {
  8358. #if ENABLE_HUSH_FUNCTIONS
  8359. if (command->cmd_type == CMD_FUNCDEF) {
  8360. /* "executing" func () { list } */
  8361. struct function *funcp;
  8362. funcp = new_function(command->argv[0]);
  8363. /* funcp->name is already set to argv[0] */
  8364. funcp->body = command->group;
  8365. # if !BB_MMU
  8366. funcp->body_as_string = command->group_as_string;
  8367. command->group_as_string = NULL;
  8368. # endif
  8369. command->group = NULL;
  8370. command->argv[0] = NULL;
  8371. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8372. funcp->parent_cmd = command;
  8373. command->child_func = funcp;
  8374. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8375. debug_leave();
  8376. return EXIT_SUCCESS;
  8377. }
  8378. #endif
  8379. /* { list } */
  8380. debug_printf_exec("non-subshell group\n");
  8381. rcode = 1; /* exitcode if redir failed */
  8382. if (setup_redirects(command, &squirrel) == 0) {
  8383. debug_printf_exec(": run_list\n");
  8384. //FIXME: we need to pass squirrel down into run_list()
  8385. //for SH_STANDALONE case, or else this construct:
  8386. // { find /proc/self/fd; true; } >FILE; cmd2
  8387. //has no way of closing saved fd#1 for "find",
  8388. //and in SH_STANDALONE mode, "find" is not execed,
  8389. //therefore CLOEXEC on saved fd does not help.
  8390. rcode = run_list(command->group) & 0xff;
  8391. }
  8392. restore_redirects(squirrel);
  8393. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8394. debug_leave();
  8395. debug_printf_exec("run_pipe: return %d\n", rcode);
  8396. return rcode;
  8397. }
  8398. argv = command->argv ? command->argv : (char **) &null_ptr;
  8399. {
  8400. const struct built_in_command *x;
  8401. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8402. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8403. struct variable **sv_shadowed;
  8404. struct variable *old_vars;
  8405. #if ENABLE_HUSH_LINENO_VAR
  8406. G.execute_lineno = command->lineno;
  8407. #endif
  8408. if (argv[command->assignment_cnt] == NULL) {
  8409. /* Assignments, but no command.
  8410. * Ensure redirects take effect (that is, create files).
  8411. * Try "a=t >file"
  8412. */
  8413. unsigned i;
  8414. G.expand_exitcode = 0;
  8415. only_assignments:
  8416. rcode = setup_redirects(command, &squirrel);
  8417. restore_redirects(squirrel);
  8418. /* Set shell variables */
  8419. i = 0;
  8420. while (i < command->assignment_cnt) {
  8421. char *p = expand_string_to_string(argv[i],
  8422. EXP_FLAG_ESC_GLOB_CHARS,
  8423. /*unbackslash:*/ 1
  8424. );
  8425. #if ENABLE_HUSH_MODE_X
  8426. if (G_x_mode) {
  8427. char *eq;
  8428. if (i == 0)
  8429. x_mode_prefix();
  8430. x_mode_addchr(' ');
  8431. eq = strchrnul(p, '=');
  8432. if (*eq) eq++;
  8433. x_mode_addblock(p, (eq - p));
  8434. x_mode_print_optionally_squoted(eq);
  8435. x_mode_flush();
  8436. }
  8437. #endif
  8438. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8439. if (set_local_var(p, /*flag:*/ 0)) {
  8440. /* assignment to readonly var / putenv error? */
  8441. rcode = 1;
  8442. }
  8443. i++;
  8444. }
  8445. /* Redirect error sets $? to 1. Otherwise,
  8446. * if evaluating assignment value set $?, retain it.
  8447. * Else, clear $?:
  8448. * false; q=`exit 2`; echo $? - should print 2
  8449. * false; x=1; echo $? - should print 0
  8450. * Because of the 2nd case, we can't just use G.last_exitcode.
  8451. */
  8452. if (rcode == 0)
  8453. rcode = G.expand_exitcode;
  8454. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8455. debug_leave();
  8456. debug_printf_exec("run_pipe: return %d\n", rcode);
  8457. return rcode;
  8458. }
  8459. /* Expand the rest into (possibly) many strings each */
  8460. #if defined(CMD_SINGLEWORD_NOGLOB)
  8461. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8462. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8463. else
  8464. #endif
  8465. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8466. /* If someone gives us an empty string: `cmd with empty output` */
  8467. if (!argv_expanded[0]) {
  8468. free(argv_expanded);
  8469. /* `false` still has to set exitcode 1 */
  8470. G.expand_exitcode = G.last_exitcode;
  8471. goto only_assignments;
  8472. }
  8473. old_vars = NULL;
  8474. sv_shadowed = G.shadowed_vars_pp;
  8475. /* Check if argv[0] matches any functions (this goes before bltins) */
  8476. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8477. IF_HUSH_FUNCTIONS(x = NULL;)
  8478. IF_HUSH_FUNCTIONS(if (!funcp))
  8479. x = find_builtin(argv_expanded[0]);
  8480. if (x || funcp) {
  8481. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8482. debug_printf("exec with redirects only\n");
  8483. /*
  8484. * Variable assignments are executed, but then "forgotten":
  8485. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8486. * sleeps, but prints nothing.
  8487. */
  8488. enter_var_nest_level();
  8489. G.shadowed_vars_pp = &old_vars;
  8490. rcode = redirect_and_varexp_helper(command,
  8491. /*squirrel:*/ ERR_PTR,
  8492. argv_expanded
  8493. );
  8494. G.shadowed_vars_pp = sv_shadowed;
  8495. /* rcode=1 can be if redir file can't be opened */
  8496. goto clean_up_and_ret1;
  8497. }
  8498. /* Bump var nesting, or this will leak exported $a:
  8499. * a=b true; env | grep ^a=
  8500. */
  8501. enter_var_nest_level();
  8502. /* Collect all variables "shadowed" by helper
  8503. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8504. * into old_vars list:
  8505. */
  8506. G.shadowed_vars_pp = &old_vars;
  8507. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8508. if (rcode == 0) {
  8509. if (!funcp) {
  8510. /* Do not collect *to old_vars list* vars shadowed
  8511. * by e.g. "local VAR" builtin (collect them
  8512. * in the previously nested list instead):
  8513. * don't want them to be restored immediately
  8514. * after "local" completes.
  8515. */
  8516. G.shadowed_vars_pp = sv_shadowed;
  8517. debug_printf_exec(": builtin '%s' '%s'...\n",
  8518. x->b_cmd, argv_expanded[1]);
  8519. fflush_all();
  8520. rcode = x->b_function(argv_expanded) & 0xff;
  8521. fflush_all();
  8522. }
  8523. #if ENABLE_HUSH_FUNCTIONS
  8524. else {
  8525. debug_printf_exec(": function '%s' '%s'...\n",
  8526. funcp->name, argv_expanded[1]);
  8527. rcode = run_function(funcp, argv_expanded) & 0xff;
  8528. /*
  8529. * But do collect *to old_vars list* vars shadowed
  8530. * within function execution. To that end, restore
  8531. * this pointer _after_ function run:
  8532. */
  8533. G.shadowed_vars_pp = sv_shadowed;
  8534. }
  8535. #endif
  8536. }
  8537. } else
  8538. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8539. int n = find_applet_by_name(argv_expanded[0]);
  8540. if (n < 0 || !APPLET_IS_NOFORK(n))
  8541. goto must_fork;
  8542. enter_var_nest_level();
  8543. /* Collect all variables "shadowed" by helper into old_vars list */
  8544. G.shadowed_vars_pp = &old_vars;
  8545. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8546. G.shadowed_vars_pp = sv_shadowed;
  8547. if (rcode == 0) {
  8548. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8549. argv_expanded[0], argv_expanded[1]);
  8550. /*
  8551. * Note: signals (^C) can't interrupt here.
  8552. * We remember them and they will be acted upon
  8553. * after applet returns.
  8554. * This makes applets which can run for a long time
  8555. * and/or wait for user input ineligible for NOFORK:
  8556. * for example, "yes" or "rm" (rm -i waits for input).
  8557. */
  8558. rcode = run_nofork_applet(n, argv_expanded);
  8559. }
  8560. } else
  8561. goto must_fork;
  8562. restore_redirects(squirrel);
  8563. clean_up_and_ret1:
  8564. leave_var_nest_level();
  8565. add_vars(old_vars);
  8566. /*
  8567. * Try "usleep 99999999" + ^C + "echo $?"
  8568. * with FEATURE_SH_NOFORK=y.
  8569. */
  8570. if (!funcp) {
  8571. /* It was builtin or nofork.
  8572. * if this would be a real fork/execed program,
  8573. * it should have died if a fatal sig was received.
  8574. * But OTOH, there was no separate process,
  8575. * the sig was sent to _shell_, not to non-existing
  8576. * child.
  8577. * Let's just handle ^C only, this one is obvious:
  8578. * we aren't ok with exitcode 0 when ^C was pressed
  8579. * during builtin/nofork.
  8580. */
  8581. if (sigismember(&G.pending_set, SIGINT))
  8582. rcode = 128 + SIGINT;
  8583. }
  8584. free(argv_expanded);
  8585. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8586. debug_leave();
  8587. debug_printf_exec("run_pipe return %d\n", rcode);
  8588. return rcode;
  8589. }
  8590. must_fork:
  8591. /* NB: argv_expanded may already be created, and that
  8592. * might include `cmd` runs! Do not rerun it! We *must*
  8593. * use argv_expanded if it's non-NULL */
  8594. /* Going to fork a child per each pipe member */
  8595. pi->alive_cmds = 0;
  8596. next_infd = 0;
  8597. cmd_no = 0;
  8598. while (cmd_no < pi->num_cmds) {
  8599. struct fd_pair pipefds;
  8600. #if !BB_MMU
  8601. int sv_var_nest_level = G.var_nest_level;
  8602. volatile nommu_save_t nommu_save;
  8603. nommu_save.old_vars = NULL;
  8604. nommu_save.argv = NULL;
  8605. nommu_save.argv_from_re_execing = NULL;
  8606. #endif
  8607. command = &pi->cmds[cmd_no];
  8608. cmd_no++;
  8609. if (command->argv) {
  8610. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8611. command->argv[0], command->argv[1]);
  8612. } else {
  8613. debug_printf_exec(": pipe member with no argv\n");
  8614. }
  8615. /* pipes are inserted between pairs of commands */
  8616. pipefds.rd = 0;
  8617. pipefds.wr = 1;
  8618. if (cmd_no < pi->num_cmds)
  8619. xpiped_pair(pipefds);
  8620. #if ENABLE_HUSH_LINENO_VAR
  8621. G.execute_lineno = command->lineno;
  8622. #endif
  8623. command->pid = BB_MMU ? fork() : vfork();
  8624. if (!command->pid) { /* child */
  8625. #if ENABLE_HUSH_JOB
  8626. disable_restore_tty_pgrp_on_exit();
  8627. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8628. /* Every child adds itself to new process group
  8629. * with pgid == pid_of_first_child_in_pipe */
  8630. if (G.run_list_level == 1 && G_interactive_fd) {
  8631. pid_t pgrp;
  8632. pgrp = pi->pgrp;
  8633. if (pgrp < 0) /* true for 1st process only */
  8634. pgrp = getpid();
  8635. if (setpgid(0, pgrp) == 0
  8636. && pi->followup != PIPE_BG
  8637. && G_saved_tty_pgrp /* we have ctty */
  8638. ) {
  8639. /* We do it in *every* child, not just first,
  8640. * to avoid races */
  8641. tcsetpgrp(G_interactive_fd, pgrp);
  8642. }
  8643. }
  8644. #endif
  8645. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8646. /* 1st cmd in backgrounded pipe
  8647. * should have its stdin /dev/null'ed */
  8648. close(0);
  8649. if (open(bb_dev_null, O_RDONLY))
  8650. xopen("/", O_RDONLY);
  8651. } else {
  8652. xmove_fd(next_infd, 0);
  8653. }
  8654. xmove_fd(pipefds.wr, 1);
  8655. if (pipefds.rd > 1)
  8656. close(pipefds.rd);
  8657. /* Like bash, explicit redirects override pipes,
  8658. * and the pipe fd (fd#1) is available for dup'ing:
  8659. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8660. * of cmd1 goes into pipe.
  8661. */
  8662. if (setup_redirects(command, NULL)) {
  8663. /* Happens when redir file can't be opened:
  8664. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8665. * FOO
  8666. * hush: can't open '/qwe/rty': No such file or directory
  8667. * BAZ
  8668. * (echo BAR is not executed, it hits _exit(1) below)
  8669. */
  8670. _exit(1);
  8671. }
  8672. /* Stores to nommu_save list of env vars putenv'ed
  8673. * (NOMMU, on MMU we don't need that) */
  8674. /* cast away volatility... */
  8675. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8676. /* pseudo_exec() does not return */
  8677. }
  8678. /* parent or error */
  8679. #if ENABLE_HUSH_FAST
  8680. G.count_SIGCHLD++;
  8681. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8682. #endif
  8683. enable_restore_tty_pgrp_on_exit();
  8684. #if !BB_MMU
  8685. /* Clean up after vforked child */
  8686. free(nommu_save.argv);
  8687. free(nommu_save.argv_from_re_execing);
  8688. G.var_nest_level = sv_var_nest_level;
  8689. remove_nested_vars();
  8690. add_vars(nommu_save.old_vars);
  8691. #endif
  8692. free(argv_expanded);
  8693. argv_expanded = NULL;
  8694. if (command->pid < 0) { /* [v]fork failed */
  8695. /* Clearly indicate, was it fork or vfork */
  8696. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8697. } else {
  8698. pi->alive_cmds++;
  8699. #if ENABLE_HUSH_JOB
  8700. /* Second and next children need to know pid of first one */
  8701. if (pi->pgrp < 0)
  8702. pi->pgrp = command->pid;
  8703. #endif
  8704. }
  8705. if (cmd_no > 1)
  8706. close(next_infd);
  8707. if (cmd_no < pi->num_cmds)
  8708. close(pipefds.wr);
  8709. /* Pass read (output) pipe end to next iteration */
  8710. next_infd = pipefds.rd;
  8711. }
  8712. if (!pi->alive_cmds) {
  8713. debug_leave();
  8714. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8715. return 1;
  8716. }
  8717. debug_leave();
  8718. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8719. return -1;
  8720. }
  8721. /* NB: called by pseudo_exec, and therefore must not modify any
  8722. * global data until exec/_exit (we can be a child after vfork!) */
  8723. static int run_list(struct pipe *pi)
  8724. {
  8725. #if ENABLE_HUSH_CASE
  8726. char *case_word = NULL;
  8727. #endif
  8728. #if ENABLE_HUSH_LOOPS
  8729. struct pipe *loop_top = NULL;
  8730. char **for_lcur = NULL;
  8731. char **for_list = NULL;
  8732. #endif
  8733. smallint last_followup;
  8734. smalluint rcode;
  8735. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8736. smalluint cond_code = 0;
  8737. #else
  8738. enum { cond_code = 0 };
  8739. #endif
  8740. #if HAS_KEYWORDS
  8741. smallint rword; /* RES_foo */
  8742. smallint last_rword; /* ditto */
  8743. #endif
  8744. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8745. debug_enter();
  8746. #if ENABLE_HUSH_LOOPS
  8747. /* Check syntax for "for" */
  8748. {
  8749. struct pipe *cpipe;
  8750. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8751. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8752. continue;
  8753. /* current word is FOR or IN (BOLD in comments below) */
  8754. if (cpipe->next == NULL) {
  8755. syntax_error("malformed for");
  8756. debug_leave();
  8757. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8758. return 1;
  8759. }
  8760. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8761. if (cpipe->next->res_word == RES_DO)
  8762. continue;
  8763. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8764. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8765. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8766. ) {
  8767. syntax_error("malformed for");
  8768. debug_leave();
  8769. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8770. return 1;
  8771. }
  8772. }
  8773. }
  8774. #endif
  8775. /* Past this point, all code paths should jump to ret: label
  8776. * in order to return, no direct "return" statements please.
  8777. * This helps to ensure that no memory is leaked. */
  8778. #if ENABLE_HUSH_JOB
  8779. G.run_list_level++;
  8780. #endif
  8781. #if HAS_KEYWORDS
  8782. rword = RES_NONE;
  8783. last_rword = RES_XXXX;
  8784. #endif
  8785. last_followup = PIPE_SEQ;
  8786. rcode = G.last_exitcode;
  8787. /* Go through list of pipes, (maybe) executing them. */
  8788. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8789. int r;
  8790. int sv_errexit_depth;
  8791. if (G.flag_SIGINT)
  8792. break;
  8793. if (G_flag_return_in_progress == 1)
  8794. break;
  8795. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8796. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8797. rword, cond_code, last_rword);
  8798. sv_errexit_depth = G.errexit_depth;
  8799. if (
  8800. #if ENABLE_HUSH_IF
  8801. rword == RES_IF || rword == RES_ELIF ||
  8802. #endif
  8803. pi->followup != PIPE_SEQ
  8804. ) {
  8805. G.errexit_depth++;
  8806. }
  8807. #if ENABLE_HUSH_LOOPS
  8808. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8809. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8810. ) {
  8811. /* start of a loop: remember where loop starts */
  8812. loop_top = pi;
  8813. G.depth_of_loop++;
  8814. }
  8815. #endif
  8816. /* Still in the same "if...", "then..." or "do..." branch? */
  8817. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8818. if ((rcode == 0 && last_followup == PIPE_OR)
  8819. || (rcode != 0 && last_followup == PIPE_AND)
  8820. ) {
  8821. /* It is "<true> || CMD" or "<false> && CMD"
  8822. * and we should not execute CMD */
  8823. debug_printf_exec("skipped cmd because of || or &&\n");
  8824. last_followup = pi->followup;
  8825. goto dont_check_jobs_but_continue;
  8826. }
  8827. }
  8828. last_followup = pi->followup;
  8829. IF_HAS_KEYWORDS(last_rword = rword;)
  8830. #if ENABLE_HUSH_IF
  8831. if (cond_code) {
  8832. if (rword == RES_THEN) {
  8833. /* if false; then ... fi has exitcode 0! */
  8834. G.last_exitcode = rcode = EXIT_SUCCESS;
  8835. /* "if <false> THEN cmd": skip cmd */
  8836. continue;
  8837. }
  8838. } else {
  8839. if (rword == RES_ELSE || rword == RES_ELIF) {
  8840. /* "if <true> then ... ELSE/ELIF cmd":
  8841. * skip cmd and all following ones */
  8842. break;
  8843. }
  8844. }
  8845. #endif
  8846. #if ENABLE_HUSH_LOOPS
  8847. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8848. if (!for_lcur) {
  8849. /* first loop through for */
  8850. static const char encoded_dollar_at[] ALIGN1 = {
  8851. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8852. }; /* encoded representation of "$@" */
  8853. static const char *const encoded_dollar_at_argv[] = {
  8854. encoded_dollar_at, NULL
  8855. }; /* argv list with one element: "$@" */
  8856. char **vals;
  8857. G.last_exitcode = rcode = EXIT_SUCCESS;
  8858. vals = (char**)encoded_dollar_at_argv;
  8859. if (pi->next->res_word == RES_IN) {
  8860. /* if no variable values after "in" we skip "for" */
  8861. if (!pi->next->cmds[0].argv) {
  8862. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8863. break;
  8864. }
  8865. vals = pi->next->cmds[0].argv;
  8866. } /* else: "for var; do..." -> assume "$@" list */
  8867. /* create list of variable values */
  8868. debug_print_strings("for_list made from", vals);
  8869. for_list = expand_strvec_to_strvec(vals);
  8870. for_lcur = for_list;
  8871. debug_print_strings("for_list", for_list);
  8872. }
  8873. if (!*for_lcur) {
  8874. /* "for" loop is over, clean up */
  8875. free(for_list);
  8876. for_list = NULL;
  8877. for_lcur = NULL;
  8878. break;
  8879. }
  8880. /* Insert next value from for_lcur */
  8881. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8882. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8883. continue;
  8884. }
  8885. if (rword == RES_IN) {
  8886. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8887. }
  8888. if (rword == RES_DONE) {
  8889. continue; /* "done" has no cmds too */
  8890. }
  8891. #endif
  8892. #if ENABLE_HUSH_CASE
  8893. if (rword == RES_CASE) {
  8894. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8895. case_word = expand_string_to_string(pi->cmds->argv[0],
  8896. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8897. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8898. //unbackslash(case_word);
  8899. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8900. continue;
  8901. }
  8902. if (rword == RES_MATCH) {
  8903. char **argv;
  8904. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8905. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8906. break;
  8907. /* all prev words didn't match, does this one match? */
  8908. argv = pi->cmds->argv;
  8909. while (*argv) {
  8910. char *pattern;
  8911. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8912. pattern = expand_string_to_string(*argv,
  8913. EXP_FLAG_ESC_GLOB_CHARS,
  8914. /*unbackslash:*/ 0
  8915. );
  8916. /* TODO: which FNM_xxx flags to use? */
  8917. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8918. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8919. pattern, case_word, cond_code);
  8920. free(pattern);
  8921. if (cond_code == 0) {
  8922. /* match! we will execute this branch */
  8923. free(case_word);
  8924. case_word = NULL; /* make future "word)" stop */
  8925. break;
  8926. }
  8927. argv++;
  8928. }
  8929. continue;
  8930. }
  8931. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8932. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8933. if (cond_code != 0)
  8934. continue; /* not matched yet, skip this pipe */
  8935. }
  8936. if (rword == RES_ESAC) {
  8937. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8938. if (case_word) {
  8939. /* "case" did not match anything: still set $? (to 0) */
  8940. G.last_exitcode = rcode = EXIT_SUCCESS;
  8941. }
  8942. }
  8943. #endif
  8944. /* Just pressing <enter> in shell should check for jobs.
  8945. * OTOH, in non-interactive shell this is useless
  8946. * and only leads to extra job checks */
  8947. if (pi->num_cmds == 0) {
  8948. if (G_interactive_fd)
  8949. goto check_jobs_and_continue;
  8950. continue;
  8951. }
  8952. /* After analyzing all keywords and conditions, we decided
  8953. * to execute this pipe. NB: have to do checkjobs(NULL)
  8954. * after run_pipe to collect any background children,
  8955. * even if list execution is to be stopped. */
  8956. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8957. #if ENABLE_HUSH_LOOPS
  8958. G.flag_break_continue = 0;
  8959. #endif
  8960. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8961. if (r != -1) {
  8962. /* We ran a builtin, function, or group.
  8963. * rcode is already known
  8964. * and we don't need to wait for anything. */
  8965. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8966. G.last_exitcode = rcode;
  8967. check_and_run_traps();
  8968. #if ENABLE_HUSH_LOOPS
  8969. /* Was it "break" or "continue"? */
  8970. if (G.flag_break_continue) {
  8971. smallint fbc = G.flag_break_continue;
  8972. /* We might fall into outer *loop*,
  8973. * don't want to break it too */
  8974. if (loop_top) {
  8975. G.depth_break_continue--;
  8976. if (G.depth_break_continue == 0)
  8977. G.flag_break_continue = 0;
  8978. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8979. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8980. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8981. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8982. break;
  8983. }
  8984. /* "continue": simulate end of loop */
  8985. rword = RES_DONE;
  8986. continue;
  8987. }
  8988. #endif
  8989. if (G_flag_return_in_progress == 1) {
  8990. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8991. break;
  8992. }
  8993. } else if (pi->followup == PIPE_BG) {
  8994. /* What does bash do with attempts to background builtins? */
  8995. /* even bash 3.2 doesn't do that well with nested bg:
  8996. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8997. * I'm NOT treating inner &'s as jobs */
  8998. #if ENABLE_HUSH_JOB
  8999. if (G.run_list_level == 1)
  9000. insert_job_into_table(pi);
  9001. #endif
  9002. /* Last command's pid goes to $! */
  9003. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9004. G.last_bg_pid_exitcode = 0;
  9005. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9006. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9007. rcode = EXIT_SUCCESS;
  9008. goto check_traps;
  9009. } else {
  9010. #if ENABLE_HUSH_JOB
  9011. if (G.run_list_level == 1 && G_interactive_fd) {
  9012. /* Waits for completion, then fg's main shell */
  9013. rcode = checkjobs_and_fg_shell(pi);
  9014. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9015. goto check_traps;
  9016. }
  9017. #endif
  9018. /* This one just waits for completion */
  9019. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9020. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9021. check_traps:
  9022. G.last_exitcode = rcode;
  9023. check_and_run_traps();
  9024. }
  9025. /* Handle "set -e" */
  9026. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9027. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9028. if (G.errexit_depth == 0)
  9029. hush_exit(rcode);
  9030. }
  9031. G.errexit_depth = sv_errexit_depth;
  9032. /* Analyze how result affects subsequent commands */
  9033. #if ENABLE_HUSH_IF
  9034. if (rword == RES_IF || rword == RES_ELIF)
  9035. cond_code = rcode;
  9036. #endif
  9037. check_jobs_and_continue:
  9038. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9039. dont_check_jobs_but_continue: ;
  9040. #if ENABLE_HUSH_LOOPS
  9041. /* Beware of "while false; true; do ..."! */
  9042. if (pi->next
  9043. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9044. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9045. ) {
  9046. if (rword == RES_WHILE) {
  9047. if (rcode) {
  9048. /* "while false; do...done" - exitcode 0 */
  9049. G.last_exitcode = rcode = EXIT_SUCCESS;
  9050. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9051. break;
  9052. }
  9053. }
  9054. if (rword == RES_UNTIL) {
  9055. if (!rcode) {
  9056. debug_printf_exec(": until expr is true: breaking\n");
  9057. break;
  9058. }
  9059. }
  9060. }
  9061. #endif
  9062. } /* for (pi) */
  9063. #if ENABLE_HUSH_JOB
  9064. G.run_list_level--;
  9065. #endif
  9066. #if ENABLE_HUSH_LOOPS
  9067. if (loop_top)
  9068. G.depth_of_loop--;
  9069. free(for_list);
  9070. #endif
  9071. #if ENABLE_HUSH_CASE
  9072. free(case_word);
  9073. #endif
  9074. debug_leave();
  9075. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9076. return rcode;
  9077. }
  9078. /* Select which version we will use */
  9079. static int run_and_free_list(struct pipe *pi)
  9080. {
  9081. int rcode = 0;
  9082. debug_printf_exec("run_and_free_list entered\n");
  9083. if (!G.o_opt[OPT_O_NOEXEC]) {
  9084. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9085. rcode = run_list(pi);
  9086. }
  9087. /* free_pipe_list has the side effect of clearing memory.
  9088. * In the long run that function can be merged with run_list,
  9089. * but doing that now would hobble the debugging effort. */
  9090. free_pipe_list(pi);
  9091. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9092. return rcode;
  9093. }
  9094. static void install_sighandlers(unsigned mask)
  9095. {
  9096. sighandler_t old_handler;
  9097. unsigned sig = 0;
  9098. while ((mask >>= 1) != 0) {
  9099. sig++;
  9100. if (!(mask & 1))
  9101. continue;
  9102. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9103. /* POSIX allows shell to re-enable SIGCHLD
  9104. * even if it was SIG_IGN on entry.
  9105. * Therefore we skip IGN check for it:
  9106. */
  9107. if (sig == SIGCHLD)
  9108. continue;
  9109. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  9110. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  9111. */
  9112. //if (sig == SIGHUP) continue; - TODO?
  9113. if (old_handler == SIG_IGN) {
  9114. /* oops... restore back to IGN, and record this fact */
  9115. install_sighandler(sig, old_handler);
  9116. #if ENABLE_HUSH_TRAP
  9117. if (!G_traps)
  9118. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9119. free(G_traps[sig]);
  9120. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9121. #endif
  9122. }
  9123. }
  9124. }
  9125. /* Called a few times only (or even once if "sh -c") */
  9126. static void install_special_sighandlers(void)
  9127. {
  9128. unsigned mask;
  9129. /* Which signals are shell-special? */
  9130. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9131. if (G_interactive_fd) {
  9132. mask |= SPECIAL_INTERACTIVE_SIGS;
  9133. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9134. mask |= SPECIAL_JOBSTOP_SIGS;
  9135. }
  9136. /* Careful, do not re-install handlers we already installed */
  9137. if (G.special_sig_mask != mask) {
  9138. unsigned diff = mask & ~G.special_sig_mask;
  9139. G.special_sig_mask = mask;
  9140. install_sighandlers(diff);
  9141. }
  9142. }
  9143. #if ENABLE_HUSH_JOB
  9144. /* helper */
  9145. /* Set handlers to restore tty pgrp and exit */
  9146. static void install_fatal_sighandlers(void)
  9147. {
  9148. unsigned mask;
  9149. /* We will restore tty pgrp on these signals */
  9150. mask = 0
  9151. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9152. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9153. + (1 << SIGBUS ) * HUSH_DEBUG
  9154. + (1 << SIGSEGV) * HUSH_DEBUG
  9155. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9156. + (1 << SIGABRT)
  9157. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9158. + (1 << SIGPIPE)
  9159. + (1 << SIGALRM)
  9160. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9161. * if we aren't interactive... but in this case
  9162. * we never want to restore pgrp on exit, and this fn is not called
  9163. */
  9164. /*+ (1 << SIGHUP )*/
  9165. /*+ (1 << SIGTERM)*/
  9166. /*+ (1 << SIGINT )*/
  9167. ;
  9168. G_fatal_sig_mask = mask;
  9169. install_sighandlers(mask);
  9170. }
  9171. #endif
  9172. static int set_mode(int state, char mode, const char *o_opt)
  9173. {
  9174. int idx;
  9175. switch (mode) {
  9176. case 'n':
  9177. G.o_opt[OPT_O_NOEXEC] = state;
  9178. break;
  9179. case 'x':
  9180. IF_HUSH_MODE_X(G_x_mode = state;)
  9181. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9182. break;
  9183. case 'e':
  9184. G.o_opt[OPT_O_ERREXIT] = state;
  9185. break;
  9186. case 'o':
  9187. if (!o_opt) {
  9188. /* "set -o" or "set +o" without parameter.
  9189. * in bash, set -o produces this output:
  9190. * pipefail off
  9191. * and set +o:
  9192. * set +o pipefail
  9193. * We always use the second form.
  9194. */
  9195. const char *p = o_opt_strings;
  9196. idx = 0;
  9197. while (*p) {
  9198. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9199. idx++;
  9200. p += strlen(p) + 1;
  9201. }
  9202. break;
  9203. }
  9204. idx = index_in_strings(o_opt_strings, o_opt);
  9205. if (idx >= 0) {
  9206. G.o_opt[idx] = state;
  9207. break;
  9208. }
  9209. /* fall through to error */
  9210. default:
  9211. return EXIT_FAILURE;
  9212. }
  9213. return EXIT_SUCCESS;
  9214. }
  9215. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9216. int hush_main(int argc, char **argv)
  9217. {
  9218. enum {
  9219. OPT_login = (1 << 0),
  9220. };
  9221. unsigned flags;
  9222. unsigned builtin_argc;
  9223. char **e;
  9224. struct variable *cur_var;
  9225. struct variable *shell_ver;
  9226. INIT_G();
  9227. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9228. G.last_exitcode = EXIT_SUCCESS;
  9229. #if ENABLE_HUSH_FAST
  9230. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9231. #endif
  9232. #if !BB_MMU
  9233. G.argv0_for_re_execing = argv[0];
  9234. #endif
  9235. /* Deal with HUSH_VERSION */
  9236. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9237. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9238. shell_ver = xzalloc(sizeof(*shell_ver));
  9239. shell_ver->flg_export = 1;
  9240. shell_ver->flg_read_only = 1;
  9241. /* Code which handles ${var<op>...} needs writable values for all variables,
  9242. * therefore we xstrdup: */
  9243. shell_ver->varstr = xstrdup(hush_version_str);
  9244. /* Create shell local variables from the values
  9245. * currently living in the environment */
  9246. G.top_var = shell_ver;
  9247. cur_var = G.top_var;
  9248. e = environ;
  9249. if (e) while (*e) {
  9250. char *value = strchr(*e, '=');
  9251. if (value) { /* paranoia */
  9252. cur_var->next = xzalloc(sizeof(*cur_var));
  9253. cur_var = cur_var->next;
  9254. cur_var->varstr = *e;
  9255. cur_var->max_len = strlen(*e);
  9256. cur_var->flg_export = 1;
  9257. }
  9258. e++;
  9259. }
  9260. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9261. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9262. putenv(shell_ver->varstr);
  9263. /* Export PWD */
  9264. set_pwd_var(SETFLAG_EXPORT);
  9265. #if BASH_HOSTNAME_VAR
  9266. /* Set (but not export) HOSTNAME unless already set */
  9267. if (!get_local_var_value("HOSTNAME")) {
  9268. struct utsname uts;
  9269. uname(&uts);
  9270. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9271. }
  9272. #endif
  9273. /* IFS is not inherited from the parent environment */
  9274. set_local_var_from_halves("IFS", defifs);
  9275. if (!get_local_var_value("PATH"))
  9276. set_local_var_from_halves("PATH", bb_default_root_path);
  9277. /* PS1/PS2 are set later, if we determine that we are interactive */
  9278. /* bash also exports SHLVL and _,
  9279. * and sets (but doesn't export) the following variables:
  9280. * BASH=/bin/bash
  9281. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9282. * BASH_VERSION='3.2.0(1)-release'
  9283. * HOSTTYPE=i386
  9284. * MACHTYPE=i386-pc-linux-gnu
  9285. * OSTYPE=linux-gnu
  9286. * PPID=<NNNNN> - we also do it elsewhere
  9287. * EUID=<NNNNN>
  9288. * UID=<NNNNN>
  9289. * GROUPS=()
  9290. * LINES=<NNN>
  9291. * COLUMNS=<NNN>
  9292. * BASH_ARGC=()
  9293. * BASH_ARGV=()
  9294. * BASH_LINENO=()
  9295. * BASH_SOURCE=()
  9296. * DIRSTACK=()
  9297. * PIPESTATUS=([0]="0")
  9298. * HISTFILE=/<xxx>/.bash_history
  9299. * HISTFILESIZE=500
  9300. * HISTSIZE=500
  9301. * MAILCHECK=60
  9302. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9303. * SHELL=/bin/bash
  9304. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9305. * TERM=dumb
  9306. * OPTERR=1
  9307. * OPTIND=1
  9308. * PS4='+ '
  9309. */
  9310. /* Initialize some more globals to non-zero values */
  9311. die_func = restore_ttypgrp_and__exit;
  9312. /* Shell is non-interactive at first. We need to call
  9313. * install_special_sighandlers() if we are going to execute "sh <script>",
  9314. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9315. * If we later decide that we are interactive, we run install_special_sighandlers()
  9316. * in order to intercept (more) signals.
  9317. */
  9318. /* Parse options */
  9319. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9320. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9321. builtin_argc = 0;
  9322. #if NUM_SCRIPTS > 0
  9323. if (argc < 0) {
  9324. optarg = get_script_content(-argc - 1);
  9325. optind = 0;
  9326. argc = string_array_len(argv);
  9327. goto run_script;
  9328. }
  9329. #endif
  9330. while (1) {
  9331. int opt = getopt(argc, argv, "+c:exinsl"
  9332. #if !BB_MMU
  9333. "<:$:R:V:"
  9334. # if ENABLE_HUSH_FUNCTIONS
  9335. "F:"
  9336. # endif
  9337. #endif
  9338. );
  9339. if (opt <= 0)
  9340. break;
  9341. switch (opt) {
  9342. case 'c':
  9343. /* Possibilities:
  9344. * sh ... -c 'script'
  9345. * sh ... -c 'script' ARG0 [ARG1...]
  9346. * On NOMMU, if builtin_argc != 0,
  9347. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9348. * "" needs to be replaced with NULL
  9349. * and BARGV vector fed to builtin function.
  9350. * Note: the form without ARG0 never happens:
  9351. * sh ... -c 'builtin' BARGV... ""
  9352. */
  9353. #if NUM_SCRIPTS > 0
  9354. run_script:
  9355. #endif
  9356. if (!G.root_pid) {
  9357. G.root_pid = getpid();
  9358. G.root_ppid = getppid();
  9359. }
  9360. G.global_argv = argv + optind;
  9361. G.global_argc = argc - optind;
  9362. if (builtin_argc) {
  9363. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9364. const struct built_in_command *x;
  9365. install_special_sighandlers();
  9366. x = find_builtin(optarg);
  9367. if (x) { /* paranoia */
  9368. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9369. G.global_argv += builtin_argc;
  9370. G.global_argv[-1] = NULL; /* replace "" */
  9371. fflush_all();
  9372. G.last_exitcode = x->b_function(argv + optind - 1);
  9373. }
  9374. goto final_return;
  9375. }
  9376. G.opt_c = 1;
  9377. if (!G.global_argv[0]) {
  9378. /* -c 'script' (no params): prevent empty $0 */
  9379. G.global_argv--; /* points to argv[i] of 'script' */
  9380. G.global_argv[0] = argv[0];
  9381. G.global_argc++;
  9382. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9383. install_special_sighandlers();
  9384. parse_and_run_string(optarg);
  9385. goto final_return;
  9386. case 'i':
  9387. /* Well, we cannot just declare interactiveness,
  9388. * we have to have some stuff (ctty, etc) */
  9389. /* G_interactive_fd++; */
  9390. break;
  9391. case 's':
  9392. G.opt_s = 1;
  9393. break;
  9394. case 'l':
  9395. flags |= OPT_login;
  9396. break;
  9397. #if !BB_MMU
  9398. case '<': /* "big heredoc" support */
  9399. full_write1_str(optarg);
  9400. _exit(0);
  9401. case '$': {
  9402. unsigned long long empty_trap_mask;
  9403. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9404. optarg++;
  9405. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9406. optarg++;
  9407. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9408. optarg++;
  9409. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9410. optarg++;
  9411. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9412. optarg++;
  9413. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9414. if (empty_trap_mask != 0) {
  9415. IF_HUSH_TRAP(int sig;)
  9416. install_special_sighandlers();
  9417. # if ENABLE_HUSH_TRAP
  9418. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9419. for (sig = 1; sig < NSIG; sig++) {
  9420. if (empty_trap_mask & (1LL << sig)) {
  9421. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9422. install_sighandler(sig, SIG_IGN);
  9423. }
  9424. }
  9425. # endif
  9426. }
  9427. # if ENABLE_HUSH_LOOPS
  9428. optarg++;
  9429. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9430. # endif
  9431. # if ENABLE_HUSH_FUNCTIONS
  9432. /* nommu uses re-exec trick for "... | func | ...",
  9433. * should allow "return".
  9434. * This accidentally allows returns in subshells.
  9435. */
  9436. G_flag_return_in_progress = -1;
  9437. # endif
  9438. break;
  9439. }
  9440. case 'R':
  9441. case 'V':
  9442. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9443. break;
  9444. # if ENABLE_HUSH_FUNCTIONS
  9445. case 'F': {
  9446. struct function *funcp = new_function(optarg);
  9447. /* funcp->name is already set to optarg */
  9448. /* funcp->body is set to NULL. It's a special case. */
  9449. funcp->body_as_string = argv[optind];
  9450. optind++;
  9451. break;
  9452. }
  9453. # endif
  9454. #endif
  9455. case 'n':
  9456. case 'x':
  9457. case 'e':
  9458. if (set_mode(1, opt, NULL) == 0) /* no error */
  9459. break;
  9460. default:
  9461. #ifndef BB_VER
  9462. fprintf(stderr, "Usage: sh [FILE]...\n"
  9463. " or: sh -c command [args]...\n\n");
  9464. exit(EXIT_FAILURE);
  9465. #else
  9466. bb_show_usage();
  9467. #endif
  9468. }
  9469. } /* option parsing loop */
  9470. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9471. G.global_argc = argc - (optind - 1);
  9472. G.global_argv = argv + (optind - 1);
  9473. G.global_argv[0] = argv[0];
  9474. if (!G.root_pid) {
  9475. G.root_pid = getpid();
  9476. G.root_ppid = getppid();
  9477. }
  9478. /* If we are login shell... */
  9479. if (flags & OPT_login) {
  9480. HFILE *input;
  9481. debug_printf("sourcing /etc/profile\n");
  9482. input = hfopen("/etc/profile");
  9483. if (input != NULL) {
  9484. install_special_sighandlers();
  9485. parse_and_run_file(input);
  9486. hfclose(input);
  9487. }
  9488. /* bash: after sourcing /etc/profile,
  9489. * tries to source (in the given order):
  9490. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9491. * stopping on first found. --noprofile turns this off.
  9492. * bash also sources ~/.bash_logout on exit.
  9493. * If called as sh, skips .bash_XXX files.
  9494. */
  9495. }
  9496. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9497. if (!G.opt_s && G.global_argv[1]) {
  9498. HFILE *input;
  9499. /*
  9500. * "bash <script>" (which is never interactive (unless -i?))
  9501. * sources $BASH_ENV here (without scanning $PATH).
  9502. * If called as sh, does the same but with $ENV.
  9503. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9504. */
  9505. G.global_argc--;
  9506. G.global_argv++;
  9507. debug_printf("running script '%s'\n", G.global_argv[0]);
  9508. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9509. input = hfopen(G.global_argv[0]);
  9510. if (!input) {
  9511. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9512. }
  9513. xfunc_error_retval = 1;
  9514. install_special_sighandlers();
  9515. parse_and_run_file(input);
  9516. #if ENABLE_FEATURE_CLEAN_UP
  9517. hfclose(input);
  9518. #endif
  9519. goto final_return;
  9520. }
  9521. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9522. G.opt_s = 1;
  9523. /* Up to here, shell was non-interactive. Now it may become one.
  9524. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9525. */
  9526. /* A shell is interactive if the '-i' flag was given,
  9527. * or if all of the following conditions are met:
  9528. * no -c command
  9529. * no arguments remaining or the -s flag given
  9530. * standard input is a terminal
  9531. * standard output is a terminal
  9532. * Refer to Posix.2, the description of the 'sh' utility.
  9533. */
  9534. #if ENABLE_HUSH_JOB
  9535. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9536. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9537. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9538. if (G_saved_tty_pgrp < 0)
  9539. G_saved_tty_pgrp = 0;
  9540. /* try to dup stdin to high fd#, >= 255 */
  9541. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9542. if (G_interactive_fd < 0) {
  9543. /* try to dup to any fd */
  9544. G_interactive_fd = dup(STDIN_FILENO);
  9545. if (G_interactive_fd < 0) {
  9546. /* give up */
  9547. G_interactive_fd = 0;
  9548. G_saved_tty_pgrp = 0;
  9549. }
  9550. }
  9551. }
  9552. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9553. if (G_interactive_fd) {
  9554. close_on_exec_on(G_interactive_fd);
  9555. if (G_saved_tty_pgrp) {
  9556. /* If we were run as 'hush &', sleep until we are
  9557. * in the foreground (tty pgrp == our pgrp).
  9558. * If we get started under a job aware app (like bash),
  9559. * make sure we are now in charge so we don't fight over
  9560. * who gets the foreground */
  9561. while (1) {
  9562. pid_t shell_pgrp = getpgrp();
  9563. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9564. if (G_saved_tty_pgrp == shell_pgrp)
  9565. break;
  9566. /* send TTIN to ourself (should stop us) */
  9567. kill(- shell_pgrp, SIGTTIN);
  9568. }
  9569. }
  9570. /* Install more signal handlers */
  9571. install_special_sighandlers();
  9572. if (G_saved_tty_pgrp) {
  9573. /* Set other signals to restore saved_tty_pgrp */
  9574. install_fatal_sighandlers();
  9575. /* Put ourselves in our own process group
  9576. * (bash, too, does this only if ctty is available) */
  9577. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9578. /* Grab control of the terminal */
  9579. tcsetpgrp(G_interactive_fd, getpid());
  9580. }
  9581. enable_restore_tty_pgrp_on_exit();
  9582. # if ENABLE_FEATURE_EDITING
  9583. G.line_input_state = new_line_input_t(FOR_SHELL);
  9584. # endif
  9585. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9586. {
  9587. const char *hp = get_local_var_value("HISTFILE");
  9588. if (!hp) {
  9589. hp = get_local_var_value("HOME");
  9590. if (hp)
  9591. hp = concat_path_file(hp, ".hush_history");
  9592. } else {
  9593. hp = xstrdup(hp);
  9594. }
  9595. if (hp) {
  9596. G.line_input_state->hist_file = hp;
  9597. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9598. }
  9599. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9600. hp = get_local_var_value("HISTFILESIZE");
  9601. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9602. # endif
  9603. }
  9604. # endif
  9605. } else {
  9606. install_special_sighandlers();
  9607. }
  9608. #elif ENABLE_HUSH_INTERACTIVE
  9609. /* No job control compiled in, only prompt/line editing */
  9610. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9611. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9612. if (G_interactive_fd < 0) {
  9613. /* try to dup to any fd */
  9614. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9615. if (G_interactive_fd < 0)
  9616. /* give up */
  9617. G_interactive_fd = 0;
  9618. }
  9619. }
  9620. if (G_interactive_fd) {
  9621. close_on_exec_on(G_interactive_fd);
  9622. }
  9623. install_special_sighandlers();
  9624. #else
  9625. /* We have interactiveness code disabled */
  9626. install_special_sighandlers();
  9627. #endif
  9628. /* bash:
  9629. * if interactive but not a login shell, sources ~/.bashrc
  9630. * (--norc turns this off, --rcfile <file> overrides)
  9631. */
  9632. if (G_interactive_fd) {
  9633. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9634. /* Set (but not export) PS1/2 unless already set */
  9635. if (!get_local_var_value("PS1"))
  9636. set_local_var_from_halves("PS1", "\\w \\$ ");
  9637. if (!get_local_var_value("PS2"))
  9638. set_local_var_from_halves("PS2", "> ");
  9639. #endif
  9640. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9641. /* note: ash and hush share this string */
  9642. printf("\n\n%s %s\n"
  9643. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9644. "\n",
  9645. bb_banner,
  9646. "hush - the humble shell"
  9647. );
  9648. }
  9649. }
  9650. parse_and_run_file(hfopen(NULL)); /* stdin */
  9651. final_return:
  9652. hush_exit(G.last_exitcode);
  9653. }
  9654. /*
  9655. * Built-ins
  9656. */
  9657. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9658. {
  9659. return 0;
  9660. }
  9661. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9662. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9663. {
  9664. int argc = string_array_len(argv);
  9665. return applet_main_func(argc, argv);
  9666. }
  9667. #endif
  9668. #if ENABLE_HUSH_TEST || BASH_TEST2
  9669. static int FAST_FUNC builtin_test(char **argv)
  9670. {
  9671. return run_applet_main(argv, test_main);
  9672. }
  9673. #endif
  9674. #if ENABLE_HUSH_ECHO
  9675. static int FAST_FUNC builtin_echo(char **argv)
  9676. {
  9677. return run_applet_main(argv, echo_main);
  9678. }
  9679. #endif
  9680. #if ENABLE_HUSH_PRINTF
  9681. static int FAST_FUNC builtin_printf(char **argv)
  9682. {
  9683. return run_applet_main(argv, printf_main);
  9684. }
  9685. #endif
  9686. #if ENABLE_HUSH_HELP
  9687. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9688. {
  9689. const struct built_in_command *x;
  9690. printf(
  9691. "Built-in commands:\n"
  9692. "------------------\n");
  9693. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9694. if (x->b_descr)
  9695. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9696. }
  9697. return EXIT_SUCCESS;
  9698. }
  9699. #endif
  9700. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9701. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9702. {
  9703. if (G.line_input_state)
  9704. show_history(G.line_input_state);
  9705. return EXIT_SUCCESS;
  9706. }
  9707. #endif
  9708. static char **skip_dash_dash(char **argv)
  9709. {
  9710. argv++;
  9711. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9712. argv++;
  9713. return argv;
  9714. }
  9715. static int FAST_FUNC builtin_cd(char **argv)
  9716. {
  9717. const char *newdir;
  9718. argv = skip_dash_dash(argv);
  9719. newdir = argv[0];
  9720. if (newdir == NULL) {
  9721. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9722. * bash says "bash: cd: HOME not set" and does nothing
  9723. * (exitcode 1)
  9724. */
  9725. const char *home = get_local_var_value("HOME");
  9726. newdir = home ? home : "/";
  9727. }
  9728. if (chdir(newdir)) {
  9729. /* Mimic bash message exactly */
  9730. bb_perror_msg("cd: %s", newdir);
  9731. return EXIT_FAILURE;
  9732. }
  9733. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9734. * Note: do not enforce exporting. If PWD was unset or unexported,
  9735. * set it again, but do not export. bash does the same.
  9736. */
  9737. set_pwd_var(/*flag:*/ 0);
  9738. return EXIT_SUCCESS;
  9739. }
  9740. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9741. {
  9742. puts(get_cwd(0));
  9743. return EXIT_SUCCESS;
  9744. }
  9745. static int FAST_FUNC builtin_eval(char **argv)
  9746. {
  9747. argv = skip_dash_dash(argv);
  9748. if (!argv[0])
  9749. return EXIT_SUCCESS;
  9750. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9751. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9752. if (!argv[1]) {
  9753. /* bash:
  9754. * eval "echo Hi; done" ("done" is syntax error):
  9755. * "echo Hi" will not execute too.
  9756. */
  9757. parse_and_run_string(argv[0]);
  9758. } else {
  9759. /* "The eval utility shall construct a command by
  9760. * concatenating arguments together, separating
  9761. * each with a <space> character."
  9762. */
  9763. char *str, *p;
  9764. unsigned len = 0;
  9765. char **pp = argv;
  9766. do
  9767. len += strlen(*pp) + 1;
  9768. while (*++pp);
  9769. str = p = xmalloc(len);
  9770. pp = argv;
  9771. for (;;) {
  9772. p = stpcpy(p, *pp);
  9773. pp++;
  9774. if (!*pp)
  9775. break;
  9776. *p++ = ' ';
  9777. }
  9778. parse_and_run_string(str);
  9779. free(str);
  9780. }
  9781. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9782. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9783. return G.last_exitcode;
  9784. }
  9785. static int FAST_FUNC builtin_exec(char **argv)
  9786. {
  9787. argv = skip_dash_dash(argv);
  9788. if (argv[0] == NULL)
  9789. return EXIT_SUCCESS; /* bash does this */
  9790. /* Careful: we can end up here after [v]fork. Do not restore
  9791. * tty pgrp then, only top-level shell process does that */
  9792. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9793. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9794. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9795. * open here. However, they are all CLOEXEC, and execv below
  9796. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9797. * it should show no extra open fds in the "ls" process.
  9798. * If we'd try to run builtins/NOEXECs, this would need improving.
  9799. */
  9800. //close_saved_fds_and_FILE_fds();
  9801. /* TODO: if exec fails, bash does NOT exit! We do.
  9802. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9803. * and tcsetpgrp, and this is inherently racy.
  9804. */
  9805. execvp_or_die(argv);
  9806. }
  9807. static int FAST_FUNC builtin_exit(char **argv)
  9808. {
  9809. debug_printf_exec("%s()\n", __func__);
  9810. /* interactive bash:
  9811. * # trap "echo EEE" EXIT
  9812. * # exit
  9813. * exit
  9814. * There are stopped jobs.
  9815. * (if there are _stopped_ jobs, running ones don't count)
  9816. * # exit
  9817. * exit
  9818. * EEE (then bash exits)
  9819. *
  9820. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9821. */
  9822. /* note: EXIT trap is run by hush_exit */
  9823. argv = skip_dash_dash(argv);
  9824. if (argv[0] == NULL)
  9825. hush_exit(G.last_exitcode);
  9826. /* mimic bash: exit 123abc == exit 255 + error msg */
  9827. xfunc_error_retval = 255;
  9828. /* bash: exit -2 == exit 254, no error msg */
  9829. hush_exit(xatoi(argv[0]) & 0xff);
  9830. }
  9831. #if ENABLE_HUSH_TYPE
  9832. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9833. static int FAST_FUNC builtin_type(char **argv)
  9834. {
  9835. int ret = EXIT_SUCCESS;
  9836. while (*++argv) {
  9837. const char *type;
  9838. char *path = NULL;
  9839. if (0) {} /* make conditional compile easier below */
  9840. /*else if (find_alias(*argv))
  9841. type = "an alias";*/
  9842. #if ENABLE_HUSH_FUNCTIONS
  9843. else if (find_function(*argv))
  9844. type = "a function";
  9845. #endif
  9846. else if (find_builtin(*argv))
  9847. type = "a shell builtin";
  9848. else if ((path = find_in_path(*argv)) != NULL)
  9849. type = path;
  9850. else {
  9851. bb_error_msg("type: %s: not found", *argv);
  9852. ret = EXIT_FAILURE;
  9853. continue;
  9854. }
  9855. printf("%s is %s\n", *argv, type);
  9856. free(path);
  9857. }
  9858. return ret;
  9859. }
  9860. #endif
  9861. #if ENABLE_HUSH_READ
  9862. /* Interruptibility of read builtin in bash
  9863. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9864. *
  9865. * Empty trap makes read ignore corresponding signal, for any signal.
  9866. *
  9867. * SIGINT:
  9868. * - terminates non-interactive shell;
  9869. * - interrupts read in interactive shell;
  9870. * if it has non-empty trap:
  9871. * - executes trap and returns to command prompt in interactive shell;
  9872. * - executes trap and returns to read in non-interactive shell;
  9873. * SIGTERM:
  9874. * - is ignored (does not interrupt) read in interactive shell;
  9875. * - terminates non-interactive shell;
  9876. * if it has non-empty trap:
  9877. * - executes trap and returns to read;
  9878. * SIGHUP:
  9879. * - terminates shell (regardless of interactivity);
  9880. * if it has non-empty trap:
  9881. * - executes trap and returns to read;
  9882. * SIGCHLD from children:
  9883. * - does not interrupt read regardless of interactivity:
  9884. * try: sleep 1 & read x; echo $x
  9885. */
  9886. static int FAST_FUNC builtin_read(char **argv)
  9887. {
  9888. const char *r;
  9889. struct builtin_read_params params;
  9890. memset(&params, 0, sizeof(params));
  9891. /* "!": do not abort on errors.
  9892. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9893. */
  9894. params.read_flags = getopt32(argv,
  9895. #if BASH_READ_D
  9896. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9897. #else
  9898. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9899. #endif
  9900. );
  9901. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9902. return EXIT_FAILURE;
  9903. argv += optind;
  9904. params.argv = argv;
  9905. params.setvar = set_local_var_from_halves;
  9906. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9907. again:
  9908. r = shell_builtin_read(&params);
  9909. if ((uintptr_t)r == 1 && errno == EINTR) {
  9910. unsigned sig = check_and_run_traps();
  9911. if (sig != SIGINT)
  9912. goto again;
  9913. }
  9914. if ((uintptr_t)r > 1) {
  9915. bb_simple_error_msg(r);
  9916. r = (char*)(uintptr_t)1;
  9917. }
  9918. return (uintptr_t)r;
  9919. }
  9920. #endif
  9921. #if ENABLE_HUSH_UMASK
  9922. static int FAST_FUNC builtin_umask(char **argv)
  9923. {
  9924. int rc;
  9925. mode_t mask;
  9926. rc = 1;
  9927. mask = umask(0);
  9928. argv = skip_dash_dash(argv);
  9929. if (argv[0]) {
  9930. mode_t old_mask = mask;
  9931. /* numeric umasks are taken as-is */
  9932. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9933. if (!isdigit(argv[0][0]))
  9934. mask ^= 0777;
  9935. mask = bb_parse_mode(argv[0], mask);
  9936. if (!isdigit(argv[0][0]))
  9937. mask ^= 0777;
  9938. if ((unsigned)mask > 0777) {
  9939. mask = old_mask;
  9940. /* bash messages:
  9941. * bash: umask: 'q': invalid symbolic mode operator
  9942. * bash: umask: 999: octal number out of range
  9943. */
  9944. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9945. rc = 0;
  9946. }
  9947. } else {
  9948. /* Mimic bash */
  9949. printf("%04o\n", (unsigned) mask);
  9950. /* fall through and restore mask which we set to 0 */
  9951. }
  9952. umask(mask);
  9953. return !rc; /* rc != 0 - success */
  9954. }
  9955. #endif
  9956. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9957. static void print_escaped(const char *s)
  9958. {
  9959. if (*s == '\'')
  9960. goto squote;
  9961. do {
  9962. const char *p = strchrnul(s, '\'');
  9963. /* print 'xxxx', possibly just '' */
  9964. printf("'%.*s'", (int)(p - s), s);
  9965. if (*p == '\0')
  9966. break;
  9967. s = p;
  9968. squote:
  9969. /* s points to '; print "'''...'''" */
  9970. putchar('"');
  9971. do putchar('\''); while (*++s == '\'');
  9972. putchar('"');
  9973. } while (*s);
  9974. }
  9975. #endif
  9976. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9977. static int helper_export_local(char **argv, unsigned flags)
  9978. {
  9979. do {
  9980. char *name = *argv;
  9981. const char *name_end = endofname(name);
  9982. if (*name_end == '\0') {
  9983. struct variable *var, **vpp;
  9984. vpp = get_ptr_to_local_var(name, name_end - name);
  9985. var = vpp ? *vpp : NULL;
  9986. if (flags & SETFLAG_UNEXPORT) {
  9987. /* export -n NAME (without =VALUE) */
  9988. if (var) {
  9989. var->flg_export = 0;
  9990. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9991. unsetenv(name);
  9992. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9993. continue;
  9994. }
  9995. if (flags & SETFLAG_EXPORT) {
  9996. /* export NAME (without =VALUE) */
  9997. if (var) {
  9998. var->flg_export = 1;
  9999. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10000. putenv(var->varstr);
  10001. continue;
  10002. }
  10003. }
  10004. if (flags & SETFLAG_MAKE_RO) {
  10005. /* readonly NAME (without =VALUE) */
  10006. if (var) {
  10007. var->flg_read_only = 1;
  10008. continue;
  10009. }
  10010. }
  10011. # if ENABLE_HUSH_LOCAL
  10012. /* Is this "local" bltin? */
  10013. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10014. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10015. if (var && var->var_nest_level == lvl) {
  10016. /* "local x=abc; ...; local x" - ignore second local decl */
  10017. continue;
  10018. }
  10019. }
  10020. # endif
  10021. /* Exporting non-existing variable.
  10022. * bash does not put it in environment,
  10023. * but remembers that it is exported,
  10024. * and does put it in env when it is set later.
  10025. * We just set it to "" and export.
  10026. */
  10027. /* Or, it's "local NAME" (without =VALUE).
  10028. * bash sets the value to "".
  10029. */
  10030. /* Or, it's "readonly NAME" (without =VALUE).
  10031. * bash remembers NAME and disallows its creation
  10032. * in the future.
  10033. */
  10034. name = xasprintf("%s=", name);
  10035. } else {
  10036. if (*name_end != '=') {
  10037. bb_error_msg("'%s': bad variable name", name);
  10038. /* do not parse following argv[]s: */
  10039. return 1;
  10040. }
  10041. /* (Un)exporting/making local NAME=VALUE */
  10042. name = xstrdup(name);
  10043. /* Testcase: export PS1='\w \$ ' */
  10044. unbackslash(name);
  10045. }
  10046. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10047. if (set_local_var(name, flags))
  10048. return EXIT_FAILURE;
  10049. } while (*++argv);
  10050. return EXIT_SUCCESS;
  10051. }
  10052. #endif
  10053. #if ENABLE_HUSH_EXPORT
  10054. static int FAST_FUNC builtin_export(char **argv)
  10055. {
  10056. unsigned opt_unexport;
  10057. #if ENABLE_HUSH_EXPORT_N
  10058. /* "!": do not abort on errors */
  10059. opt_unexport = getopt32(argv, "!n");
  10060. if (opt_unexport == (uint32_t)-1)
  10061. return EXIT_FAILURE;
  10062. argv += optind;
  10063. #else
  10064. opt_unexport = 0;
  10065. argv++;
  10066. #endif
  10067. if (argv[0] == NULL) {
  10068. char **e = environ;
  10069. if (e) {
  10070. while (*e) {
  10071. #if 0
  10072. puts(*e++);
  10073. #else
  10074. /* ash emits: export VAR='VAL'
  10075. * bash: declare -x VAR="VAL"
  10076. * we follow ash example */
  10077. const char *s = *e++;
  10078. const char *p = strchr(s, '=');
  10079. if (!p) /* wtf? take next variable */
  10080. continue;
  10081. /* export var= */
  10082. printf("export %.*s", (int)(p - s) + 1, s);
  10083. print_escaped(p + 1);
  10084. putchar('\n');
  10085. #endif
  10086. }
  10087. /*fflush_all(); - done after each builtin anyway */
  10088. }
  10089. return EXIT_SUCCESS;
  10090. }
  10091. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10092. }
  10093. #endif
  10094. #if ENABLE_HUSH_LOCAL
  10095. static int FAST_FUNC builtin_local(char **argv)
  10096. {
  10097. if (G.func_nest_level == 0) {
  10098. bb_error_msg("%s: not in a function", argv[0]);
  10099. return EXIT_FAILURE; /* bash compat */
  10100. }
  10101. argv++;
  10102. /* Since all builtins run in a nested variable level,
  10103. * need to use level - 1 here. Or else the variable will be removed at once
  10104. * after builtin returns.
  10105. */
  10106. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10107. }
  10108. #endif
  10109. #if ENABLE_HUSH_READONLY
  10110. static int FAST_FUNC builtin_readonly(char **argv)
  10111. {
  10112. argv++;
  10113. if (*argv == NULL) {
  10114. /* bash: readonly [-p]: list all readonly VARs
  10115. * (-p has no effect in bash)
  10116. */
  10117. struct variable *e;
  10118. for (e = G.top_var; e; e = e->next) {
  10119. if (e->flg_read_only) {
  10120. //TODO: quote value: readonly VAR='VAL'
  10121. printf("readonly %s\n", e->varstr);
  10122. }
  10123. }
  10124. return EXIT_SUCCESS;
  10125. }
  10126. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10127. }
  10128. #endif
  10129. #if ENABLE_HUSH_UNSET
  10130. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10131. static int FAST_FUNC builtin_unset(char **argv)
  10132. {
  10133. int ret;
  10134. unsigned opts;
  10135. /* "!": do not abort on errors */
  10136. /* "+": stop at 1st non-option */
  10137. opts = getopt32(argv, "!+vf");
  10138. if (opts == (unsigned)-1)
  10139. return EXIT_FAILURE;
  10140. if (opts == 3) {
  10141. bb_simple_error_msg("unset: -v and -f are exclusive");
  10142. return EXIT_FAILURE;
  10143. }
  10144. argv += optind;
  10145. ret = EXIT_SUCCESS;
  10146. while (*argv) {
  10147. if (!(opts & 2)) { /* not -f */
  10148. if (unset_local_var(*argv)) {
  10149. /* unset <nonexistent_var> doesn't fail.
  10150. * Error is when one tries to unset RO var.
  10151. * Message was printed by unset_local_var. */
  10152. ret = EXIT_FAILURE;
  10153. }
  10154. }
  10155. # if ENABLE_HUSH_FUNCTIONS
  10156. else {
  10157. unset_func(*argv);
  10158. }
  10159. # endif
  10160. argv++;
  10161. }
  10162. return ret;
  10163. }
  10164. #endif
  10165. #if ENABLE_HUSH_SET
  10166. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10167. * built-in 'set' handler
  10168. * SUSv3 says:
  10169. * set [-abCefhmnuvx] [-o option] [argument...]
  10170. * set [+abCefhmnuvx] [+o option] [argument...]
  10171. * set -- [argument...]
  10172. * set -o
  10173. * set +o
  10174. * Implementations shall support the options in both their hyphen and
  10175. * plus-sign forms. These options can also be specified as options to sh.
  10176. * Examples:
  10177. * Write out all variables and their values: set
  10178. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10179. * Turn on the -x and -v options: set -xv
  10180. * Unset all positional parameters: set --
  10181. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10182. * Set the positional parameters to the expansion of x, even if x expands
  10183. * with a leading '-' or '+': set -- $x
  10184. *
  10185. * So far, we only support "set -- [argument...]" and some of the short names.
  10186. */
  10187. static int FAST_FUNC builtin_set(char **argv)
  10188. {
  10189. int n;
  10190. char **pp, **g_argv;
  10191. char *arg = *++argv;
  10192. if (arg == NULL) {
  10193. struct variable *e;
  10194. for (e = G.top_var; e; e = e->next)
  10195. puts(e->varstr);
  10196. return EXIT_SUCCESS;
  10197. }
  10198. do {
  10199. if (strcmp(arg, "--") == 0) {
  10200. ++argv;
  10201. goto set_argv;
  10202. }
  10203. if (arg[0] != '+' && arg[0] != '-')
  10204. break;
  10205. for (n = 1; arg[n]; ++n) {
  10206. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10207. bb_error_msg("%s: %s: invalid option", "set", arg);
  10208. return EXIT_FAILURE;
  10209. }
  10210. if (arg[n] == 'o' && argv[1])
  10211. argv++;
  10212. }
  10213. } while ((arg = *++argv) != NULL);
  10214. /* Now argv[0] is 1st argument */
  10215. if (arg == NULL)
  10216. return EXIT_SUCCESS;
  10217. set_argv:
  10218. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10219. g_argv = G.global_argv;
  10220. if (G.global_args_malloced) {
  10221. pp = g_argv;
  10222. while (*++pp)
  10223. free(*pp);
  10224. g_argv[1] = NULL;
  10225. } else {
  10226. G.global_args_malloced = 1;
  10227. pp = xzalloc(sizeof(pp[0]) * 2);
  10228. pp[0] = g_argv[0]; /* retain $0 */
  10229. g_argv = pp;
  10230. }
  10231. /* This realloc's G.global_argv */
  10232. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10233. G.global_argc = 1 + string_array_len(pp + 1);
  10234. return EXIT_SUCCESS;
  10235. }
  10236. #endif
  10237. static int FAST_FUNC builtin_shift(char **argv)
  10238. {
  10239. int n = 1;
  10240. argv = skip_dash_dash(argv);
  10241. if (argv[0]) {
  10242. n = bb_strtou(argv[0], NULL, 10);
  10243. if (errno || n < 0) {
  10244. /* shared string with ash.c */
  10245. bb_error_msg("Illegal number: %s", argv[0]);
  10246. /*
  10247. * ash aborts in this case.
  10248. * bash prints error message and set $? to 1.
  10249. * Interestingly, for "shift 99999" bash does not
  10250. * print error message, but does set $? to 1
  10251. * (and does no shifting at all).
  10252. */
  10253. }
  10254. }
  10255. if (n >= 0 && n < G.global_argc) {
  10256. if (G_global_args_malloced) {
  10257. int m = 1;
  10258. while (m <= n)
  10259. free(G.global_argv[m++]);
  10260. }
  10261. G.global_argc -= n;
  10262. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10263. G.global_argc * sizeof(G.global_argv[0]));
  10264. return EXIT_SUCCESS;
  10265. }
  10266. return EXIT_FAILURE;
  10267. }
  10268. #if ENABLE_HUSH_GETOPTS
  10269. static int FAST_FUNC builtin_getopts(char **argv)
  10270. {
  10271. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10272. TODO:
  10273. If a required argument is not found, and getopts is not silent,
  10274. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10275. diagnostic message is printed. If getopts is silent, then a
  10276. colon (:) is placed in VAR and OPTARG is set to the option
  10277. character found.
  10278. Test that VAR is a valid variable name?
  10279. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10280. */
  10281. char cbuf[2];
  10282. const char *cp, *optstring, *var;
  10283. int c, n, exitcode, my_opterr;
  10284. unsigned count;
  10285. optstring = *++argv;
  10286. if (!optstring || !(var = *++argv)) {
  10287. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10288. return EXIT_FAILURE;
  10289. }
  10290. if (argv[1])
  10291. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10292. else
  10293. argv = G.global_argv;
  10294. cbuf[1] = '\0';
  10295. my_opterr = 0;
  10296. if (optstring[0] != ':') {
  10297. cp = get_local_var_value("OPTERR");
  10298. /* 0 if "OPTERR=0", 1 otherwise */
  10299. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10300. }
  10301. /* getopts stops on first non-option. Add "+" to force that */
  10302. /*if (optstring[0] != '+')*/ {
  10303. char *s = alloca(strlen(optstring) + 2);
  10304. sprintf(s, "+%s", optstring);
  10305. optstring = s;
  10306. }
  10307. /* Naively, now we should just
  10308. * cp = get_local_var_value("OPTIND");
  10309. * optind = cp ? atoi(cp) : 0;
  10310. * optarg = NULL;
  10311. * opterr = my_opterr;
  10312. * c = getopt(string_array_len(argv), argv, optstring);
  10313. * and be done? Not so fast...
  10314. * Unlike normal getopt() usage in C programs, here
  10315. * each successive call will (usually) have the same argv[] CONTENTS,
  10316. * but not the ADDRESSES. Worse yet, it's possible that between
  10317. * invocations of "getopts", there will be calls to shell builtins
  10318. * which use getopt() internally. Example:
  10319. * while getopts "abc" RES -a -bc -abc de; do
  10320. * unset -ff func
  10321. * done
  10322. * This would not work correctly: getopt() call inside "unset"
  10323. * modifies internal libc state which is tracking position in
  10324. * multi-option strings ("-abc"). At best, it can skip options
  10325. * or return the same option infinitely. With glibc implementation
  10326. * of getopt(), it would use outright invalid pointers and return
  10327. * garbage even _without_ "unset" mangling internal state.
  10328. *
  10329. * We resort to resetting getopt() state and calling it N times,
  10330. * until we get Nth result (or failure).
  10331. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10332. */
  10333. GETOPT_RESET();
  10334. count = 0;
  10335. n = string_array_len(argv);
  10336. do {
  10337. optarg = NULL;
  10338. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10339. c = getopt(n, argv, optstring);
  10340. if (c < 0)
  10341. break;
  10342. count++;
  10343. } while (count <= G.getopt_count);
  10344. /* Set OPTIND. Prevent resetting of the magic counter! */
  10345. set_local_var_from_halves("OPTIND", utoa(optind));
  10346. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10347. GETOPT_RESET(); /* just in case */
  10348. /* Set OPTARG */
  10349. /* Always set or unset, never left as-is, even on exit/error:
  10350. * "If no option was found, or if the option that was found
  10351. * does not have an option-argument, OPTARG shall be unset."
  10352. */
  10353. cp = optarg;
  10354. if (c == '?') {
  10355. /* If ":optstring" and unknown option is seen,
  10356. * it is stored to OPTARG.
  10357. */
  10358. if (optstring[1] == ':') {
  10359. cbuf[0] = optopt;
  10360. cp = cbuf;
  10361. }
  10362. }
  10363. if (cp)
  10364. set_local_var_from_halves("OPTARG", cp);
  10365. else
  10366. unset_local_var("OPTARG");
  10367. /* Convert -1 to "?" */
  10368. exitcode = EXIT_SUCCESS;
  10369. if (c < 0) { /* -1: end of options */
  10370. exitcode = EXIT_FAILURE;
  10371. c = '?';
  10372. }
  10373. /* Set VAR */
  10374. cbuf[0] = c;
  10375. set_local_var_from_halves(var, cbuf);
  10376. return exitcode;
  10377. }
  10378. #endif
  10379. static int FAST_FUNC builtin_source(char **argv)
  10380. {
  10381. char *arg_path, *filename;
  10382. HFILE *input;
  10383. save_arg_t sv;
  10384. char *args_need_save;
  10385. #if ENABLE_HUSH_FUNCTIONS
  10386. smallint sv_flg;
  10387. #endif
  10388. argv = skip_dash_dash(argv);
  10389. filename = argv[0];
  10390. if (!filename) {
  10391. /* bash says: "bash: .: filename argument required" */
  10392. return 2; /* bash compat */
  10393. }
  10394. arg_path = NULL;
  10395. if (!strchr(filename, '/')) {
  10396. arg_path = find_in_path(filename);
  10397. if (arg_path)
  10398. filename = arg_path;
  10399. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10400. errno = ENOENT;
  10401. bb_simple_perror_msg(filename);
  10402. return EXIT_FAILURE;
  10403. }
  10404. }
  10405. input = hfopen(filename);
  10406. free(arg_path);
  10407. if (!input) {
  10408. bb_perror_msg("%s", filename);
  10409. /* POSIX: non-interactive shell should abort here,
  10410. * not merely fail. So far no one complained :)
  10411. */
  10412. return EXIT_FAILURE;
  10413. }
  10414. #if ENABLE_HUSH_FUNCTIONS
  10415. sv_flg = G_flag_return_in_progress;
  10416. /* "we are inside sourced file, ok to use return" */
  10417. G_flag_return_in_progress = -1;
  10418. #endif
  10419. args_need_save = argv[1]; /* used as a boolean variable */
  10420. if (args_need_save)
  10421. save_and_replace_G_args(&sv, argv);
  10422. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10423. G.last_exitcode = 0;
  10424. parse_and_run_file(input);
  10425. hfclose(input);
  10426. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10427. restore_G_args(&sv, argv);
  10428. #if ENABLE_HUSH_FUNCTIONS
  10429. G_flag_return_in_progress = sv_flg;
  10430. #endif
  10431. return G.last_exitcode;
  10432. }
  10433. #if ENABLE_HUSH_TRAP
  10434. static int FAST_FUNC builtin_trap(char **argv)
  10435. {
  10436. int sig;
  10437. char *new_cmd;
  10438. if (!G_traps)
  10439. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10440. argv++;
  10441. if (!*argv) {
  10442. int i;
  10443. /* No args: print all trapped */
  10444. for (i = 0; i < NSIG; ++i) {
  10445. if (G_traps[i]) {
  10446. printf("trap -- ");
  10447. print_escaped(G_traps[i]);
  10448. /* note: bash adds "SIG", but only if invoked
  10449. * as "bash". If called as "sh", or if set -o posix,
  10450. * then it prints short signal names.
  10451. * We are printing short names: */
  10452. printf(" %s\n", get_signame(i));
  10453. }
  10454. }
  10455. /*fflush_all(); - done after each builtin anyway */
  10456. return EXIT_SUCCESS;
  10457. }
  10458. new_cmd = NULL;
  10459. /* If first arg is a number: reset all specified signals */
  10460. sig = bb_strtou(*argv, NULL, 10);
  10461. if (errno == 0) {
  10462. int ret;
  10463. process_sig_list:
  10464. ret = EXIT_SUCCESS;
  10465. while (*argv) {
  10466. sighandler_t handler;
  10467. sig = get_signum(*argv++);
  10468. if (sig < 0) {
  10469. ret = EXIT_FAILURE;
  10470. /* Mimic bash message exactly */
  10471. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10472. continue;
  10473. }
  10474. free(G_traps[sig]);
  10475. G_traps[sig] = xstrdup(new_cmd);
  10476. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10477. get_signame(sig), sig, G_traps[sig]);
  10478. /* There is no signal for 0 (EXIT) */
  10479. if (sig == 0)
  10480. continue;
  10481. if (new_cmd)
  10482. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10483. else
  10484. /* We are removing trap handler */
  10485. handler = pick_sighandler(sig);
  10486. install_sighandler(sig, handler);
  10487. }
  10488. return ret;
  10489. }
  10490. if (!argv[1]) { /* no second arg */
  10491. bb_simple_error_msg("trap: invalid arguments");
  10492. return EXIT_FAILURE;
  10493. }
  10494. /* First arg is "-": reset all specified to default */
  10495. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10496. /* Everything else: set arg as signal handler
  10497. * (includes "" case, which ignores signal) */
  10498. if (argv[0][0] == '-') {
  10499. if (argv[0][1] == '\0') { /* "-" */
  10500. /* new_cmd remains NULL: "reset these sigs" */
  10501. goto reset_traps;
  10502. }
  10503. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10504. argv++;
  10505. }
  10506. /* else: "-something", no special meaning */
  10507. }
  10508. new_cmd = *argv;
  10509. reset_traps:
  10510. argv++;
  10511. goto process_sig_list;
  10512. }
  10513. #endif
  10514. #if ENABLE_HUSH_JOB
  10515. static struct pipe *parse_jobspec(const char *str)
  10516. {
  10517. struct pipe *pi;
  10518. unsigned jobnum;
  10519. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10520. if (str[0] != '%'
  10521. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10522. ) {
  10523. bb_error_msg("bad argument '%s'", str);
  10524. return NULL;
  10525. }
  10526. /* It is "%%", "%+" or "%" - current job */
  10527. jobnum = G.last_jobid;
  10528. if (jobnum == 0) {
  10529. bb_simple_error_msg("no current job");
  10530. return NULL;
  10531. }
  10532. }
  10533. for (pi = G.job_list; pi; pi = pi->next) {
  10534. if (pi->jobid == jobnum) {
  10535. return pi;
  10536. }
  10537. }
  10538. bb_error_msg("%u: no such job", jobnum);
  10539. return NULL;
  10540. }
  10541. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10542. {
  10543. struct pipe *job;
  10544. const char *status_string;
  10545. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10546. for (job = G.job_list; job; job = job->next) {
  10547. if (job->alive_cmds == job->stopped_cmds)
  10548. status_string = "Stopped";
  10549. else
  10550. status_string = "Running";
  10551. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10552. }
  10553. clean_up_last_dead_job();
  10554. return EXIT_SUCCESS;
  10555. }
  10556. /* built-in 'fg' and 'bg' handler */
  10557. static int FAST_FUNC builtin_fg_bg(char **argv)
  10558. {
  10559. int i;
  10560. struct pipe *pi;
  10561. if (!G_interactive_fd)
  10562. return EXIT_FAILURE;
  10563. /* If they gave us no args, assume they want the last backgrounded task */
  10564. if (!argv[1]) {
  10565. for (pi = G.job_list; pi; pi = pi->next) {
  10566. if (pi->jobid == G.last_jobid) {
  10567. goto found;
  10568. }
  10569. }
  10570. bb_error_msg("%s: no current job", argv[0]);
  10571. return EXIT_FAILURE;
  10572. }
  10573. pi = parse_jobspec(argv[1]);
  10574. if (!pi)
  10575. return EXIT_FAILURE;
  10576. found:
  10577. /* TODO: bash prints a string representation
  10578. * of job being foregrounded (like "sleep 1 | cat") */
  10579. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10580. /* Put the job into the foreground. */
  10581. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10582. }
  10583. /* Restart the processes in the job */
  10584. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10585. for (i = 0; i < pi->num_cmds; i++) {
  10586. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10587. }
  10588. pi->stopped_cmds = 0;
  10589. i = kill(- pi->pgrp, SIGCONT);
  10590. if (i < 0) {
  10591. if (errno == ESRCH) {
  10592. delete_finished_job(pi);
  10593. return EXIT_SUCCESS;
  10594. }
  10595. bb_simple_perror_msg("kill (SIGCONT)");
  10596. }
  10597. if (argv[0][0] == 'f') {
  10598. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10599. return checkjobs_and_fg_shell(pi);
  10600. }
  10601. return EXIT_SUCCESS;
  10602. }
  10603. #endif
  10604. #if ENABLE_HUSH_KILL
  10605. static int FAST_FUNC builtin_kill(char **argv)
  10606. {
  10607. int ret = 0;
  10608. # if ENABLE_HUSH_JOB
  10609. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10610. int i = 1;
  10611. do {
  10612. struct pipe *pi;
  10613. char *dst;
  10614. int j, n;
  10615. if (argv[i][0] != '%')
  10616. continue;
  10617. /*
  10618. * "kill %N" - job kill
  10619. * Converting to pgrp / pid kill
  10620. */
  10621. pi = parse_jobspec(argv[i]);
  10622. if (!pi) {
  10623. /* Eat bad jobspec */
  10624. j = i;
  10625. do {
  10626. j++;
  10627. argv[j - 1] = argv[j];
  10628. } while (argv[j]);
  10629. ret = 1;
  10630. i--;
  10631. continue;
  10632. }
  10633. /*
  10634. * In jobs started under job control, we signal
  10635. * entire process group by kill -PGRP_ID.
  10636. * This happens, f.e., in interactive shell.
  10637. *
  10638. * Otherwise, we signal each child via
  10639. * kill PID1 PID2 PID3.
  10640. * Testcases:
  10641. * sh -c 'sleep 1|sleep 1 & kill %1'
  10642. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10643. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10644. */
  10645. n = G_interactive_fd ? 1 : pi->num_cmds;
  10646. dst = alloca(n * sizeof(int)*4);
  10647. argv[i] = dst;
  10648. if (G_interactive_fd)
  10649. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10650. else for (j = 0; j < n; j++) {
  10651. struct command *cmd = &pi->cmds[j];
  10652. /* Skip exited members of the job */
  10653. if (cmd->pid == 0)
  10654. continue;
  10655. /*
  10656. * kill_main has matching code to expect
  10657. * leading space. Needed to not confuse
  10658. * negative pids with "kill -SIGNAL_NO" syntax
  10659. */
  10660. dst += sprintf(dst, " %u", (int)cmd->pid);
  10661. }
  10662. *dst = '\0';
  10663. } while (argv[++i]);
  10664. }
  10665. # endif
  10666. if (argv[1] || ret == 0) {
  10667. ret = run_applet_main(argv, kill_main);
  10668. }
  10669. /* else: ret = 1, "kill %bad_jobspec" case */
  10670. return ret;
  10671. }
  10672. #endif
  10673. #if ENABLE_HUSH_WAIT
  10674. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10675. #if !ENABLE_HUSH_JOB
  10676. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10677. #endif
  10678. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10679. {
  10680. int ret = 0;
  10681. for (;;) {
  10682. int sig;
  10683. sigset_t oldset;
  10684. if (!sigisemptyset(&G.pending_set))
  10685. goto check_sig;
  10686. /* waitpid is not interruptible by SA_RESTARTed
  10687. * signals which we use. Thus, this ugly dance:
  10688. */
  10689. /* Make sure possible SIGCHLD is stored in kernel's
  10690. * pending signal mask before we call waitpid.
  10691. * Or else we may race with SIGCHLD, lose it,
  10692. * and get stuck in sigsuspend...
  10693. */
  10694. sigfillset(&oldset); /* block all signals, remember old set */
  10695. sigprocmask2(SIG_SETMASK, &oldset);
  10696. if (!sigisemptyset(&G.pending_set)) {
  10697. /* Crap! we raced with some signal! */
  10698. goto restore;
  10699. }
  10700. /*errno = 0; - checkjobs does this */
  10701. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10702. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10703. debug_printf_exec("checkjobs:%d\n", ret);
  10704. #if ENABLE_HUSH_JOB
  10705. if (waitfor_pipe) {
  10706. int rcode = job_exited_or_stopped(waitfor_pipe);
  10707. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10708. if (rcode >= 0) {
  10709. ret = rcode;
  10710. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10711. break;
  10712. }
  10713. }
  10714. #endif
  10715. /* if ECHILD, there are no children (ret is -1 or 0) */
  10716. /* if ret == 0, no children changed state */
  10717. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10718. if (errno == ECHILD || ret) {
  10719. ret--;
  10720. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10721. ret = 0;
  10722. #if ENABLE_HUSH_BASH_COMPAT
  10723. if (waitfor_pid == -1 && errno == ECHILD) {
  10724. /* exitcode of "wait -n" with no children is 127, not 0 */
  10725. ret = 127;
  10726. }
  10727. #endif
  10728. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10729. break;
  10730. }
  10731. /* Wait for SIGCHLD or any other signal */
  10732. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10733. /* Note: sigsuspend invokes signal handler */
  10734. sigsuspend(&oldset);
  10735. restore:
  10736. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10737. check_sig:
  10738. /* So, did we get a signal? */
  10739. sig = check_and_run_traps();
  10740. if (sig /*&& sig != SIGCHLD - always true */) {
  10741. /* Do this for any (non-ignored) signal, not only for ^C */
  10742. ret = 128 + sig;
  10743. break;
  10744. }
  10745. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10746. }
  10747. return ret;
  10748. }
  10749. static int FAST_FUNC builtin_wait(char **argv)
  10750. {
  10751. int ret;
  10752. int status;
  10753. argv = skip_dash_dash(argv);
  10754. #if ENABLE_HUSH_BASH_COMPAT
  10755. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10756. /* wait -n */
  10757. /* (bash accepts "wait -n PID" too and ignores PID) */
  10758. G.dead_job_exitcode = -1;
  10759. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10760. }
  10761. #endif
  10762. if (argv[0] == NULL) {
  10763. /* Don't care about wait results */
  10764. /* Note 1: must wait until there are no more children */
  10765. /* Note 2: must be interruptible */
  10766. /* Examples:
  10767. * $ sleep 3 & sleep 6 & wait
  10768. * [1] 30934 sleep 3
  10769. * [2] 30935 sleep 6
  10770. * [1] Done sleep 3
  10771. * [2] Done sleep 6
  10772. * $ sleep 3 & sleep 6 & wait
  10773. * [1] 30936 sleep 3
  10774. * [2] 30937 sleep 6
  10775. * [1] Done sleep 3
  10776. * ^C <-- after ~4 sec from keyboard
  10777. * $
  10778. */
  10779. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10780. }
  10781. do {
  10782. pid_t pid = bb_strtou(*argv, NULL, 10);
  10783. if (errno || pid <= 0) {
  10784. #if ENABLE_HUSH_JOB
  10785. if (argv[0][0] == '%') {
  10786. struct pipe *wait_pipe;
  10787. ret = 127; /* bash compat for bad jobspecs */
  10788. wait_pipe = parse_jobspec(*argv);
  10789. if (wait_pipe) {
  10790. ret = job_exited_or_stopped(wait_pipe);
  10791. if (ret < 0) {
  10792. ret = wait_for_child_or_signal(wait_pipe, 0);
  10793. } else {
  10794. /* waiting on "last dead job" removes it */
  10795. clean_up_last_dead_job();
  10796. }
  10797. }
  10798. /* else: parse_jobspec() already emitted error msg */
  10799. continue;
  10800. }
  10801. #endif
  10802. /* mimic bash message */
  10803. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10804. ret = EXIT_FAILURE;
  10805. continue; /* bash checks all argv[] */
  10806. }
  10807. /* Do we have such child? */
  10808. ret = waitpid(pid, &status, WNOHANG);
  10809. if (ret < 0) {
  10810. /* No */
  10811. ret = 127;
  10812. if (errno == ECHILD) {
  10813. if (pid == G.last_bg_pid) {
  10814. /* "wait $!" but last bg task has already exited. Try:
  10815. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10816. * In bash it prints exitcode 0, then 3.
  10817. * In dash, it is 127.
  10818. */
  10819. ret = G.last_bg_pid_exitcode;
  10820. } else {
  10821. /* Example: "wait 1". mimic bash message */
  10822. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10823. }
  10824. } else {
  10825. /* ??? */
  10826. bb_perror_msg("wait %s", *argv);
  10827. }
  10828. continue; /* bash checks all argv[] */
  10829. }
  10830. if (ret == 0) {
  10831. /* Yes, and it still runs */
  10832. ret = wait_for_child_or_signal(NULL, pid);
  10833. } else {
  10834. /* Yes, and it just exited */
  10835. process_wait_result(NULL, pid, status);
  10836. ret = WEXITSTATUS(status);
  10837. if (WIFSIGNALED(status))
  10838. ret = 128 + WTERMSIG(status);
  10839. }
  10840. } while (*++argv);
  10841. return ret;
  10842. }
  10843. #endif
  10844. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10845. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10846. {
  10847. if (argv[1]) {
  10848. def = bb_strtou(argv[1], NULL, 10);
  10849. if (errno || def < def_min || argv[2]) {
  10850. bb_error_msg("%s: bad arguments", argv[0]);
  10851. def = UINT_MAX;
  10852. }
  10853. }
  10854. return def;
  10855. }
  10856. #endif
  10857. #if ENABLE_HUSH_LOOPS
  10858. static int FAST_FUNC builtin_break(char **argv)
  10859. {
  10860. unsigned depth;
  10861. if (G.depth_of_loop == 0) {
  10862. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10863. /* if we came from builtin_continue(), need to undo "= 1" */
  10864. G.flag_break_continue = 0;
  10865. return EXIT_SUCCESS; /* bash compat */
  10866. }
  10867. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10868. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10869. if (depth == UINT_MAX)
  10870. G.flag_break_continue = BC_BREAK;
  10871. if (G.depth_of_loop < depth)
  10872. G.depth_break_continue = G.depth_of_loop;
  10873. return EXIT_SUCCESS;
  10874. }
  10875. static int FAST_FUNC builtin_continue(char **argv)
  10876. {
  10877. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10878. return builtin_break(argv);
  10879. }
  10880. #endif
  10881. #if ENABLE_HUSH_FUNCTIONS
  10882. static int FAST_FUNC builtin_return(char **argv)
  10883. {
  10884. int rc;
  10885. if (G_flag_return_in_progress != -1) {
  10886. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10887. return EXIT_FAILURE; /* bash compat */
  10888. }
  10889. G_flag_return_in_progress = 1;
  10890. /* bash:
  10891. * out of range: wraps around at 256, does not error out
  10892. * non-numeric param:
  10893. * f() { false; return qwe; }; f; echo $?
  10894. * bash: return: qwe: numeric argument required <== we do this
  10895. * 255 <== we also do this
  10896. */
  10897. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10898. return rc;
  10899. }
  10900. #endif
  10901. #if ENABLE_HUSH_TIMES
  10902. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10903. {
  10904. static const uint8_t times_tbl[] ALIGN1 = {
  10905. ' ', offsetof(struct tms, tms_utime),
  10906. '\n', offsetof(struct tms, tms_stime),
  10907. ' ', offsetof(struct tms, tms_cutime),
  10908. '\n', offsetof(struct tms, tms_cstime),
  10909. 0
  10910. };
  10911. const uint8_t *p;
  10912. unsigned clk_tck;
  10913. struct tms buf;
  10914. clk_tck = bb_clk_tck();
  10915. times(&buf);
  10916. p = times_tbl;
  10917. do {
  10918. unsigned sec, frac;
  10919. unsigned long t;
  10920. t = *(clock_t *)(((char *) &buf) + p[1]);
  10921. sec = t / clk_tck;
  10922. frac = t % clk_tck;
  10923. printf("%um%u.%03us%c",
  10924. sec / 60, sec % 60,
  10925. (frac * 1000) / clk_tck,
  10926. p[0]);
  10927. p += 2;
  10928. } while (*p);
  10929. return EXIT_SUCCESS;
  10930. }
  10931. #endif
  10932. #if ENABLE_HUSH_MEMLEAK
  10933. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10934. {
  10935. void *p;
  10936. unsigned long l;
  10937. # ifdef M_TRIM_THRESHOLD
  10938. /* Optional. Reduces probability of false positives */
  10939. malloc_trim(0);
  10940. # endif
  10941. /* Crude attempt to find where "free memory" starts,
  10942. * sans fragmentation. */
  10943. p = malloc(240);
  10944. l = (unsigned long)p;
  10945. free(p);
  10946. p = malloc(3400);
  10947. if (l < (unsigned long)p) l = (unsigned long)p;
  10948. free(p);
  10949. # if 0 /* debug */
  10950. {
  10951. struct mallinfo mi = mallinfo();
  10952. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10953. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10954. }
  10955. # endif
  10956. if (!G.memleak_value)
  10957. G.memleak_value = l;
  10958. l -= G.memleak_value;
  10959. if ((long)l < 0)
  10960. l = 0;
  10961. l /= 1024;
  10962. if (l > 127)
  10963. l = 127;
  10964. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10965. return l;
  10966. }
  10967. #endif