hush.c 323 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776
  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 is_stdin;
  551. int fd;
  552. char buf[1024];
  553. } HFILE;
  554. typedef struct in_str {
  555. const char *p;
  556. int peek_buf[2];
  557. int last_char;
  558. HFILE *file;
  559. } in_str;
  560. /* The descrip member of this structure is only used to make
  561. * debugging output pretty */
  562. static const struct {
  563. int mode;
  564. signed char default_fd;
  565. char descrip[3];
  566. } redir_table[] = {
  567. { O_RDONLY, 0, "<" },
  568. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  569. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  570. { O_CREAT|O_RDWR, 1, "<>" },
  571. { O_RDONLY, 0, "<<" },
  572. /* Should not be needed. Bogus default_fd helps in debugging */
  573. /* { O_RDONLY, 77, "<<" }, */
  574. };
  575. struct redir_struct {
  576. struct redir_struct *next;
  577. char *rd_filename; /* filename */
  578. int rd_fd; /* fd to redirect */
  579. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  580. int rd_dup;
  581. smallint rd_type; /* (enum redir_type) */
  582. /* note: for heredocs, rd_filename contains heredoc delimiter,
  583. * and subsequently heredoc itself; and rd_dup is a bitmask:
  584. * bit 0: do we need to trim leading tabs?
  585. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  586. */
  587. };
  588. typedef enum redir_type {
  589. REDIRECT_INPUT = 0,
  590. REDIRECT_OVERWRITE = 1,
  591. REDIRECT_APPEND = 2,
  592. REDIRECT_IO = 3,
  593. REDIRECT_HEREDOC = 4,
  594. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  595. REDIRFD_CLOSE = -3,
  596. REDIRFD_SYNTAX_ERR = -2,
  597. REDIRFD_TO_FILE = -1,
  598. /* otherwise, rd_fd is redirected to rd_dup */
  599. HEREDOC_SKIPTABS = 1,
  600. HEREDOC_QUOTED = 2,
  601. } redir_type;
  602. struct command {
  603. pid_t pid; /* 0 if exited */
  604. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  605. #if ENABLE_HUSH_LINENO_VAR
  606. unsigned lineno;
  607. #endif
  608. smallint cmd_type; /* CMD_xxx */
  609. #define CMD_NORMAL 0
  610. #define CMD_SUBSHELL 1
  611. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  612. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  613. * "export v=t*"
  614. */
  615. # define CMD_SINGLEWORD_NOGLOB 2
  616. #endif
  617. #if ENABLE_HUSH_FUNCTIONS
  618. # define CMD_FUNCDEF 3
  619. #endif
  620. smalluint cmd_exitcode;
  621. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  622. struct pipe *group;
  623. #if !BB_MMU
  624. char *group_as_string;
  625. #endif
  626. #if ENABLE_HUSH_FUNCTIONS
  627. struct function *child_func;
  628. /* This field is used to prevent a bug here:
  629. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  630. * When we execute "f1() {a;}" cmd, we create new function and clear
  631. * cmd->group, cmd->group_as_string, cmd->argv[0].
  632. * When we execute "f1() {b;}", we notice that f1 exists,
  633. * and that its "parent cmd" struct is still "alive",
  634. * we put those fields back into cmd->xxx
  635. * (struct function has ->parent_cmd ptr to facilitate that).
  636. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  637. * Without this trick, loop would execute a;b;b;b;...
  638. * instead of correct sequence a;b;a;b;...
  639. * When command is freed, it severs the link
  640. * (sets ->child_func->parent_cmd to NULL).
  641. */
  642. #endif
  643. char **argv; /* command name and arguments */
  644. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  645. * and on execution these are substituted with their values.
  646. * Substitution can make _several_ words out of one argv[n]!
  647. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  648. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  649. */
  650. struct redir_struct *redirects; /* I/O redirections */
  651. };
  652. /* Is there anything in this command at all? */
  653. #define IS_NULL_CMD(cmd) \
  654. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  655. struct pipe {
  656. struct pipe *next;
  657. int num_cmds; /* total number of commands in pipe */
  658. int alive_cmds; /* number of commands running (not exited) */
  659. int stopped_cmds; /* number of commands alive, but stopped */
  660. #if ENABLE_HUSH_JOB
  661. unsigned jobid; /* job number */
  662. pid_t pgrp; /* process group ID for the job */
  663. char *cmdtext; /* name of job */
  664. #endif
  665. struct command *cmds; /* array of commands in pipe */
  666. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  667. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  668. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  669. };
  670. typedef enum pipe_style {
  671. PIPE_SEQ = 0,
  672. PIPE_AND = 1,
  673. PIPE_OR = 2,
  674. PIPE_BG = 3,
  675. } pipe_style;
  676. /* Is there anything in this pipe at all? */
  677. #define IS_NULL_PIPE(pi) \
  678. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  679. /* This holds pointers to the various results of parsing */
  680. struct parse_context {
  681. /* linked list of pipes */
  682. struct pipe *list_head;
  683. /* last pipe (being constructed right now) */
  684. struct pipe *pipe;
  685. /* last command in pipe (being constructed right now) */
  686. struct command *command;
  687. /* last redirect in command->redirects list */
  688. struct redir_struct *pending_redirect;
  689. o_string word;
  690. #if !BB_MMU
  691. o_string as_string;
  692. #endif
  693. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  694. #if HAS_KEYWORDS
  695. smallint ctx_res_w;
  696. smallint ctx_inverted; /* "! cmd | cmd" */
  697. #if ENABLE_HUSH_CASE
  698. smallint ctx_dsemicolon; /* ";;" seen */
  699. #endif
  700. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  701. int old_flag;
  702. /* group we are enclosed in:
  703. * example: "if pipe1; pipe2; then pipe3; fi"
  704. * when we see "if" or "then", we malloc and copy current context,
  705. * and make ->stack point to it. then we parse pipeN.
  706. * when closing "then" / fi" / whatever is found,
  707. * we move list_head into ->stack->command->group,
  708. * copy ->stack into current context, and delete ->stack.
  709. * (parsing of { list } and ( list ) doesn't use this method)
  710. */
  711. struct parse_context *stack;
  712. #endif
  713. };
  714. enum {
  715. MAYBE_ASSIGNMENT = 0,
  716. DEFINITELY_ASSIGNMENT = 1,
  717. NOT_ASSIGNMENT = 2,
  718. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  719. WORD_IS_KEYWORD = 3,
  720. };
  721. /* On program start, environ points to initial environment.
  722. * putenv adds new pointers into it, unsetenv removes them.
  723. * Neither of these (de)allocates the strings.
  724. * setenv allocates new strings in malloc space and does putenv,
  725. * and thus setenv is unusable (leaky) for shell's purposes */
  726. #define setenv(...) setenv_is_leaky_dont_use()
  727. struct variable {
  728. struct variable *next;
  729. char *varstr; /* points to "name=" portion */
  730. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  731. uint16_t var_nest_level;
  732. smallint flg_export; /* putenv should be done on this var */
  733. smallint flg_read_only;
  734. };
  735. enum {
  736. BC_BREAK = 1,
  737. BC_CONTINUE = 2,
  738. };
  739. #if ENABLE_HUSH_FUNCTIONS
  740. struct function {
  741. struct function *next;
  742. char *name;
  743. struct command *parent_cmd;
  744. struct pipe *body;
  745. # if !BB_MMU
  746. char *body_as_string;
  747. # endif
  748. };
  749. #endif
  750. /* set -/+o OPT support. (TODO: make it optional)
  751. * bash supports the following opts:
  752. * allexport off
  753. * braceexpand on
  754. * emacs on
  755. * errexit off
  756. * errtrace off
  757. * functrace off
  758. * hashall on
  759. * histexpand off
  760. * history on
  761. * ignoreeof off
  762. * interactive-comments on
  763. * keyword off
  764. * monitor on
  765. * noclobber off
  766. * noexec off
  767. * noglob off
  768. * nolog off
  769. * notify off
  770. * nounset off
  771. * onecmd off
  772. * physical off
  773. * pipefail off
  774. * posix off
  775. * privileged off
  776. * verbose off
  777. * vi off
  778. * xtrace off
  779. */
  780. static const char o_opt_strings[] ALIGN1 =
  781. "pipefail\0"
  782. "noexec\0"
  783. "errexit\0"
  784. #if ENABLE_HUSH_MODE_X
  785. "xtrace\0"
  786. #endif
  787. ;
  788. enum {
  789. OPT_O_PIPEFAIL,
  790. OPT_O_NOEXEC,
  791. OPT_O_ERREXIT,
  792. #if ENABLE_HUSH_MODE_X
  793. OPT_O_XTRACE,
  794. #endif
  795. NUM_OPT_O
  796. };
  797. /* "Globals" within this file */
  798. /* Sorted roughly by size (smaller offsets == smaller code) */
  799. struct globals {
  800. /* interactive_fd != 0 means we are an interactive shell.
  801. * If we are, then saved_tty_pgrp can also be != 0, meaning
  802. * that controlling tty is available. With saved_tty_pgrp == 0,
  803. * job control still works, but terminal signals
  804. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  805. * process groups can only be created with "cmd &".
  806. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  807. * to give tty to the foreground process group,
  808. * and will take it back when the group is stopped (^Z)
  809. * or killed (^C).
  810. */
  811. #if ENABLE_HUSH_INTERACTIVE
  812. /* 'interactive_fd' is a fd# open to ctty, if we have one
  813. * _AND_ if we decided to act interactively */
  814. int interactive_fd;
  815. const char *PS1;
  816. IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
  817. # define G_interactive_fd (G.interactive_fd)
  818. #else
  819. # define G_interactive_fd 0
  820. #endif
  821. #if ENABLE_FEATURE_EDITING
  822. line_input_t *line_input_state;
  823. #endif
  824. pid_t root_pid;
  825. pid_t root_ppid;
  826. pid_t last_bg_pid;
  827. #if ENABLE_HUSH_RANDOM_SUPPORT
  828. random_t random_gen;
  829. #endif
  830. #if ENABLE_HUSH_JOB
  831. int run_list_level;
  832. unsigned last_jobid;
  833. pid_t saved_tty_pgrp;
  834. struct pipe *job_list;
  835. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  836. #else
  837. # define G_saved_tty_pgrp 0
  838. #endif
  839. /* How deeply are we in context where "set -e" is ignored */
  840. int errexit_depth;
  841. /* "set -e" rules (do we follow them correctly?):
  842. * Exit if pipe, list, or compound command exits with a non-zero status.
  843. * Shell does not exit if failed command is part of condition in
  844. * if/while, part of && or || list except the last command, any command
  845. * in a pipe but the last, or if the command's return value is being
  846. * inverted with !. If a compound command other than a subshell returns a
  847. * non-zero status because a command failed while -e was being ignored, the
  848. * shell does not exit. A trap on ERR, if set, is executed before the shell
  849. * exits [ERR is a bashism].
  850. *
  851. * If a compound command or function executes in a context where -e is
  852. * ignored, none of the commands executed within are affected by the -e
  853. * setting. If a compound command or function sets -e while executing in a
  854. * context where -e is ignored, that setting does not have any effect until
  855. * the compound command or the command containing the function call completes.
  856. */
  857. char o_opt[NUM_OPT_O];
  858. #if ENABLE_HUSH_MODE_X
  859. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  860. #else
  861. # define G_x_mode 0
  862. #endif
  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 lineno;
  929. char *lineno_var;
  930. #endif
  931. HFILE *HFILE_list;
  932. /* Which signals have non-DFL handler (even with no traps set)?
  933. * Set at the start to:
  934. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  935. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  936. * The rest is cleared right before execv syscalls.
  937. * Other than these two times, never modified.
  938. */
  939. unsigned special_sig_mask;
  940. #if ENABLE_HUSH_JOB
  941. unsigned fatal_sig_mask;
  942. # define G_fatal_sig_mask (G.fatal_sig_mask)
  943. #else
  944. # define G_fatal_sig_mask 0
  945. #endif
  946. #if ENABLE_HUSH_TRAP
  947. char **traps; /* char *traps[NSIG] */
  948. # define G_traps G.traps
  949. #else
  950. # define G_traps ((char**)NULL)
  951. #endif
  952. sigset_t pending_set;
  953. #if ENABLE_HUSH_MEMLEAK
  954. unsigned long memleak_value;
  955. #endif
  956. #if ENABLE_HUSH_MODE_X
  957. unsigned x_mode_depth;
  958. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  959. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  960. * for all subsequent output.
  961. */
  962. int x_mode_fd;
  963. o_string x_mode_buf;
  964. #endif
  965. #if HUSH_DEBUG >= 2
  966. int debug_indent;
  967. #endif
  968. struct sigaction sa;
  969. #if BASH_EPOCH_VARS
  970. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  971. #endif
  972. #if ENABLE_FEATURE_EDITING
  973. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  974. #endif
  975. };
  976. #define G (*ptr_to_globals)
  977. /* Not #defining name to G.name - this quickly gets unwieldy
  978. * (too many defines). Also, I actually prefer to see when a variable
  979. * is global, thus "G." prefix is a useful hint */
  980. #define INIT_G() do { \
  981. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  982. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  983. sigfillset(&G.sa.sa_mask); \
  984. G.sa.sa_flags = SA_RESTART; \
  985. } while (0)
  986. /* Function prototypes for builtins */
  987. static int builtin_cd(char **argv) FAST_FUNC;
  988. #if ENABLE_HUSH_ECHO
  989. static int builtin_echo(char **argv) FAST_FUNC;
  990. #endif
  991. static int builtin_eval(char **argv) FAST_FUNC;
  992. static int builtin_exec(char **argv) FAST_FUNC;
  993. static int builtin_exit(char **argv) FAST_FUNC;
  994. #if ENABLE_HUSH_EXPORT
  995. static int builtin_export(char **argv) FAST_FUNC;
  996. #endif
  997. #if ENABLE_HUSH_READONLY
  998. static int builtin_readonly(char **argv) FAST_FUNC;
  999. #endif
  1000. #if ENABLE_HUSH_JOB
  1001. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1002. static int builtin_jobs(char **argv) FAST_FUNC;
  1003. #endif
  1004. #if ENABLE_HUSH_GETOPTS
  1005. static int builtin_getopts(char **argv) FAST_FUNC;
  1006. #endif
  1007. #if ENABLE_HUSH_HELP
  1008. static int builtin_help(char **argv) FAST_FUNC;
  1009. #endif
  1010. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1011. static int builtin_history(char **argv) FAST_FUNC;
  1012. #endif
  1013. #if ENABLE_HUSH_LOCAL
  1014. static int builtin_local(char **argv) FAST_FUNC;
  1015. #endif
  1016. #if ENABLE_HUSH_MEMLEAK
  1017. static int builtin_memleak(char **argv) FAST_FUNC;
  1018. #endif
  1019. #if ENABLE_HUSH_PRINTF
  1020. static int builtin_printf(char **argv) FAST_FUNC;
  1021. #endif
  1022. static int builtin_pwd(char **argv) FAST_FUNC;
  1023. #if ENABLE_HUSH_READ
  1024. static int builtin_read(char **argv) FAST_FUNC;
  1025. #endif
  1026. #if ENABLE_HUSH_SET
  1027. static int builtin_set(char **argv) FAST_FUNC;
  1028. #endif
  1029. static int builtin_shift(char **argv) FAST_FUNC;
  1030. static int builtin_source(char **argv) FAST_FUNC;
  1031. #if ENABLE_HUSH_TEST || BASH_TEST2
  1032. static int builtin_test(char **argv) FAST_FUNC;
  1033. #endif
  1034. #if ENABLE_HUSH_TRAP
  1035. static int builtin_trap(char **argv) FAST_FUNC;
  1036. #endif
  1037. #if ENABLE_HUSH_TYPE
  1038. static int builtin_type(char **argv) FAST_FUNC;
  1039. #endif
  1040. #if ENABLE_HUSH_TIMES
  1041. static int builtin_times(char **argv) FAST_FUNC;
  1042. #endif
  1043. static int builtin_true(char **argv) FAST_FUNC;
  1044. #if ENABLE_HUSH_UMASK
  1045. static int builtin_umask(char **argv) FAST_FUNC;
  1046. #endif
  1047. #if ENABLE_HUSH_UNSET
  1048. static int builtin_unset(char **argv) FAST_FUNC;
  1049. #endif
  1050. #if ENABLE_HUSH_KILL
  1051. static int builtin_kill(char **argv) FAST_FUNC;
  1052. #endif
  1053. #if ENABLE_HUSH_WAIT
  1054. static int builtin_wait(char **argv) FAST_FUNC;
  1055. #endif
  1056. #if ENABLE_HUSH_LOOPS
  1057. static int builtin_break(char **argv) FAST_FUNC;
  1058. static int builtin_continue(char **argv) FAST_FUNC;
  1059. #endif
  1060. #if ENABLE_HUSH_FUNCTIONS
  1061. static int builtin_return(char **argv) FAST_FUNC;
  1062. #endif
  1063. /* Table of built-in functions. They can be forked or not, depending on
  1064. * context: within pipes, they fork. As simple commands, they do not.
  1065. * When used in non-forking context, they can change global variables
  1066. * in the parent shell process. If forked, of course they cannot.
  1067. * For example, 'unset foo | whatever' will parse and run, but foo will
  1068. * still be set at the end. */
  1069. struct built_in_command {
  1070. const char *b_cmd;
  1071. int (*b_function)(char **argv) FAST_FUNC;
  1072. #if ENABLE_HUSH_HELP
  1073. const char *b_descr;
  1074. # define BLTIN(cmd, func, help) { cmd, func, help }
  1075. #else
  1076. # define BLTIN(cmd, func, help) { cmd, func }
  1077. #endif
  1078. };
  1079. static const struct built_in_command bltins1[] = {
  1080. BLTIN("." , builtin_source , "Run commands in file"),
  1081. BLTIN(":" , builtin_true , NULL),
  1082. #if ENABLE_HUSH_JOB
  1083. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1084. #endif
  1085. #if ENABLE_HUSH_LOOPS
  1086. BLTIN("break" , builtin_break , "Exit loop"),
  1087. #endif
  1088. BLTIN("cd" , builtin_cd , "Change directory"),
  1089. #if ENABLE_HUSH_LOOPS
  1090. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1091. #endif
  1092. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1093. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1094. BLTIN("exit" , builtin_exit , NULL),
  1095. #if ENABLE_HUSH_EXPORT
  1096. BLTIN("export" , builtin_export , "Set environment variables"),
  1097. #endif
  1098. #if ENABLE_HUSH_JOB
  1099. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1100. #endif
  1101. #if ENABLE_HUSH_GETOPTS
  1102. BLTIN("getopts" , builtin_getopts , NULL),
  1103. #endif
  1104. #if ENABLE_HUSH_HELP
  1105. BLTIN("help" , builtin_help , NULL),
  1106. #endif
  1107. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1108. BLTIN("history" , builtin_history , "Show history"),
  1109. #endif
  1110. #if ENABLE_HUSH_JOB
  1111. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1112. #endif
  1113. #if ENABLE_HUSH_KILL
  1114. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1115. #endif
  1116. #if ENABLE_HUSH_LOCAL
  1117. BLTIN("local" , builtin_local , "Set local variables"),
  1118. #endif
  1119. #if ENABLE_HUSH_MEMLEAK
  1120. BLTIN("memleak" , builtin_memleak , NULL),
  1121. #endif
  1122. #if ENABLE_HUSH_READ
  1123. BLTIN("read" , builtin_read , "Input into variable"),
  1124. #endif
  1125. #if ENABLE_HUSH_READONLY
  1126. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1127. #endif
  1128. #if ENABLE_HUSH_FUNCTIONS
  1129. BLTIN("return" , builtin_return , "Return from function"),
  1130. #endif
  1131. #if ENABLE_HUSH_SET
  1132. BLTIN("set" , builtin_set , "Set positional parameters"),
  1133. #endif
  1134. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1135. #if BASH_SOURCE
  1136. BLTIN("source" , builtin_source , NULL),
  1137. #endif
  1138. #if ENABLE_HUSH_TIMES
  1139. BLTIN("times" , builtin_times , NULL),
  1140. #endif
  1141. #if ENABLE_HUSH_TRAP
  1142. BLTIN("trap" , builtin_trap , "Trap signals"),
  1143. #endif
  1144. BLTIN("true" , builtin_true , NULL),
  1145. #if ENABLE_HUSH_TYPE
  1146. BLTIN("type" , builtin_type , "Show command type"),
  1147. #endif
  1148. #if ENABLE_HUSH_ULIMIT
  1149. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1150. #endif
  1151. #if ENABLE_HUSH_UMASK
  1152. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1153. #endif
  1154. #if ENABLE_HUSH_UNSET
  1155. BLTIN("unset" , builtin_unset , "Unset variables"),
  1156. #endif
  1157. #if ENABLE_HUSH_WAIT
  1158. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1159. #endif
  1160. };
  1161. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1162. * (it's cheaper to run an external program in this case):
  1163. */
  1164. static const struct built_in_command bltins2[] = {
  1165. #if ENABLE_HUSH_TEST
  1166. BLTIN("[" , builtin_test , NULL),
  1167. #endif
  1168. #if BASH_TEST2
  1169. BLTIN("[[" , builtin_test , NULL),
  1170. #endif
  1171. #if ENABLE_HUSH_ECHO
  1172. BLTIN("echo" , builtin_echo , NULL),
  1173. #endif
  1174. #if ENABLE_HUSH_PRINTF
  1175. BLTIN("printf" , builtin_printf , NULL),
  1176. #endif
  1177. BLTIN("pwd" , builtin_pwd , NULL),
  1178. #if ENABLE_HUSH_TEST
  1179. BLTIN("test" , builtin_test , NULL),
  1180. #endif
  1181. };
  1182. /* Debug printouts.
  1183. */
  1184. #if HUSH_DEBUG >= 2
  1185. /* prevent disasters with G.debug_indent < 0 */
  1186. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1187. # define debug_enter() (G.debug_indent++)
  1188. # define debug_leave() (G.debug_indent--)
  1189. #else
  1190. # define indent() ((void)0)
  1191. # define debug_enter() ((void)0)
  1192. # define debug_leave() ((void)0)
  1193. #endif
  1194. #ifndef debug_printf
  1195. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1196. #endif
  1197. #ifndef debug_printf_parse
  1198. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1199. #endif
  1200. #ifndef debug_printf_heredoc
  1201. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1202. #endif
  1203. #ifndef debug_printf_exec
  1204. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1205. #endif
  1206. #ifndef debug_printf_env
  1207. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1208. #endif
  1209. #ifndef debug_printf_jobs
  1210. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1211. # define DEBUG_JOBS 1
  1212. #else
  1213. # define DEBUG_JOBS 0
  1214. #endif
  1215. #ifndef debug_printf_expand
  1216. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. # define DEBUG_EXPAND 1
  1218. #else
  1219. # define DEBUG_EXPAND 0
  1220. #endif
  1221. #ifndef debug_printf_varexp
  1222. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. #endif
  1224. #ifndef debug_printf_glob
  1225. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. # define DEBUG_GLOB 1
  1227. #else
  1228. # define DEBUG_GLOB 0
  1229. #endif
  1230. #ifndef debug_printf_redir
  1231. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1232. #endif
  1233. #ifndef debug_printf_list
  1234. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1235. #endif
  1236. #ifndef debug_printf_subst
  1237. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1238. #endif
  1239. #ifndef debug_printf_prompt
  1240. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1241. #endif
  1242. #ifndef debug_printf_clean
  1243. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1244. # define DEBUG_CLEAN 1
  1245. #else
  1246. # define DEBUG_CLEAN 0
  1247. #endif
  1248. #if DEBUG_EXPAND
  1249. static void debug_print_strings(const char *prefix, char **vv)
  1250. {
  1251. indent();
  1252. fdprintf(2, "%s:\n", prefix);
  1253. while (*vv)
  1254. fdprintf(2, " '%s'\n", *vv++);
  1255. }
  1256. #else
  1257. # define debug_print_strings(prefix, vv) ((void)0)
  1258. #endif
  1259. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1260. */
  1261. #if LEAK_HUNTING
  1262. static void *xxmalloc(int lineno, size_t size)
  1263. {
  1264. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1265. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1266. return ptr;
  1267. }
  1268. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1269. {
  1270. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1271. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1272. return ptr;
  1273. }
  1274. static char *xxstrdup(int lineno, const char *str)
  1275. {
  1276. char *ptr = xstrdup(str);
  1277. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1278. return ptr;
  1279. }
  1280. static void xxfree(void *ptr)
  1281. {
  1282. fdprintf(2, "free %p\n", ptr);
  1283. free(ptr);
  1284. }
  1285. # define xmalloc(s) xxmalloc(__LINE__, s)
  1286. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1287. # define xstrdup(s) xxstrdup(__LINE__, s)
  1288. # define free(p) xxfree(p)
  1289. #endif
  1290. /* Syntax and runtime errors. They always abort scripts.
  1291. * In interactive use they usually discard unparsed and/or unexecuted commands
  1292. * and return to the prompt.
  1293. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1294. */
  1295. #if HUSH_DEBUG < 2
  1296. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1297. # define syntax_error(lineno, msg) syntax_error(msg)
  1298. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1299. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1300. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1301. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1302. #endif
  1303. static void die_if_script(void)
  1304. {
  1305. if (!G_interactive_fd) {
  1306. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1307. xfunc_error_retval = G.last_exitcode;
  1308. xfunc_die();
  1309. }
  1310. }
  1311. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1312. {
  1313. va_list p;
  1314. #if HUSH_DEBUG >= 2
  1315. bb_error_msg("hush.c:%u", lineno);
  1316. #endif
  1317. va_start(p, fmt);
  1318. bb_verror_msg(fmt, p, NULL);
  1319. va_end(p);
  1320. die_if_script();
  1321. }
  1322. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1323. {
  1324. if (msg)
  1325. bb_error_msg("syntax error: %s", msg);
  1326. else
  1327. bb_error_msg("syntax error");
  1328. die_if_script();
  1329. }
  1330. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1331. {
  1332. bb_error_msg("syntax error at '%s'", msg);
  1333. die_if_script();
  1334. }
  1335. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1336. {
  1337. bb_error_msg("syntax error: unterminated %s", s);
  1338. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1339. // die_if_script();
  1340. }
  1341. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1342. {
  1343. char msg[2] = { ch, '\0' };
  1344. syntax_error_unterm_str(lineno, msg);
  1345. }
  1346. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1347. {
  1348. char msg[2];
  1349. msg[0] = ch;
  1350. msg[1] = '\0';
  1351. #if HUSH_DEBUG >= 2
  1352. bb_error_msg("hush.c:%u", lineno);
  1353. #endif
  1354. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1355. die_if_script();
  1356. }
  1357. #if HUSH_DEBUG < 2
  1358. # undef msg_and_die_if_script
  1359. # undef syntax_error
  1360. # undef syntax_error_at
  1361. # undef syntax_error_unterm_ch
  1362. # undef syntax_error_unterm_str
  1363. # undef syntax_error_unexpected_ch
  1364. #else
  1365. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1366. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1367. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1368. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1369. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1370. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1371. #endif
  1372. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1373. static void cmdedit_update_prompt(void);
  1374. #else
  1375. # define cmdedit_update_prompt() ((void)0)
  1376. #endif
  1377. /* Utility functions
  1378. */
  1379. /* Replace each \x with x in place, return ptr past NUL. */
  1380. static char *unbackslash(char *src)
  1381. {
  1382. char *dst = src = strchrnul(src, '\\');
  1383. while (1) {
  1384. if (*src == '\\') {
  1385. src++;
  1386. if (*src != '\0') {
  1387. /* \x -> x */
  1388. *dst++ = *src++;
  1389. continue;
  1390. }
  1391. /* else: "\<nul>". Do not delete this backslash.
  1392. * Testcase: eval 'echo ok\'
  1393. */
  1394. *dst++ = '\\';
  1395. /* fallthrough */
  1396. }
  1397. if ((*dst++ = *src++) == '\0')
  1398. break;
  1399. }
  1400. return dst;
  1401. }
  1402. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1403. {
  1404. int i;
  1405. unsigned count1;
  1406. unsigned count2;
  1407. char **v;
  1408. v = strings;
  1409. count1 = 0;
  1410. if (v) {
  1411. while (*v) {
  1412. count1++;
  1413. v++;
  1414. }
  1415. }
  1416. count2 = 0;
  1417. v = add;
  1418. while (*v) {
  1419. count2++;
  1420. v++;
  1421. }
  1422. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1423. v[count1 + count2] = NULL;
  1424. i = count2;
  1425. while (--i >= 0)
  1426. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1427. return v;
  1428. }
  1429. #if LEAK_HUNTING
  1430. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1431. {
  1432. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1433. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1434. return ptr;
  1435. }
  1436. #define add_strings_to_strings(strings, add, need_to_dup) \
  1437. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1438. #endif
  1439. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1440. static char **add_string_to_strings(char **strings, char *add)
  1441. {
  1442. char *v[2];
  1443. v[0] = add;
  1444. v[1] = NULL;
  1445. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1446. }
  1447. #if LEAK_HUNTING
  1448. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1449. {
  1450. char **ptr = add_string_to_strings(strings, add);
  1451. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1452. return ptr;
  1453. }
  1454. #define add_string_to_strings(strings, add) \
  1455. xx_add_string_to_strings(__LINE__, strings, add)
  1456. #endif
  1457. static void free_strings(char **strings)
  1458. {
  1459. char **v;
  1460. if (!strings)
  1461. return;
  1462. v = strings;
  1463. while (*v) {
  1464. free(*v);
  1465. v++;
  1466. }
  1467. free(strings);
  1468. }
  1469. static int dup_CLOEXEC(int fd, int avoid_fd)
  1470. {
  1471. int newfd;
  1472. repeat:
  1473. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1474. if (newfd >= 0) {
  1475. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1476. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1477. } else { /* newfd < 0 */
  1478. if (errno == EBUSY)
  1479. goto repeat;
  1480. if (errno == EINTR)
  1481. goto repeat;
  1482. }
  1483. return newfd;
  1484. }
  1485. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1486. {
  1487. int newfd;
  1488. repeat:
  1489. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1490. if (newfd < 0) {
  1491. if (errno == EBUSY)
  1492. goto repeat;
  1493. if (errno == EINTR)
  1494. goto repeat;
  1495. /* fd was not open? */
  1496. if (errno == EBADF)
  1497. return fd;
  1498. xfunc_die();
  1499. }
  1500. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1501. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1502. close(fd);
  1503. return newfd;
  1504. }
  1505. /* Manipulating HFILEs */
  1506. static HFILE *hfopen(const char *name)
  1507. {
  1508. HFILE *fp;
  1509. int fd;
  1510. fd = STDIN_FILENO;
  1511. if (name) {
  1512. fd = open(name, O_RDONLY | O_CLOEXEC);
  1513. if (fd < 0)
  1514. return NULL;
  1515. if (O_CLOEXEC == 0) /* ancient libc */
  1516. close_on_exec_on(fd);
  1517. }
  1518. fp = xmalloc(sizeof(*fp));
  1519. fp->is_stdin = (name == NULL);
  1520. fp->fd = fd;
  1521. fp->cur = fp->end = fp->buf;
  1522. fp->next_hfile = G.HFILE_list;
  1523. G.HFILE_list = fp;
  1524. return fp;
  1525. }
  1526. static void hfclose(HFILE *fp)
  1527. {
  1528. HFILE **pp = &G.HFILE_list;
  1529. while (*pp) {
  1530. HFILE *cur = *pp;
  1531. if (cur == fp) {
  1532. *pp = cur->next_hfile;
  1533. break;
  1534. }
  1535. pp = &cur->next_hfile;
  1536. }
  1537. if (fp->fd >= 0)
  1538. close(fp->fd);
  1539. free(fp);
  1540. }
  1541. static int refill_HFILE_and_getc(HFILE *fp)
  1542. {
  1543. int n;
  1544. if (fp->fd < 0) {
  1545. /* Already saw EOF */
  1546. return EOF;
  1547. }
  1548. /* Try to buffer more input */
  1549. fp->cur = fp->buf;
  1550. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1551. if (n < 0) {
  1552. bb_perror_msg("read error");
  1553. n = 0;
  1554. }
  1555. fp->end = fp->buf + n;
  1556. if (n == 0) {
  1557. /* EOF/error */
  1558. close(fp->fd);
  1559. fp->fd = -1;
  1560. return EOF;
  1561. }
  1562. return (unsigned char)(*fp->cur++);
  1563. }
  1564. /* Inlined for common case of non-empty buffer.
  1565. */
  1566. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1567. {
  1568. if (fp->cur < fp->end)
  1569. return (unsigned char)(*fp->cur++);
  1570. /* Buffer empty */
  1571. return refill_HFILE_and_getc(fp);
  1572. }
  1573. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1574. {
  1575. HFILE *fl = G.HFILE_list;
  1576. while (fl) {
  1577. if (fd == fl->fd) {
  1578. /* We use it only on script files, they are all CLOEXEC */
  1579. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1580. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1581. return 1; /* "found and moved" */
  1582. }
  1583. fl = fl->next_hfile;
  1584. }
  1585. #if ENABLE_HUSH_MODE_X
  1586. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1587. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1588. return 1; /* "found and moved" */
  1589. }
  1590. #endif
  1591. return 0; /* "not in the list" */
  1592. }
  1593. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1594. static void close_all_HFILE_list(void)
  1595. {
  1596. HFILE *fl = G.HFILE_list;
  1597. while (fl) {
  1598. /* hfclose would also free HFILE object.
  1599. * It is disastrous if we share memory with a vforked parent.
  1600. * I'm not sure we never come here after vfork.
  1601. * Therefore just close fd, nothing more.
  1602. *
  1603. * ">" instead of ">=": we don't close fd#0,
  1604. * interactive shell uses hfopen(NULL) as stdin input
  1605. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1606. * If we'd close it here, then e.g. interactive "set | sort"
  1607. * with NOFORKed sort, would have sort's input fd closed.
  1608. */
  1609. if (fl->fd > 0)
  1610. /*hfclose(fl); - unsafe */
  1611. close(fl->fd);
  1612. fl = fl->next_hfile;
  1613. }
  1614. }
  1615. #endif
  1616. static int fd_in_HFILEs(int fd)
  1617. {
  1618. HFILE *fl = G.HFILE_list;
  1619. while (fl) {
  1620. if (fl->fd == fd)
  1621. return 1;
  1622. fl = fl->next_hfile;
  1623. }
  1624. return 0;
  1625. }
  1626. /* Helpers for setting new $n and restoring them back
  1627. */
  1628. typedef struct save_arg_t {
  1629. char *sv_argv0;
  1630. char **sv_g_argv;
  1631. int sv_g_argc;
  1632. IF_HUSH_SET(smallint sv_g_malloced;)
  1633. } save_arg_t;
  1634. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1635. {
  1636. sv->sv_argv0 = argv[0];
  1637. sv->sv_g_argv = G.global_argv;
  1638. sv->sv_g_argc = G.global_argc;
  1639. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1640. argv[0] = G.global_argv[0]; /* retain $0 */
  1641. G.global_argv = argv;
  1642. IF_HUSH_SET(G.global_args_malloced = 0;)
  1643. G.global_argc = 1 + string_array_len(argv + 1);
  1644. }
  1645. static void restore_G_args(save_arg_t *sv, char **argv)
  1646. {
  1647. #if ENABLE_HUSH_SET
  1648. if (G.global_args_malloced) {
  1649. /* someone ran "set -- arg1 arg2 ...", undo */
  1650. char **pp = G.global_argv;
  1651. while (*++pp) /* note: does not free $0 */
  1652. free(*pp);
  1653. free(G.global_argv);
  1654. }
  1655. #endif
  1656. argv[0] = sv->sv_argv0;
  1657. G.global_argv = sv->sv_g_argv;
  1658. G.global_argc = sv->sv_g_argc;
  1659. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1660. }
  1661. /* Basic theory of signal handling in shell
  1662. * ========================================
  1663. * This does not describe what hush does, rather, it is current understanding
  1664. * what it _should_ do. If it doesn't, it's a bug.
  1665. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1666. *
  1667. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1668. * is finished or backgrounded. It is the same in interactive and
  1669. * non-interactive shells, and is the same regardless of whether
  1670. * a user trap handler is installed or a shell special one is in effect.
  1671. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1672. * backgrounds (i.e. stops) or kills all members of currently running
  1673. * pipe.
  1674. *
  1675. * Wait builtin is interruptible by signals for which user trap is set
  1676. * or by SIGINT in interactive shell.
  1677. *
  1678. * Trap handlers will execute even within trap handlers. (right?)
  1679. *
  1680. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1681. * except for handlers set to '' (empty string).
  1682. *
  1683. * If job control is off, backgrounded commands ("cmd &")
  1684. * have SIGINT, SIGQUIT set to SIG_IGN.
  1685. *
  1686. * Commands which are run in command substitution ("`cmd`")
  1687. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1688. *
  1689. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1690. * by the shell from its parent.
  1691. *
  1692. * Signals which differ from SIG_DFL action
  1693. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1694. *
  1695. * SIGQUIT: ignore
  1696. * SIGTERM (interactive): ignore
  1697. * SIGHUP (interactive):
  1698. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1699. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1700. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1701. * that all pipe members are stopped. Try this in bash:
  1702. * while :; do :; done - ^Z does not background it
  1703. * (while :; do :; done) - ^Z backgrounds it
  1704. * SIGINT (interactive): wait for last pipe, ignore the rest
  1705. * of the command line, show prompt. NB: ^C does not send SIGINT
  1706. * to interactive shell while shell is waiting for a pipe,
  1707. * since shell is bg'ed (is not in foreground process group).
  1708. * Example 1: this waits 5 sec, but does not execute ls:
  1709. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1710. * Example 2: this does not wait and does not execute ls:
  1711. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1712. * Example 3: this does not wait 5 sec, but executes ls:
  1713. * "sleep 5; ls -l" + press ^C
  1714. * Example 4: this does not wait and does not execute ls:
  1715. * "sleep 5 & wait; ls -l" + press ^C
  1716. *
  1717. * (What happens to signals which are IGN on shell start?)
  1718. * (What happens with signal mask on shell start?)
  1719. *
  1720. * Old implementation
  1721. * ==================
  1722. * We use in-kernel pending signal mask to determine which signals were sent.
  1723. * We block all signals which we don't want to take action immediately,
  1724. * i.e. we block all signals which need to have special handling as described
  1725. * above, and all signals which have traps set.
  1726. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1727. * and act on them.
  1728. *
  1729. * unsigned special_sig_mask: a mask of such "special" signals
  1730. * sigset_t blocked_set: current blocked signal set
  1731. *
  1732. * "trap - SIGxxx":
  1733. * clear bit in blocked_set unless it is also in special_sig_mask
  1734. * "trap 'cmd' SIGxxx":
  1735. * set bit in blocked_set (even if 'cmd' is '')
  1736. * after [v]fork, if we plan to be a shell:
  1737. * unblock signals with special interactive handling
  1738. * (child shell is not interactive),
  1739. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1740. * after [v]fork, if we plan to exec:
  1741. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1742. * Restore blocked signal set to one inherited by shell just prior to exec.
  1743. *
  1744. * Note: as a result, we do not use signal handlers much. The only uses
  1745. * are to count SIGCHLDs
  1746. * and to restore tty pgrp on signal-induced exit.
  1747. *
  1748. * Note 2 (compat):
  1749. * Standard says "When a subshell is entered, traps that are not being ignored
  1750. * are set to the default actions". bash interprets it so that traps which
  1751. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1752. *
  1753. * Problem: the above approach makes it unwieldy to catch signals while
  1754. * we are in read builtin, or while we read commands from stdin:
  1755. * masked signals are not visible!
  1756. *
  1757. * New implementation
  1758. * ==================
  1759. * We record each signal we are interested in by installing signal handler
  1760. * for them - a bit like emulating kernel pending signal mask in userspace.
  1761. * We are interested in: signals which need to have special handling
  1762. * as described above, and all signals which have traps set.
  1763. * Signals are recorded in pending_set.
  1764. * After each pipe execution, we extract any pending signals
  1765. * and act on them.
  1766. *
  1767. * unsigned special_sig_mask: a mask of shell-special signals.
  1768. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1769. * char *traps[sig] if trap for sig is set (even if it's '').
  1770. * sigset_t pending_set: set of sigs we received.
  1771. *
  1772. * "trap - SIGxxx":
  1773. * if sig is in special_sig_mask, set handler back to:
  1774. * record_pending_signo, or to IGN if it's a tty stop signal
  1775. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1776. * else: set handler back to SIG_DFL
  1777. * "trap 'cmd' SIGxxx":
  1778. * set handler to record_pending_signo.
  1779. * "trap '' SIGxxx":
  1780. * set handler to SIG_IGN.
  1781. * after [v]fork, if we plan to be a shell:
  1782. * set signals with special interactive handling to SIG_DFL
  1783. * (because child shell is not interactive),
  1784. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1785. * after [v]fork, if we plan to exec:
  1786. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1787. *
  1788. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1789. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1790. *
  1791. * Note (compat):
  1792. * Standard says "When a subshell is entered, traps that are not being ignored
  1793. * are set to the default actions". bash interprets it so that traps which
  1794. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1795. */
  1796. enum {
  1797. SPECIAL_INTERACTIVE_SIGS = 0
  1798. | (1 << SIGTERM)
  1799. | (1 << SIGINT)
  1800. | (1 << SIGHUP)
  1801. ,
  1802. SPECIAL_JOBSTOP_SIGS = 0
  1803. #if ENABLE_HUSH_JOB
  1804. | (1 << SIGTTIN)
  1805. | (1 << SIGTTOU)
  1806. | (1 << SIGTSTP)
  1807. #endif
  1808. ,
  1809. };
  1810. static void record_pending_signo(int sig)
  1811. {
  1812. sigaddset(&G.pending_set, sig);
  1813. #if ENABLE_HUSH_FAST
  1814. if (sig == SIGCHLD) {
  1815. G.count_SIGCHLD++;
  1816. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1817. }
  1818. #endif
  1819. }
  1820. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1821. {
  1822. struct sigaction old_sa;
  1823. /* We could use signal() to install handlers... almost:
  1824. * except that we need to mask ALL signals while handlers run.
  1825. * I saw signal nesting in strace, race window isn't small.
  1826. * SA_RESTART is also needed, but in Linux, signal()
  1827. * sets SA_RESTART too.
  1828. */
  1829. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1830. /* sigfillset(&G.sa.sa_mask); - already done */
  1831. /* G.sa.sa_flags = SA_RESTART; - already done */
  1832. G.sa.sa_handler = handler;
  1833. sigaction(sig, &G.sa, &old_sa);
  1834. return old_sa.sa_handler;
  1835. }
  1836. static void hush_exit(int exitcode) NORETURN;
  1837. static void restore_ttypgrp_and__exit(void) NORETURN;
  1838. static void restore_ttypgrp_and__exit(void)
  1839. {
  1840. /* xfunc has failed! die die die */
  1841. /* no EXIT traps, this is an escape hatch! */
  1842. G.exiting = 1;
  1843. hush_exit(xfunc_error_retval);
  1844. }
  1845. #if ENABLE_HUSH_JOB
  1846. /* Needed only on some libc:
  1847. * It was observed that on exit(), fgetc'ed buffered data
  1848. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1849. * With the net effect that even after fork(), not vfork(),
  1850. * exit() in NOEXECed applet in "sh SCRIPT":
  1851. * noexec_applet_here
  1852. * echo END_OF_SCRIPT
  1853. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1854. * This makes "echo END_OF_SCRIPT" executed twice.
  1855. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1856. * and in `cmd` handling.
  1857. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1858. */
  1859. static void fflush_and__exit(void) NORETURN;
  1860. static void fflush_and__exit(void)
  1861. {
  1862. fflush_all();
  1863. _exit(xfunc_error_retval);
  1864. }
  1865. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1866. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1867. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1868. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1869. /* Restores tty foreground process group, and exits.
  1870. * May be called as signal handler for fatal signal
  1871. * (will resend signal to itself, producing correct exit state)
  1872. * or called directly with -EXITCODE.
  1873. * We also call it if xfunc is exiting.
  1874. */
  1875. static void sigexit(int sig) NORETURN;
  1876. static void sigexit(int sig)
  1877. {
  1878. /* Careful: we can end up here after [v]fork. Do not restore
  1879. * tty pgrp then, only top-level shell process does that */
  1880. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1881. /* Disable all signals: job control, SIGPIPE, etc.
  1882. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1883. */
  1884. sigprocmask_allsigs(SIG_BLOCK);
  1885. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1886. }
  1887. /* Not a signal, just exit */
  1888. if (sig <= 0)
  1889. _exit(- sig);
  1890. kill_myself_with_sig(sig); /* does not return */
  1891. }
  1892. #else
  1893. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1894. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1895. #endif
  1896. static sighandler_t pick_sighandler(unsigned sig)
  1897. {
  1898. sighandler_t handler = SIG_DFL;
  1899. if (sig < sizeof(unsigned)*8) {
  1900. unsigned sigmask = (1 << sig);
  1901. #if ENABLE_HUSH_JOB
  1902. /* is sig fatal? */
  1903. if (G_fatal_sig_mask & sigmask)
  1904. handler = sigexit;
  1905. else
  1906. #endif
  1907. /* sig has special handling? */
  1908. if (G.special_sig_mask & sigmask) {
  1909. handler = record_pending_signo;
  1910. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1911. * in order to ignore them: they will be raised
  1912. * in an endless loop when we try to do some
  1913. * terminal ioctls! We do have to _ignore_ these.
  1914. */
  1915. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1916. handler = SIG_IGN;
  1917. }
  1918. }
  1919. return handler;
  1920. }
  1921. /* Restores tty foreground process group, and exits. */
  1922. static void hush_exit(int exitcode)
  1923. {
  1924. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1925. save_history(G.line_input_state);
  1926. #endif
  1927. fflush_all();
  1928. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1929. char *argv[3];
  1930. /* argv[0] is unused */
  1931. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1932. argv[2] = NULL;
  1933. G.exiting = 1; /* prevent EXIT trap recursion */
  1934. /* Note: G_traps[0] is not cleared!
  1935. * "trap" will still show it, if executed
  1936. * in the handler */
  1937. builtin_eval(argv);
  1938. }
  1939. #if ENABLE_FEATURE_CLEAN_UP
  1940. {
  1941. struct variable *cur_var;
  1942. if (G.cwd != bb_msg_unknown)
  1943. free((char*)G.cwd);
  1944. cur_var = G.top_var;
  1945. while (cur_var) {
  1946. struct variable *tmp = cur_var;
  1947. if (!cur_var->max_len)
  1948. free(cur_var->varstr);
  1949. cur_var = cur_var->next;
  1950. free(tmp);
  1951. }
  1952. }
  1953. #endif
  1954. fflush_all();
  1955. #if ENABLE_HUSH_JOB
  1956. sigexit(- (exitcode & 0xff));
  1957. #else
  1958. _exit(exitcode);
  1959. #endif
  1960. }
  1961. //TODO: return a mask of ALL handled sigs?
  1962. static int check_and_run_traps(void)
  1963. {
  1964. int last_sig = 0;
  1965. while (1) {
  1966. int sig;
  1967. if (sigisemptyset(&G.pending_set))
  1968. break;
  1969. sig = 0;
  1970. do {
  1971. sig++;
  1972. if (sigismember(&G.pending_set, sig)) {
  1973. sigdelset(&G.pending_set, sig);
  1974. goto got_sig;
  1975. }
  1976. } while (sig < NSIG);
  1977. break;
  1978. got_sig:
  1979. if (G_traps && G_traps[sig]) {
  1980. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1981. if (G_traps[sig][0]) {
  1982. /* We have user-defined handler */
  1983. smalluint save_rcode;
  1984. char *argv[3];
  1985. /* argv[0] is unused */
  1986. argv[1] = xstrdup(G_traps[sig]);
  1987. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1988. argv[2] = NULL;
  1989. save_rcode = G.last_exitcode;
  1990. builtin_eval(argv);
  1991. free(argv[1]);
  1992. //FIXME: shouldn't it be set to 128 + sig instead?
  1993. G.last_exitcode = save_rcode;
  1994. last_sig = sig;
  1995. } /* else: "" trap, ignoring signal */
  1996. continue;
  1997. }
  1998. /* not a trap: special action */
  1999. switch (sig) {
  2000. case SIGINT:
  2001. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2002. G.flag_SIGINT = 1;
  2003. last_sig = sig;
  2004. break;
  2005. #if ENABLE_HUSH_JOB
  2006. case SIGHUP: {
  2007. //TODO: why are we doing this? ash and dash don't do this,
  2008. //they have no handler for SIGHUP at all,
  2009. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2010. struct pipe *job;
  2011. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2012. /* bash is observed to signal whole process groups,
  2013. * not individual processes */
  2014. for (job = G.job_list; job; job = job->next) {
  2015. if (job->pgrp <= 0)
  2016. continue;
  2017. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2018. if (kill(- job->pgrp, SIGHUP) == 0)
  2019. kill(- job->pgrp, SIGCONT);
  2020. }
  2021. sigexit(SIGHUP);
  2022. }
  2023. #endif
  2024. #if ENABLE_HUSH_FAST
  2025. case SIGCHLD:
  2026. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2027. G.count_SIGCHLD++;
  2028. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2029. /* Note:
  2030. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2031. * This simplifies wait builtin a bit.
  2032. */
  2033. break;
  2034. #endif
  2035. default: /* ignored: */
  2036. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2037. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2038. /* Note:
  2039. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2040. * Example: wait is not interrupted by TERM
  2041. * in interactive shell, because TERM is ignored.
  2042. */
  2043. break;
  2044. }
  2045. }
  2046. return last_sig;
  2047. }
  2048. static const char *get_cwd(int force)
  2049. {
  2050. if (force || G.cwd == NULL) {
  2051. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2052. * we must not try to free(bb_msg_unknown) */
  2053. if (G.cwd == bb_msg_unknown)
  2054. G.cwd = NULL;
  2055. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2056. if (!G.cwd)
  2057. G.cwd = bb_msg_unknown;
  2058. }
  2059. return G.cwd;
  2060. }
  2061. /*
  2062. * Shell and environment variable support
  2063. */
  2064. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2065. {
  2066. struct variable **pp;
  2067. struct variable *cur;
  2068. pp = &G.top_var;
  2069. while ((cur = *pp) != NULL) {
  2070. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2071. return pp;
  2072. pp = &cur->next;
  2073. }
  2074. return NULL;
  2075. }
  2076. static const char* FAST_FUNC get_local_var_value(const char *name)
  2077. {
  2078. struct variable **vpp;
  2079. unsigned len = strlen(name);
  2080. if (G.expanded_assignments) {
  2081. char **cpp = G.expanded_assignments;
  2082. while (*cpp) {
  2083. char *cp = *cpp;
  2084. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2085. return cp + len + 1;
  2086. cpp++;
  2087. }
  2088. }
  2089. vpp = get_ptr_to_local_var(name, len);
  2090. if (vpp)
  2091. return (*vpp)->varstr + len + 1;
  2092. if (strcmp(name, "PPID") == 0)
  2093. return utoa(G.root_ppid);
  2094. // bash compat: UID? EUID?
  2095. #if ENABLE_HUSH_RANDOM_SUPPORT
  2096. if (strcmp(name, "RANDOM") == 0)
  2097. return utoa(next_random(&G.random_gen));
  2098. #endif
  2099. #if BASH_EPOCH_VARS
  2100. {
  2101. const char *fmt = NULL;
  2102. if (strcmp(name, "EPOCHSECONDS") == 0)
  2103. fmt = "%lu";
  2104. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2105. fmt = "%lu.%06u";
  2106. if (fmt) {
  2107. struct timeval tv;
  2108. gettimeofday(&tv, NULL);
  2109. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2110. (unsigned)tv.tv_usec);
  2111. return G.epoch_buf;
  2112. }
  2113. }
  2114. #endif
  2115. return NULL;
  2116. }
  2117. static void handle_changed_special_names(const char *name, unsigned name_len)
  2118. {
  2119. if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2120. && name_len == 3 && name[0] == 'P' && name[1] == 'S'
  2121. ) {
  2122. cmdedit_update_prompt();
  2123. return;
  2124. }
  2125. if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
  2126. && name_len == 6
  2127. ) {
  2128. #if ENABLE_HUSH_LINENO_VAR
  2129. if (strncmp(name, "LINENO", 6) == 0) {
  2130. G.lineno_var = NULL;
  2131. return;
  2132. }
  2133. #endif
  2134. #if ENABLE_HUSH_GETOPTS
  2135. if (strncmp(name, "OPTIND", 6) == 0) {
  2136. G.getopt_count = 0;
  2137. return;
  2138. }
  2139. #endif
  2140. }
  2141. }
  2142. /* str holds "NAME=VAL" and is expected to be malloced.
  2143. * We take ownership of it.
  2144. */
  2145. #define SETFLAG_EXPORT (1 << 0)
  2146. #define SETFLAG_UNEXPORT (1 << 1)
  2147. #define SETFLAG_MAKE_RO (1 << 2)
  2148. #define SETFLAG_VARLVL_SHIFT 3
  2149. static int set_local_var(char *str, unsigned flags)
  2150. {
  2151. struct variable **cur_pp;
  2152. struct variable *cur;
  2153. char *free_me = NULL;
  2154. char *eq_sign;
  2155. int name_len;
  2156. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2157. eq_sign = strchr(str, '=');
  2158. if (HUSH_DEBUG && !eq_sign)
  2159. bb_error_msg_and_die("BUG in setvar");
  2160. name_len = eq_sign - str + 1; /* including '=' */
  2161. cur_pp = &G.top_var;
  2162. while ((cur = *cur_pp) != NULL) {
  2163. if (strncmp(cur->varstr, str, name_len) != 0) {
  2164. cur_pp = &cur->next;
  2165. continue;
  2166. }
  2167. /* We found an existing var with this name */
  2168. if (cur->flg_read_only) {
  2169. bb_error_msg("%s: readonly variable", str);
  2170. free(str);
  2171. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2172. //but export per se succeeds (does put the var in env). We don't mimic that.
  2173. return -1;
  2174. }
  2175. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2176. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2177. *eq_sign = '\0';
  2178. unsetenv(str);
  2179. *eq_sign = '=';
  2180. }
  2181. if (cur->var_nest_level < local_lvl) {
  2182. /* bash 3.2.33(1) and exported vars:
  2183. * # export z=z
  2184. * # f() { local z=a; env | grep ^z; }
  2185. * # f
  2186. * z=a
  2187. * # env | grep ^z
  2188. * z=z
  2189. */
  2190. if (cur->flg_export)
  2191. flags |= SETFLAG_EXPORT;
  2192. /* New variable is local ("local VAR=VAL" or
  2193. * "VAR=VAL cmd")
  2194. * and existing one is global, or local
  2195. * on a lower level that new one.
  2196. * Remove it from global variable list:
  2197. */
  2198. *cur_pp = cur->next;
  2199. if (G.shadowed_vars_pp) {
  2200. /* Save in "shadowed" list */
  2201. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2202. cur->flg_export ? "exported " : "",
  2203. cur->varstr, cur->var_nest_level, str, local_lvl
  2204. );
  2205. cur->next = *G.shadowed_vars_pp;
  2206. *G.shadowed_vars_pp = cur;
  2207. } else {
  2208. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2209. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2210. cur->flg_export ? "exported " : "",
  2211. cur->varstr, cur->var_nest_level, str, local_lvl
  2212. );
  2213. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2214. free_me = cur->varstr; /* then free it later */
  2215. free(cur);
  2216. }
  2217. break;
  2218. }
  2219. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2220. debug_printf_env("assignement '%s' does not change anything\n", str);
  2221. free_and_exp:
  2222. free(str);
  2223. goto exp;
  2224. }
  2225. /* Replace the value in the found "struct variable" */
  2226. if (cur->max_len != 0) {
  2227. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2228. /* This one is from startup env, reuse space */
  2229. debug_printf_env("reusing startup env for '%s'\n", str);
  2230. strcpy(cur->varstr, str);
  2231. goto free_and_exp;
  2232. }
  2233. /* Can't reuse */
  2234. cur->max_len = 0;
  2235. goto set_str_and_exp;
  2236. }
  2237. /* max_len == 0 signifies "malloced" var, which we can
  2238. * (and have to) free. But we can't free(cur->varstr) here:
  2239. * if cur->flg_export is 1, it is in the environment.
  2240. * We should either unsetenv+free, or wait until putenv,
  2241. * then putenv(new)+free(old).
  2242. */
  2243. free_me = cur->varstr;
  2244. goto set_str_and_exp;
  2245. }
  2246. /* Not found or shadowed - create new variable struct */
  2247. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2248. cur = xzalloc(sizeof(*cur));
  2249. cur->var_nest_level = local_lvl;
  2250. cur->next = *cur_pp;
  2251. *cur_pp = cur;
  2252. set_str_and_exp:
  2253. cur->varstr = str;
  2254. exp:
  2255. #if !BB_MMU || ENABLE_HUSH_READONLY
  2256. if (flags & SETFLAG_MAKE_RO) {
  2257. cur->flg_read_only = 1;
  2258. }
  2259. #endif
  2260. if (flags & SETFLAG_EXPORT)
  2261. cur->flg_export = 1;
  2262. if (cur->flg_export) {
  2263. if (flags & SETFLAG_UNEXPORT) {
  2264. cur->flg_export = 0;
  2265. /* unsetenv was already done */
  2266. } else {
  2267. int i;
  2268. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2269. i = putenv(cur->varstr);
  2270. /* only now we can free old exported malloced string */
  2271. free(free_me);
  2272. return i;
  2273. }
  2274. }
  2275. free(free_me);
  2276. handle_changed_special_names(cur->varstr, name_len - 1);
  2277. return 0;
  2278. }
  2279. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2280. {
  2281. char *var = xasprintf("%s=%s", name, val);
  2282. set_local_var(var, /*flag:*/ 0);
  2283. }
  2284. /* Used at startup and after each cd */
  2285. static void set_pwd_var(unsigned flag)
  2286. {
  2287. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2288. }
  2289. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2290. static int unset_local_var_len(const char *name, int name_len)
  2291. {
  2292. struct variable *cur;
  2293. struct variable **cur_pp;
  2294. cur_pp = &G.top_var;
  2295. while ((cur = *cur_pp) != NULL) {
  2296. if (strncmp(cur->varstr, name, name_len) == 0
  2297. && cur->varstr[name_len] == '='
  2298. ) {
  2299. if (cur->flg_read_only) {
  2300. bb_error_msg("%s: readonly variable", name);
  2301. return EXIT_FAILURE;
  2302. }
  2303. *cur_pp = cur->next;
  2304. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2305. bb_unsetenv(cur->varstr);
  2306. if (!cur->max_len)
  2307. free(cur->varstr);
  2308. free(cur);
  2309. break;
  2310. }
  2311. cur_pp = &cur->next;
  2312. }
  2313. /* Handle "unset PS1" et al even if did not find the variable to unset */
  2314. handle_changed_special_names(name, name_len);
  2315. return EXIT_SUCCESS;
  2316. }
  2317. static int unset_local_var(const char *name)
  2318. {
  2319. return unset_local_var_len(name, strlen(name));
  2320. }
  2321. #endif
  2322. /*
  2323. * Helpers for "var1=val1 var2=val2 cmd" feature
  2324. */
  2325. static void add_vars(struct variable *var)
  2326. {
  2327. struct variable *next;
  2328. while (var) {
  2329. next = var->next;
  2330. var->next = G.top_var;
  2331. G.top_var = var;
  2332. if (var->flg_export) {
  2333. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2334. putenv(var->varstr);
  2335. } else {
  2336. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2337. }
  2338. var = next;
  2339. }
  2340. }
  2341. /* We put strings[i] into variable table and possibly putenv them.
  2342. * If variable is read only, we can free the strings[i]
  2343. * which attempts to overwrite it.
  2344. * The strings[] vector itself is freed.
  2345. */
  2346. static void set_vars_and_save_old(char **strings)
  2347. {
  2348. char **s;
  2349. if (!strings)
  2350. return;
  2351. s = strings;
  2352. while (*s) {
  2353. struct variable *var_p;
  2354. struct variable **var_pp;
  2355. char *eq;
  2356. eq = strchr(*s, '=');
  2357. if (HUSH_DEBUG && !eq)
  2358. bb_error_msg_and_die("BUG in varexp4");
  2359. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2360. if (var_pp) {
  2361. var_p = *var_pp;
  2362. if (var_p->flg_read_only) {
  2363. char **p;
  2364. bb_error_msg("%s: readonly variable", *s);
  2365. /*
  2366. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2367. * If VAR is readonly, leaving it in the list
  2368. * after asssignment error (msg above)
  2369. * causes doubled error message later, on unset.
  2370. */
  2371. debug_printf_env("removing/freeing '%s' element\n", *s);
  2372. free(*s);
  2373. p = s;
  2374. do { *p = p[1]; p++; } while (*p);
  2375. goto next;
  2376. }
  2377. /* below, set_local_var() with nest level will
  2378. * "shadow" (remove) this variable from
  2379. * global linked list.
  2380. */
  2381. }
  2382. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2383. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2384. s++;
  2385. next: ;
  2386. }
  2387. free(strings);
  2388. }
  2389. /*
  2390. * Unicode helper
  2391. */
  2392. static void reinit_unicode_for_hush(void)
  2393. {
  2394. /* Unicode support should be activated even if LANG is set
  2395. * _during_ shell execution, not only if it was set when
  2396. * shell was started. Therefore, re-check LANG every time:
  2397. */
  2398. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2399. || ENABLE_UNICODE_USING_LOCALE
  2400. ) {
  2401. const char *s = get_local_var_value("LC_ALL");
  2402. if (!s) s = get_local_var_value("LC_CTYPE");
  2403. if (!s) s = get_local_var_value("LANG");
  2404. reinit_unicode(s);
  2405. }
  2406. }
  2407. /*
  2408. * in_str support (strings, and "strings" read from files).
  2409. */
  2410. #if ENABLE_HUSH_INTERACTIVE
  2411. /* To test correct lineedit/interactive behavior, type from command line:
  2412. * echo $P\
  2413. * \
  2414. * AT\
  2415. * H\
  2416. * \
  2417. * It exercises a lot of corner cases.
  2418. */
  2419. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2420. static void cmdedit_update_prompt(void)
  2421. {
  2422. G.PS1 = get_local_var_value("PS1");
  2423. if (G.PS1 == NULL)
  2424. G.PS1 = "";
  2425. G.PS2 = get_local_var_value("PS2");
  2426. if (G.PS2 == NULL)
  2427. G.PS2 = "";
  2428. }
  2429. # endif
  2430. static const char *setup_prompt_string(void)
  2431. {
  2432. const char *prompt_str;
  2433. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2434. IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
  2435. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
  2436. if (G.promptmode == 0) { /* PS1 */
  2437. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  2438. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2439. free((char*)G.PS1);
  2440. /* bash uses $PWD value, even if it is set by user.
  2441. * It uses current dir only if PWD is unset.
  2442. * We always use current dir. */
  2443. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2444. }
  2445. prompt_str = G.PS1;
  2446. }
  2447. debug_printf("prompt_str '%s'\n", prompt_str);
  2448. return prompt_str;
  2449. }
  2450. static int get_user_input(struct in_str *i)
  2451. {
  2452. int r;
  2453. const char *prompt_str;
  2454. prompt_str = setup_prompt_string();
  2455. # if ENABLE_FEATURE_EDITING
  2456. for (;;) {
  2457. reinit_unicode_for_hush();
  2458. if (G.flag_SIGINT) {
  2459. /* There was ^C'ed, make it look prettier: */
  2460. bb_putchar('\n');
  2461. G.flag_SIGINT = 0;
  2462. }
  2463. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2464. * only after <Enter>. (^C works immediately) */
  2465. r = read_line_input(G.line_input_state, prompt_str,
  2466. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2467. );
  2468. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2469. if (r == 0)
  2470. raise(SIGINT);
  2471. check_and_run_traps();
  2472. if (r != 0 && !G.flag_SIGINT)
  2473. break;
  2474. /* ^C or SIGINT: repeat */
  2475. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2476. write(STDOUT_FILENO, "^C", 2);
  2477. G.last_exitcode = 128 + SIGINT;
  2478. }
  2479. if (r < 0) {
  2480. /* EOF/error detected */
  2481. i->p = NULL;
  2482. i->peek_buf[0] = r = EOF;
  2483. return r;
  2484. }
  2485. i->p = G.user_input_buf;
  2486. return (unsigned char)*i->p++;
  2487. # else
  2488. for (;;) {
  2489. G.flag_SIGINT = 0;
  2490. if (i->last_char == '\0' || i->last_char == '\n') {
  2491. /* Why check_and_run_traps here? Try this interactively:
  2492. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2493. * $ <[enter], repeatedly...>
  2494. * Without check_and_run_traps, handler never runs.
  2495. */
  2496. check_and_run_traps();
  2497. fputs(prompt_str, stdout);
  2498. }
  2499. fflush_all();
  2500. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2501. r = hfgetc(i->file);
  2502. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2503. * no ^C masking happens during fgetc, no special code for ^C:
  2504. * it generates SIGINT as usual.
  2505. */
  2506. check_and_run_traps();
  2507. if (G.flag_SIGINT)
  2508. G.last_exitcode = 128 + SIGINT;
  2509. if (r != '\0')
  2510. break;
  2511. }
  2512. return r;
  2513. # endif
  2514. }
  2515. /* This is the magic location that prints prompts
  2516. * and gets data back from the user */
  2517. static int fgetc_interactive(struct in_str *i)
  2518. {
  2519. int ch;
  2520. /* If it's interactive stdin, get new line. */
  2521. if (G_interactive_fd && i->file->is_stdin) {
  2522. /* Returns first char (or EOF), the rest is in i->p[] */
  2523. ch = get_user_input(i);
  2524. G.promptmode = 1; /* PS2 */
  2525. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2526. } else {
  2527. /* Not stdin: script file, sourced file, etc */
  2528. do ch = hfgetc(i->file); while (ch == '\0');
  2529. }
  2530. return ch;
  2531. }
  2532. #else
  2533. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2534. {
  2535. int ch;
  2536. do ch = hfgetc(i->file); while (ch == '\0');
  2537. return ch;
  2538. }
  2539. #endif /* INTERACTIVE */
  2540. static int i_getch(struct in_str *i)
  2541. {
  2542. int ch;
  2543. if (!i->file) {
  2544. /* string-based in_str */
  2545. ch = (unsigned char)*i->p;
  2546. if (ch != '\0') {
  2547. i->p++;
  2548. i->last_char = ch;
  2549. return ch;
  2550. }
  2551. return EOF;
  2552. }
  2553. /* FILE-based in_str */
  2554. #if ENABLE_FEATURE_EDITING
  2555. /* This can be stdin, check line editing char[] buffer */
  2556. if (i->p && *i->p != '\0') {
  2557. ch = (unsigned char)*i->p++;
  2558. goto out;
  2559. }
  2560. #endif
  2561. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2562. ch = i->peek_buf[0];
  2563. if (ch != 0) {
  2564. int ch2 = i->peek_buf[1];
  2565. i->peek_buf[0] = ch2;
  2566. if (ch2 == 0) /* very likely, avoid redundant write */
  2567. goto out;
  2568. i->peek_buf[1] = 0;
  2569. goto out;
  2570. }
  2571. ch = fgetc_interactive(i);
  2572. out:
  2573. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2574. i->last_char = ch;
  2575. #if ENABLE_HUSH_LINENO_VAR
  2576. if (ch == '\n') {
  2577. G.lineno++;
  2578. debug_printf_parse("G.lineno++ = %u\n", G.lineno);
  2579. }
  2580. #endif
  2581. return ch;
  2582. }
  2583. static int i_peek(struct in_str *i)
  2584. {
  2585. int ch;
  2586. if (!i->file) {
  2587. /* string-based in_str */
  2588. /* Doesn't report EOF on NUL. None of the callers care. */
  2589. return (unsigned char)*i->p;
  2590. }
  2591. /* FILE-based in_str */
  2592. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2593. /* This can be stdin, check line editing char[] buffer */
  2594. if (i->p && *i->p != '\0')
  2595. return (unsigned char)*i->p;
  2596. #endif
  2597. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2598. ch = i->peek_buf[0];
  2599. if (ch != 0)
  2600. return ch;
  2601. /* Need to get a new char */
  2602. ch = fgetc_interactive(i);
  2603. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2604. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2605. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2606. if (i->p) {
  2607. i->p -= 1;
  2608. return ch;
  2609. }
  2610. #endif
  2611. i->peek_buf[0] = ch;
  2612. /*i->peek_buf[1] = 0; - already is */
  2613. return ch;
  2614. }
  2615. /* Only ever called if i_peek() was called, and did not return EOF.
  2616. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2617. * not end-of-line. Therefore we never need to read a new editing line here.
  2618. */
  2619. static int i_peek2(struct in_str *i)
  2620. {
  2621. int ch;
  2622. /* There are two cases when i->p[] buffer exists.
  2623. * (1) it's a string in_str.
  2624. * (2) It's a file, and we have a saved line editing buffer.
  2625. * In both cases, we know that i->p[0] exists and not NUL, and
  2626. * the peek2 result is in i->p[1].
  2627. */
  2628. if (i->p)
  2629. return (unsigned char)i->p[1];
  2630. /* Now we know it is a file-based in_str. */
  2631. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2632. /* Is there 2nd char? */
  2633. ch = i->peek_buf[1];
  2634. if (ch == 0) {
  2635. /* We did not read it yet, get it now */
  2636. do ch = hfgetc(i->file); while (ch == '\0');
  2637. i->peek_buf[1] = ch;
  2638. }
  2639. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2640. return ch;
  2641. }
  2642. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2643. {
  2644. for (;;) {
  2645. int ch, ch2;
  2646. ch = i_getch(input);
  2647. if (ch != '\\')
  2648. return ch;
  2649. ch2 = i_peek(input);
  2650. if (ch2 != '\n')
  2651. return ch;
  2652. /* backslash+newline, skip it */
  2653. i_getch(input);
  2654. }
  2655. }
  2656. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2657. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2658. */
  2659. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2660. {
  2661. for (;;) {
  2662. int ch, ch2;
  2663. ch = i_peek(input);
  2664. if (ch != '\\')
  2665. return ch;
  2666. ch2 = i_peek2(input);
  2667. if (ch2 != '\n')
  2668. return ch;
  2669. /* backslash+newline, skip it */
  2670. i_getch(input);
  2671. i_getch(input);
  2672. }
  2673. }
  2674. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2675. {
  2676. memset(i, 0, sizeof(*i));
  2677. i->file = fp;
  2678. /* i->p = NULL; */
  2679. }
  2680. static void setup_string_in_str(struct in_str *i, const char *s)
  2681. {
  2682. memset(i, 0, sizeof(*i));
  2683. /*i->file = NULL */;
  2684. i->p = s;
  2685. }
  2686. /*
  2687. * o_string support
  2688. */
  2689. #define B_CHUNK (32 * sizeof(char*))
  2690. static void o_reset_to_empty_unquoted(o_string *o)
  2691. {
  2692. o->length = 0;
  2693. o->has_quoted_part = 0;
  2694. if (o->data)
  2695. o->data[0] = '\0';
  2696. }
  2697. static void o_free_and_set_NULL(o_string *o)
  2698. {
  2699. free(o->data);
  2700. memset(o, 0, sizeof(*o));
  2701. }
  2702. static ALWAYS_INLINE void o_free(o_string *o)
  2703. {
  2704. free(o->data);
  2705. }
  2706. static void o_grow_by(o_string *o, int len)
  2707. {
  2708. if (o->length + len > o->maxlen) {
  2709. o->maxlen += (2 * len) | (B_CHUNK-1);
  2710. o->data = xrealloc(o->data, 1 + o->maxlen);
  2711. }
  2712. }
  2713. static void o_addchr(o_string *o, int ch)
  2714. {
  2715. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2716. if (o->length < o->maxlen) {
  2717. /* likely. avoid o_grow_by() call */
  2718. add:
  2719. o->data[o->length] = ch;
  2720. o->length++;
  2721. o->data[o->length] = '\0';
  2722. return;
  2723. }
  2724. o_grow_by(o, 1);
  2725. goto add;
  2726. }
  2727. #if 0
  2728. /* Valid only if we know o_string is not empty */
  2729. static void o_delchr(o_string *o)
  2730. {
  2731. o->length--;
  2732. o->data[o->length] = '\0';
  2733. }
  2734. #endif
  2735. static void o_addblock(o_string *o, const char *str, int len)
  2736. {
  2737. o_grow_by(o, len);
  2738. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2739. o->length += len;
  2740. }
  2741. static void o_addstr(o_string *o, const char *str)
  2742. {
  2743. o_addblock(o, str, strlen(str));
  2744. }
  2745. static void o_addstr_with_NUL(o_string *o, const char *str)
  2746. {
  2747. o_addblock(o, str, strlen(str) + 1);
  2748. }
  2749. #if !BB_MMU
  2750. static void nommu_addchr(o_string *o, int ch)
  2751. {
  2752. if (o)
  2753. o_addchr(o, ch);
  2754. }
  2755. #else
  2756. # define nommu_addchr(o, str) ((void)0)
  2757. #endif
  2758. #if ENABLE_HUSH_MODE_X
  2759. static void x_mode_addchr(int ch)
  2760. {
  2761. o_addchr(&G.x_mode_buf, ch);
  2762. }
  2763. static void x_mode_addstr(const char *str)
  2764. {
  2765. o_addstr(&G.x_mode_buf, str);
  2766. }
  2767. static void x_mode_addblock(const char *str, int len)
  2768. {
  2769. o_addblock(&G.x_mode_buf, str, len);
  2770. }
  2771. static void x_mode_prefix(void)
  2772. {
  2773. int n = G.x_mode_depth;
  2774. do x_mode_addchr('+'); while (--n >= 0);
  2775. }
  2776. static void x_mode_flush(void)
  2777. {
  2778. int len = G.x_mode_buf.length;
  2779. if (len <= 0)
  2780. return;
  2781. if (G.x_mode_fd > 0) {
  2782. G.x_mode_buf.data[len] = '\n';
  2783. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2784. }
  2785. G.x_mode_buf.length = 0;
  2786. }
  2787. #endif
  2788. /*
  2789. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2790. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2791. * Apparently, on unquoted $v bash still does globbing
  2792. * ("v='*.txt'; echo $v" prints all .txt files),
  2793. * but NOT brace expansion! Thus, there should be TWO independent
  2794. * quoting mechanisms on $v expansion side: one protects
  2795. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2796. * We have only second one.
  2797. */
  2798. #if ENABLE_HUSH_BRACE_EXPANSION
  2799. # define MAYBE_BRACES "{}"
  2800. #else
  2801. # define MAYBE_BRACES ""
  2802. #endif
  2803. /* My analysis of quoting semantics tells me that state information
  2804. * is associated with a destination, not a source.
  2805. */
  2806. static void o_addqchr(o_string *o, int ch)
  2807. {
  2808. int sz = 1;
  2809. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2810. if (found)
  2811. sz++;
  2812. o_grow_by(o, sz);
  2813. if (found) {
  2814. o->data[o->length] = '\\';
  2815. o->length++;
  2816. }
  2817. o->data[o->length] = ch;
  2818. o->length++;
  2819. o->data[o->length] = '\0';
  2820. }
  2821. static void o_addQchr(o_string *o, int ch)
  2822. {
  2823. int sz = 1;
  2824. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2825. && strchr("*?[\\" MAYBE_BRACES, ch)
  2826. ) {
  2827. sz++;
  2828. o->data[o->length] = '\\';
  2829. o->length++;
  2830. }
  2831. o_grow_by(o, sz);
  2832. o->data[o->length] = ch;
  2833. o->length++;
  2834. o->data[o->length] = '\0';
  2835. }
  2836. static void o_addqblock(o_string *o, const char *str, int len)
  2837. {
  2838. while (len) {
  2839. char ch;
  2840. int sz;
  2841. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2842. if (ordinary_cnt > len) /* paranoia */
  2843. ordinary_cnt = len;
  2844. o_addblock(o, str, ordinary_cnt);
  2845. if (ordinary_cnt == len)
  2846. return; /* NUL is already added by o_addblock */
  2847. str += ordinary_cnt;
  2848. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2849. ch = *str++;
  2850. sz = 1;
  2851. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2852. sz++;
  2853. o->data[o->length] = '\\';
  2854. o->length++;
  2855. }
  2856. o_grow_by(o, sz);
  2857. o->data[o->length] = ch;
  2858. o->length++;
  2859. }
  2860. o->data[o->length] = '\0';
  2861. }
  2862. static void o_addQblock(o_string *o, const char *str, int len)
  2863. {
  2864. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2865. o_addblock(o, str, len);
  2866. return;
  2867. }
  2868. o_addqblock(o, str, len);
  2869. }
  2870. static void o_addQstr(o_string *o, const char *str)
  2871. {
  2872. o_addQblock(o, str, strlen(str));
  2873. }
  2874. /* A special kind of o_string for $VAR and `cmd` expansion.
  2875. * It contains char* list[] at the beginning, which is grown in 16 element
  2876. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2877. * list[i] contains an INDEX (int!) into this string data.
  2878. * It means that if list[] needs to grow, data needs to be moved higher up
  2879. * but list[i]'s need not be modified.
  2880. * NB: remembering how many list[i]'s you have there is crucial.
  2881. * o_finalize_list() operation post-processes this structure - calculates
  2882. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2883. */
  2884. #if DEBUG_EXPAND || DEBUG_GLOB
  2885. static void debug_print_list(const char *prefix, o_string *o, int n)
  2886. {
  2887. char **list = (char**)o->data;
  2888. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2889. int i = 0;
  2890. indent();
  2891. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2892. prefix, list, n, string_start, o->length, o->maxlen,
  2893. !!(o->o_expflags & EXP_FLAG_GLOB),
  2894. o->has_quoted_part,
  2895. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2896. while (i < n) {
  2897. indent();
  2898. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2899. o->data + (int)(uintptr_t)list[i] + string_start,
  2900. o->data + (int)(uintptr_t)list[i] + string_start);
  2901. i++;
  2902. }
  2903. if (n) {
  2904. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2905. indent();
  2906. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2907. }
  2908. }
  2909. #else
  2910. # define debug_print_list(prefix, o, n) ((void)0)
  2911. #endif
  2912. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2913. * in list[n] so that it points past last stored byte so far.
  2914. * It returns n+1. */
  2915. static int o_save_ptr_helper(o_string *o, int n)
  2916. {
  2917. char **list = (char**)o->data;
  2918. int string_start;
  2919. int string_len;
  2920. if (!o->has_empty_slot) {
  2921. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2922. string_len = o->length - string_start;
  2923. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2924. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2925. /* list[n] points to string_start, make space for 16 more pointers */
  2926. o->maxlen += 0x10 * sizeof(list[0]);
  2927. o->data = xrealloc(o->data, o->maxlen + 1);
  2928. list = (char**)o->data;
  2929. memmove(list + n + 0x10, list + n, string_len);
  2930. /*
  2931. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2932. * check. (grep for -prev-ifs-check-).
  2933. * Ensure that argv[-1][last] is not garbage
  2934. * but zero bytes, to save index check there.
  2935. */
  2936. list[n + 0x10 - 1] = 0;
  2937. o->length += 0x10 * sizeof(list[0]);
  2938. } else {
  2939. debug_printf_list("list[%d]=%d string_start=%d\n",
  2940. n, string_len, string_start);
  2941. }
  2942. } else {
  2943. /* We have empty slot at list[n], reuse without growth */
  2944. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2945. string_len = o->length - string_start;
  2946. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2947. n, string_len, string_start);
  2948. o->has_empty_slot = 0;
  2949. }
  2950. o->has_quoted_part = 0;
  2951. list[n] = (char*)(uintptr_t)string_len;
  2952. return n + 1;
  2953. }
  2954. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2955. static int o_get_last_ptr(o_string *o, int n)
  2956. {
  2957. char **list = (char**)o->data;
  2958. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2959. return ((int)(uintptr_t)list[n-1]) + string_start;
  2960. }
  2961. /*
  2962. * Globbing routines.
  2963. *
  2964. * Most words in commands need to be globbed, even ones which are
  2965. * (single or double) quoted. This stems from the possiblity of
  2966. * constructs like "abc"* and 'abc'* - these should be globbed.
  2967. * Having a different code path for fully-quoted strings ("abc",
  2968. * 'abc') would only help performance-wise, but we still need
  2969. * code for partially-quoted strings.
  2970. *
  2971. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2972. * the logic can't be "shell-syntax argument is first transformed
  2973. * to a string, then globbed, and if globbing does not match anything,
  2974. * it is used verbatim". Here are two examples where it fails:
  2975. *
  2976. * echo 'b\*'?
  2977. *
  2978. * The globbing can't be avoided (because of '?' at the end).
  2979. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2980. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2981. * - IOW: they "unbackslash" the glob pattern.
  2982. * Now, look at this:
  2983. *
  2984. * v='\\\*'; echo b$v?
  2985. *
  2986. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2987. * should be used as glob pattern with no changes. However, if glob
  2988. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2989. *
  2990. * ash implements this by having an encoded representation of the word
  2991. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2992. * Glob pattern is derived from it. If glob fails, the decision what result
  2993. * should be is made using that encoded representation. Not glob pattern.
  2994. */
  2995. #if ENABLE_HUSH_BRACE_EXPANSION
  2996. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2997. * first, it processes even {a} (no commas), second,
  2998. * I didn't manage to make it return strings when they don't match
  2999. * existing files. Need to re-implement it.
  3000. */
  3001. /* Helper */
  3002. static int glob_needed(const char *s)
  3003. {
  3004. while (*s) {
  3005. if (*s == '\\') {
  3006. if (!s[1])
  3007. return 0;
  3008. s += 2;
  3009. continue;
  3010. }
  3011. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3012. return 1;
  3013. s++;
  3014. }
  3015. return 0;
  3016. }
  3017. /* Return pointer to next closing brace or to comma */
  3018. static const char *next_brace_sub(const char *cp)
  3019. {
  3020. unsigned depth = 0;
  3021. cp++;
  3022. while (*cp != '\0') {
  3023. if (*cp == '\\') {
  3024. if (*++cp == '\0')
  3025. break;
  3026. cp++;
  3027. continue;
  3028. }
  3029. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3030. break;
  3031. if (*cp++ == '{')
  3032. depth++;
  3033. }
  3034. return *cp != '\0' ? cp : NULL;
  3035. }
  3036. /* Recursive brace globber. Note: may garble pattern[]. */
  3037. static int glob_brace(char *pattern, o_string *o, int n)
  3038. {
  3039. char *new_pattern_buf;
  3040. const char *begin;
  3041. const char *next;
  3042. const char *rest;
  3043. const char *p;
  3044. size_t rest_len;
  3045. debug_printf_glob("glob_brace('%s')\n", pattern);
  3046. begin = pattern;
  3047. while (1) {
  3048. if (*begin == '\0')
  3049. goto simple_glob;
  3050. if (*begin == '{') {
  3051. /* Find the first sub-pattern and at the same time
  3052. * find the rest after the closing brace */
  3053. next = next_brace_sub(begin);
  3054. if (next == NULL) {
  3055. /* An illegal expression */
  3056. goto simple_glob;
  3057. }
  3058. if (*next == '}') {
  3059. /* "{abc}" with no commas - illegal
  3060. * brace expr, disregard and skip it */
  3061. begin = next + 1;
  3062. continue;
  3063. }
  3064. break;
  3065. }
  3066. if (*begin == '\\' && begin[1] != '\0')
  3067. begin++;
  3068. begin++;
  3069. }
  3070. debug_printf_glob("begin:%s\n", begin);
  3071. debug_printf_glob("next:%s\n", next);
  3072. /* Now find the end of the whole brace expression */
  3073. rest = next;
  3074. while (*rest != '}') {
  3075. rest = next_brace_sub(rest);
  3076. if (rest == NULL) {
  3077. /* An illegal expression */
  3078. goto simple_glob;
  3079. }
  3080. debug_printf_glob("rest:%s\n", rest);
  3081. }
  3082. rest_len = strlen(++rest) + 1;
  3083. /* We are sure the brace expression is well-formed */
  3084. /* Allocate working buffer large enough for our work */
  3085. new_pattern_buf = xmalloc(strlen(pattern));
  3086. /* We have a brace expression. BEGIN points to the opening {,
  3087. * NEXT points past the terminator of the first element, and REST
  3088. * points past the final }. We will accumulate result names from
  3089. * recursive runs for each brace alternative in the buffer using
  3090. * GLOB_APPEND. */
  3091. p = begin + 1;
  3092. while (1) {
  3093. /* Construct the new glob expression */
  3094. memcpy(
  3095. mempcpy(
  3096. mempcpy(new_pattern_buf,
  3097. /* We know the prefix for all sub-patterns */
  3098. pattern, begin - pattern),
  3099. p, next - p),
  3100. rest, rest_len);
  3101. /* Note: glob_brace() may garble new_pattern_buf[].
  3102. * That's why we re-copy prefix every time (1st memcpy above).
  3103. */
  3104. n = glob_brace(new_pattern_buf, o, n);
  3105. if (*next == '}') {
  3106. /* We saw the last entry */
  3107. break;
  3108. }
  3109. p = next + 1;
  3110. next = next_brace_sub(next);
  3111. }
  3112. free(new_pattern_buf);
  3113. return n;
  3114. simple_glob:
  3115. {
  3116. int gr;
  3117. glob_t globdata;
  3118. memset(&globdata, 0, sizeof(globdata));
  3119. gr = glob(pattern, 0, NULL, &globdata);
  3120. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3121. if (gr != 0) {
  3122. if (gr == GLOB_NOMATCH) {
  3123. globfree(&globdata);
  3124. /* NB: garbles parameter */
  3125. unbackslash(pattern);
  3126. o_addstr_with_NUL(o, pattern);
  3127. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3128. return o_save_ptr_helper(o, n);
  3129. }
  3130. if (gr == GLOB_NOSPACE)
  3131. bb_die_memory_exhausted();
  3132. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3133. * but we didn't specify it. Paranoia again. */
  3134. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3135. }
  3136. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3137. char **argv = globdata.gl_pathv;
  3138. while (1) {
  3139. o_addstr_with_NUL(o, *argv);
  3140. n = o_save_ptr_helper(o, n);
  3141. argv++;
  3142. if (!*argv)
  3143. break;
  3144. }
  3145. }
  3146. globfree(&globdata);
  3147. }
  3148. return n;
  3149. }
  3150. /* Performs globbing on last list[],
  3151. * saving each result as a new list[].
  3152. */
  3153. static int perform_glob(o_string *o, int n)
  3154. {
  3155. char *pattern, *copy;
  3156. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3157. if (!o->data)
  3158. return o_save_ptr_helper(o, n);
  3159. pattern = o->data + o_get_last_ptr(o, n);
  3160. debug_printf_glob("glob pattern '%s'\n", pattern);
  3161. if (!glob_needed(pattern)) {
  3162. /* unbackslash last string in o in place, fix length */
  3163. o->length = unbackslash(pattern) - o->data;
  3164. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3165. return o_save_ptr_helper(o, n);
  3166. }
  3167. copy = xstrdup(pattern);
  3168. /* "forget" pattern in o */
  3169. o->length = pattern - o->data;
  3170. n = glob_brace(copy, o, n);
  3171. free(copy);
  3172. if (DEBUG_GLOB)
  3173. debug_print_list("perform_glob returning", o, n);
  3174. return n;
  3175. }
  3176. #else /* !HUSH_BRACE_EXPANSION */
  3177. /* Helper */
  3178. static int glob_needed(const char *s)
  3179. {
  3180. while (*s) {
  3181. if (*s == '\\') {
  3182. if (!s[1])
  3183. return 0;
  3184. s += 2;
  3185. continue;
  3186. }
  3187. if (*s == '*' || *s == '[' || *s == '?')
  3188. return 1;
  3189. s++;
  3190. }
  3191. return 0;
  3192. }
  3193. /* Performs globbing on last list[],
  3194. * saving each result as a new list[].
  3195. */
  3196. static int perform_glob(o_string *o, int n)
  3197. {
  3198. glob_t globdata;
  3199. int gr;
  3200. char *pattern;
  3201. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3202. if (!o->data)
  3203. return o_save_ptr_helper(o, n);
  3204. pattern = o->data + o_get_last_ptr(o, n);
  3205. debug_printf_glob("glob pattern '%s'\n", pattern);
  3206. if (!glob_needed(pattern)) {
  3207. literal:
  3208. /* unbackslash last string in o in place, fix length */
  3209. o->length = unbackslash(pattern) - o->data;
  3210. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3211. return o_save_ptr_helper(o, n);
  3212. }
  3213. memset(&globdata, 0, sizeof(globdata));
  3214. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3215. * If we glob "*.\*" and don't find anything, we need
  3216. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3217. * will return "*.\*"!
  3218. */
  3219. gr = glob(pattern, 0, NULL, &globdata);
  3220. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3221. if (gr != 0) {
  3222. if (gr == GLOB_NOMATCH) {
  3223. globfree(&globdata);
  3224. goto literal;
  3225. }
  3226. if (gr == GLOB_NOSPACE)
  3227. bb_die_memory_exhausted();
  3228. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3229. * but we didn't specify it. Paranoia again. */
  3230. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3231. }
  3232. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3233. char **argv = globdata.gl_pathv;
  3234. /* "forget" pattern in o */
  3235. o->length = pattern - o->data;
  3236. while (1) {
  3237. o_addstr_with_NUL(o, *argv);
  3238. n = o_save_ptr_helper(o, n);
  3239. argv++;
  3240. if (!*argv)
  3241. break;
  3242. }
  3243. }
  3244. globfree(&globdata);
  3245. if (DEBUG_GLOB)
  3246. debug_print_list("perform_glob returning", o, n);
  3247. return n;
  3248. }
  3249. #endif /* !HUSH_BRACE_EXPANSION */
  3250. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3251. * Otherwise, just finish current list[] and start new */
  3252. static int o_save_ptr(o_string *o, int n)
  3253. {
  3254. if (o->o_expflags & EXP_FLAG_GLOB) {
  3255. /* If o->has_empty_slot, list[n] was already globbed
  3256. * (if it was requested back then when it was filled)
  3257. * so don't do that again! */
  3258. if (!o->has_empty_slot)
  3259. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3260. }
  3261. return o_save_ptr_helper(o, n);
  3262. }
  3263. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3264. static char **o_finalize_list(o_string *o, int n)
  3265. {
  3266. char **list;
  3267. int string_start;
  3268. if (DEBUG_EXPAND)
  3269. debug_print_list("finalized", o, n);
  3270. debug_printf_expand("finalized n:%d\n", n);
  3271. list = (char**)o->data;
  3272. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3273. list[--n] = NULL;
  3274. while (n) {
  3275. n--;
  3276. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3277. }
  3278. return list;
  3279. }
  3280. static void free_pipe_list(struct pipe *pi);
  3281. /* Returns pi->next - next pipe in the list */
  3282. static struct pipe *free_pipe(struct pipe *pi)
  3283. {
  3284. struct pipe *next;
  3285. int i;
  3286. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3287. for (i = 0; i < pi->num_cmds; i++) {
  3288. struct command *command;
  3289. struct redir_struct *r, *rnext;
  3290. command = &pi->cmds[i];
  3291. debug_printf_clean(" command %d:\n", i);
  3292. if (command->argv) {
  3293. if (DEBUG_CLEAN) {
  3294. int a;
  3295. char **p;
  3296. for (a = 0, p = command->argv; *p; a++, p++) {
  3297. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3298. }
  3299. }
  3300. free_strings(command->argv);
  3301. //command->argv = NULL;
  3302. }
  3303. /* not "else if": on syntax error, we may have both! */
  3304. if (command->group) {
  3305. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3306. command->cmd_type);
  3307. free_pipe_list(command->group);
  3308. debug_printf_clean(" end group\n");
  3309. //command->group = NULL;
  3310. }
  3311. /* else is crucial here.
  3312. * If group != NULL, child_func is meaningless */
  3313. #if ENABLE_HUSH_FUNCTIONS
  3314. else if (command->child_func) {
  3315. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3316. command->child_func->parent_cmd = NULL;
  3317. }
  3318. #endif
  3319. #if !BB_MMU
  3320. free(command->group_as_string);
  3321. //command->group_as_string = NULL;
  3322. #endif
  3323. for (r = command->redirects; r; r = rnext) {
  3324. debug_printf_clean(" redirect %d%s",
  3325. r->rd_fd, redir_table[r->rd_type].descrip);
  3326. /* guard against the case >$FOO, where foo is unset or blank */
  3327. if (r->rd_filename) {
  3328. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3329. free(r->rd_filename);
  3330. //r->rd_filename = NULL;
  3331. }
  3332. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3333. rnext = r->next;
  3334. free(r);
  3335. }
  3336. //command->redirects = NULL;
  3337. }
  3338. free(pi->cmds); /* children are an array, they get freed all at once */
  3339. //pi->cmds = NULL;
  3340. #if ENABLE_HUSH_JOB
  3341. free(pi->cmdtext);
  3342. //pi->cmdtext = NULL;
  3343. #endif
  3344. next = pi->next;
  3345. free(pi);
  3346. return next;
  3347. }
  3348. static void free_pipe_list(struct pipe *pi)
  3349. {
  3350. while (pi) {
  3351. #if HAS_KEYWORDS
  3352. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3353. #endif
  3354. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3355. pi = free_pipe(pi);
  3356. }
  3357. }
  3358. /*** Parsing routines ***/
  3359. #ifndef debug_print_tree
  3360. static void debug_print_tree(struct pipe *pi, int lvl)
  3361. {
  3362. static const char *const PIPE[] = {
  3363. [PIPE_SEQ] = "SEQ",
  3364. [PIPE_AND] = "AND",
  3365. [PIPE_OR ] = "OR" ,
  3366. [PIPE_BG ] = "BG" ,
  3367. };
  3368. static const char *RES[] = {
  3369. [RES_NONE ] = "NONE" ,
  3370. # if ENABLE_HUSH_IF
  3371. [RES_IF ] = "IF" ,
  3372. [RES_THEN ] = "THEN" ,
  3373. [RES_ELIF ] = "ELIF" ,
  3374. [RES_ELSE ] = "ELSE" ,
  3375. [RES_FI ] = "FI" ,
  3376. # endif
  3377. # if ENABLE_HUSH_LOOPS
  3378. [RES_FOR ] = "FOR" ,
  3379. [RES_WHILE] = "WHILE",
  3380. [RES_UNTIL] = "UNTIL",
  3381. [RES_DO ] = "DO" ,
  3382. [RES_DONE ] = "DONE" ,
  3383. # endif
  3384. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3385. [RES_IN ] = "IN" ,
  3386. # endif
  3387. # if ENABLE_HUSH_CASE
  3388. [RES_CASE ] = "CASE" ,
  3389. [RES_CASE_IN ] = "CASE_IN" ,
  3390. [RES_MATCH] = "MATCH",
  3391. [RES_CASE_BODY] = "CASE_BODY",
  3392. [RES_ESAC ] = "ESAC" ,
  3393. # endif
  3394. [RES_XXXX ] = "XXXX" ,
  3395. [RES_SNTX ] = "SNTX" ,
  3396. };
  3397. static const char *const CMDTYPE[] = {
  3398. "{}",
  3399. "()",
  3400. "[noglob]",
  3401. # if ENABLE_HUSH_FUNCTIONS
  3402. "func()",
  3403. # endif
  3404. };
  3405. int pin, prn;
  3406. pin = 0;
  3407. while (pi) {
  3408. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3409. lvl*2, "",
  3410. pin,
  3411. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3412. RES[pi->res_word],
  3413. pi->followup, PIPE[pi->followup]
  3414. );
  3415. prn = 0;
  3416. while (prn < pi->num_cmds) {
  3417. struct command *command = &pi->cmds[prn];
  3418. char **argv = command->argv;
  3419. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3420. lvl*2, "", prn,
  3421. command->assignment_cnt);
  3422. #if ENABLE_HUSH_LINENO_VAR
  3423. fdprintf(2, " LINENO:%u", command->lineno);
  3424. #endif
  3425. if (command->group) {
  3426. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3427. CMDTYPE[command->cmd_type],
  3428. argv
  3429. # if !BB_MMU
  3430. , " group_as_string:", command->group_as_string
  3431. # else
  3432. , "", ""
  3433. # endif
  3434. );
  3435. debug_print_tree(command->group, lvl+1);
  3436. prn++;
  3437. continue;
  3438. }
  3439. if (argv) while (*argv) {
  3440. fdprintf(2, " '%s'", *argv);
  3441. argv++;
  3442. }
  3443. if (command->redirects)
  3444. fdprintf(2, " {redir}");
  3445. fdprintf(2, "\n");
  3446. prn++;
  3447. }
  3448. pi = pi->next;
  3449. pin++;
  3450. }
  3451. }
  3452. #endif /* debug_print_tree */
  3453. static struct pipe *new_pipe(void)
  3454. {
  3455. struct pipe *pi;
  3456. pi = xzalloc(sizeof(struct pipe));
  3457. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3458. return pi;
  3459. }
  3460. /* Command (member of a pipe) is complete, or we start a new pipe
  3461. * if ctx->command is NULL.
  3462. * No errors possible here.
  3463. */
  3464. static int done_command(struct parse_context *ctx)
  3465. {
  3466. /* The command is really already in the pipe structure, so
  3467. * advance the pipe counter and make a new, null command. */
  3468. struct pipe *pi = ctx->pipe;
  3469. struct command *command = ctx->command;
  3470. #if 0 /* Instead we emit error message at run time */
  3471. if (ctx->pending_redirect) {
  3472. /* For example, "cmd >" (no filename to redirect to) */
  3473. syntax_error("invalid redirect");
  3474. ctx->pending_redirect = NULL;
  3475. }
  3476. #endif
  3477. if (command) {
  3478. if (IS_NULL_CMD(command)) {
  3479. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3480. goto clear_and_ret;
  3481. }
  3482. pi->num_cmds++;
  3483. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3484. //debug_print_tree(ctx->list_head, 20);
  3485. } else {
  3486. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3487. }
  3488. /* Only real trickiness here is that the uncommitted
  3489. * command structure is not counted in pi->num_cmds. */
  3490. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3491. ctx->command = command = &pi->cmds[pi->num_cmds];
  3492. clear_and_ret:
  3493. memset(command, 0, sizeof(*command));
  3494. #if ENABLE_HUSH_LINENO_VAR
  3495. command->lineno = G.lineno;
  3496. debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
  3497. #endif
  3498. return pi->num_cmds; /* used only for 0/nonzero check */
  3499. }
  3500. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3501. {
  3502. int not_null;
  3503. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3504. /* Close previous command */
  3505. not_null = done_command(ctx);
  3506. #if HAS_KEYWORDS
  3507. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3508. ctx->ctx_inverted = 0;
  3509. ctx->pipe->res_word = ctx->ctx_res_w;
  3510. #endif
  3511. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3512. /* Necessary since && and || have precedence over &:
  3513. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3514. * in a backgrounded subshell.
  3515. */
  3516. struct pipe *pi;
  3517. struct command *command;
  3518. /* Is this actually this construct, all pipes end with && or ||? */
  3519. pi = ctx->list_head;
  3520. while (pi != ctx->pipe) {
  3521. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3522. goto no_conv;
  3523. pi = pi->next;
  3524. }
  3525. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3526. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3527. pi = xzalloc(sizeof(*pi));
  3528. pi->followup = PIPE_BG;
  3529. pi->num_cmds = 1;
  3530. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3531. command = &pi->cmds[0];
  3532. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3533. command->cmd_type = CMD_NORMAL;
  3534. command->group = ctx->list_head;
  3535. #if !BB_MMU
  3536. command->group_as_string = xstrndup(
  3537. ctx->as_string.data,
  3538. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3539. );
  3540. #endif
  3541. /* Replace all pipes in ctx with one newly created */
  3542. ctx->list_head = ctx->pipe = pi;
  3543. } else {
  3544. no_conv:
  3545. ctx->pipe->followup = type;
  3546. }
  3547. /* Without this check, even just <enter> on command line generates
  3548. * tree of three NOPs (!). Which is harmless but annoying.
  3549. * IOW: it is safe to do it unconditionally. */
  3550. if (not_null
  3551. #if ENABLE_HUSH_IF
  3552. || ctx->ctx_res_w == RES_FI
  3553. #endif
  3554. #if ENABLE_HUSH_LOOPS
  3555. || ctx->ctx_res_w == RES_DONE
  3556. || ctx->ctx_res_w == RES_FOR
  3557. || ctx->ctx_res_w == RES_IN
  3558. #endif
  3559. #if ENABLE_HUSH_CASE
  3560. || ctx->ctx_res_w == RES_ESAC
  3561. #endif
  3562. ) {
  3563. struct pipe *new_p;
  3564. debug_printf_parse("done_pipe: adding new pipe: "
  3565. "not_null:%d ctx->ctx_res_w:%d\n",
  3566. not_null, ctx->ctx_res_w);
  3567. new_p = new_pipe();
  3568. ctx->pipe->next = new_p;
  3569. ctx->pipe = new_p;
  3570. /* RES_THEN, RES_DO etc are "sticky" -
  3571. * they remain set for pipes inside if/while.
  3572. * This is used to control execution.
  3573. * RES_FOR and RES_IN are NOT sticky (needed to support
  3574. * cases where variable or value happens to match a keyword):
  3575. */
  3576. #if ENABLE_HUSH_LOOPS
  3577. if (ctx->ctx_res_w == RES_FOR
  3578. || ctx->ctx_res_w == RES_IN)
  3579. ctx->ctx_res_w = RES_NONE;
  3580. #endif
  3581. #if ENABLE_HUSH_CASE
  3582. if (ctx->ctx_res_w == RES_MATCH)
  3583. ctx->ctx_res_w = RES_CASE_BODY;
  3584. if (ctx->ctx_res_w == RES_CASE)
  3585. ctx->ctx_res_w = RES_CASE_IN;
  3586. #endif
  3587. ctx->command = NULL; /* trick done_command below */
  3588. /* Create the memory for command, roughly:
  3589. * ctx->pipe->cmds = new struct command;
  3590. * ctx->command = &ctx->pipe->cmds[0];
  3591. */
  3592. done_command(ctx);
  3593. //debug_print_tree(ctx->list_head, 10);
  3594. }
  3595. debug_printf_parse("done_pipe return\n");
  3596. }
  3597. static void initialize_context(struct parse_context *ctx)
  3598. {
  3599. memset(ctx, 0, sizeof(*ctx));
  3600. if (MAYBE_ASSIGNMENT != 0)
  3601. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3602. ctx->pipe = ctx->list_head = new_pipe();
  3603. /* Create the memory for command, roughly:
  3604. * ctx->pipe->cmds = new struct command;
  3605. * ctx->command = &ctx->pipe->cmds[0];
  3606. */
  3607. done_command(ctx);
  3608. }
  3609. /* If a reserved word is found and processed, parse context is modified
  3610. * and 1 is returned.
  3611. */
  3612. #if HAS_KEYWORDS
  3613. struct reserved_combo {
  3614. char literal[6];
  3615. unsigned char res;
  3616. unsigned char assignment_flag;
  3617. int flag;
  3618. };
  3619. enum {
  3620. FLAG_END = (1 << RES_NONE ),
  3621. # if ENABLE_HUSH_IF
  3622. FLAG_IF = (1 << RES_IF ),
  3623. FLAG_THEN = (1 << RES_THEN ),
  3624. FLAG_ELIF = (1 << RES_ELIF ),
  3625. FLAG_ELSE = (1 << RES_ELSE ),
  3626. FLAG_FI = (1 << RES_FI ),
  3627. # endif
  3628. # if ENABLE_HUSH_LOOPS
  3629. FLAG_FOR = (1 << RES_FOR ),
  3630. FLAG_WHILE = (1 << RES_WHILE),
  3631. FLAG_UNTIL = (1 << RES_UNTIL),
  3632. FLAG_DO = (1 << RES_DO ),
  3633. FLAG_DONE = (1 << RES_DONE ),
  3634. FLAG_IN = (1 << RES_IN ),
  3635. # endif
  3636. # if ENABLE_HUSH_CASE
  3637. FLAG_MATCH = (1 << RES_MATCH),
  3638. FLAG_ESAC = (1 << RES_ESAC ),
  3639. # endif
  3640. FLAG_START = (1 << RES_XXXX ),
  3641. };
  3642. static const struct reserved_combo* match_reserved_word(o_string *word)
  3643. {
  3644. /* Mostly a list of accepted follow-up reserved words.
  3645. * FLAG_END means we are done with the sequence, and are ready
  3646. * to turn the compound list into a command.
  3647. * FLAG_START means the word must start a new compound list.
  3648. */
  3649. static const struct reserved_combo reserved_list[] = {
  3650. # if ENABLE_HUSH_IF
  3651. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3652. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3653. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3654. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3655. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3656. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3657. # endif
  3658. # if ENABLE_HUSH_LOOPS
  3659. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3660. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3661. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3662. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3663. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3664. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3665. # endif
  3666. # if ENABLE_HUSH_CASE
  3667. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3668. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3669. # endif
  3670. };
  3671. const struct reserved_combo *r;
  3672. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3673. if (strcmp(word->data, r->literal) == 0)
  3674. return r;
  3675. }
  3676. return NULL;
  3677. }
  3678. /* Return NULL: not a keyword, else: keyword
  3679. */
  3680. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3681. {
  3682. # if ENABLE_HUSH_CASE
  3683. static const struct reserved_combo reserved_match = {
  3684. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3685. };
  3686. # endif
  3687. const struct reserved_combo *r;
  3688. if (ctx->word.has_quoted_part)
  3689. return 0;
  3690. r = match_reserved_word(&ctx->word);
  3691. if (!r)
  3692. return r; /* NULL */
  3693. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3694. # if ENABLE_HUSH_CASE
  3695. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3696. /* "case word IN ..." - IN part starts first MATCH part */
  3697. r = &reserved_match;
  3698. } else
  3699. # endif
  3700. if (r->flag == 0) { /* '!' */
  3701. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3702. syntax_error("! ! command");
  3703. ctx->ctx_res_w = RES_SNTX;
  3704. }
  3705. ctx->ctx_inverted = 1;
  3706. return r;
  3707. }
  3708. if (r->flag & FLAG_START) {
  3709. struct parse_context *old;
  3710. old = xmemdup(ctx, sizeof(*ctx));
  3711. debug_printf_parse("push stack %p\n", old);
  3712. initialize_context(ctx);
  3713. ctx->stack = old;
  3714. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3715. syntax_error_at(ctx->word.data);
  3716. ctx->ctx_res_w = RES_SNTX;
  3717. return r;
  3718. } else {
  3719. /* "{...} fi" is ok. "{...} if" is not
  3720. * Example:
  3721. * if { echo foo; } then { echo bar; } fi */
  3722. if (ctx->command->group)
  3723. done_pipe(ctx, PIPE_SEQ);
  3724. }
  3725. ctx->ctx_res_w = r->res;
  3726. ctx->old_flag = r->flag;
  3727. ctx->is_assignment = r->assignment_flag;
  3728. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3729. if (ctx->old_flag & FLAG_END) {
  3730. struct parse_context *old;
  3731. done_pipe(ctx, PIPE_SEQ);
  3732. debug_printf_parse("pop stack %p\n", ctx->stack);
  3733. old = ctx->stack;
  3734. old->command->group = ctx->list_head;
  3735. old->command->cmd_type = CMD_NORMAL;
  3736. # if !BB_MMU
  3737. /* At this point, the compound command's string is in
  3738. * ctx->as_string... except for the leading keyword!
  3739. * Consider this example: "echo a | if true; then echo a; fi"
  3740. * ctx->as_string will contain "true; then echo a; fi",
  3741. * with "if " remaining in old->as_string!
  3742. */
  3743. {
  3744. char *str;
  3745. int len = old->as_string.length;
  3746. /* Concatenate halves */
  3747. o_addstr(&old->as_string, ctx->as_string.data);
  3748. o_free(&ctx->as_string);
  3749. /* Find where leading keyword starts in first half */
  3750. str = old->as_string.data + len;
  3751. if (str > old->as_string.data)
  3752. str--; /* skip whitespace after keyword */
  3753. while (str > old->as_string.data && isalpha(str[-1]))
  3754. str--;
  3755. /* Ugh, we're done with this horrid hack */
  3756. old->command->group_as_string = xstrdup(str);
  3757. debug_printf_parse("pop, remembering as:'%s'\n",
  3758. old->command->group_as_string);
  3759. }
  3760. # endif
  3761. *ctx = *old; /* physical copy */
  3762. free(old);
  3763. }
  3764. return r;
  3765. }
  3766. #endif /* HAS_KEYWORDS */
  3767. /* Word is complete, look at it and update parsing context.
  3768. * Normal return is 0. Syntax errors return 1.
  3769. * Note: on return, word is reset, but not o_free'd!
  3770. */
  3771. static int done_word(struct parse_context *ctx)
  3772. {
  3773. struct command *command = ctx->command;
  3774. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3775. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3776. debug_printf_parse("done_word return 0: true null, ignored\n");
  3777. return 0;
  3778. }
  3779. if (ctx->pending_redirect) {
  3780. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3781. * only if run as "bash", not "sh" */
  3782. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3783. * "2.7 Redirection
  3784. * If the redirection operator is "<<" or "<<-", the word
  3785. * that follows the redirection operator shall be
  3786. * subjected to quote removal; it is unspecified whether
  3787. * any of the other expansions occur. For the other
  3788. * redirection operators, the word that follows the
  3789. * redirection operator shall be subjected to tilde
  3790. * expansion, parameter expansion, command substitution,
  3791. * arithmetic expansion, and quote removal.
  3792. * Pathname expansion shall not be performed
  3793. * on the word by a non-interactive shell; an interactive
  3794. * shell may perform it, but shall do so only when
  3795. * the expansion would result in one word."
  3796. */
  3797. //bash does not do parameter/command substitution or arithmetic expansion
  3798. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3799. // as written:
  3800. // <<EOF$t
  3801. // <<EOF$((1))
  3802. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3803. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3804. /* Cater for >\file case:
  3805. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3806. * Same with heredocs:
  3807. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3808. */
  3809. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3810. unbackslash(ctx->pending_redirect->rd_filename);
  3811. /* Is it <<"HEREDOC"? */
  3812. if (ctx->word.has_quoted_part) {
  3813. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3814. }
  3815. }
  3816. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3817. ctx->pending_redirect = NULL;
  3818. } else {
  3819. #if HAS_KEYWORDS
  3820. # if ENABLE_HUSH_CASE
  3821. if (ctx->ctx_dsemicolon
  3822. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3823. ) {
  3824. /* already done when ctx_dsemicolon was set to 1: */
  3825. /* ctx->ctx_res_w = RES_MATCH; */
  3826. ctx->ctx_dsemicolon = 0;
  3827. } else
  3828. # endif
  3829. if (!command->argv /* if it's the first word... */
  3830. # if ENABLE_HUSH_LOOPS
  3831. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3832. && ctx->ctx_res_w != RES_IN
  3833. # endif
  3834. # if ENABLE_HUSH_CASE
  3835. && ctx->ctx_res_w != RES_CASE
  3836. # endif
  3837. ) {
  3838. const struct reserved_combo *reserved;
  3839. reserved = reserved_word(ctx);
  3840. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3841. if (reserved) {
  3842. # if ENABLE_HUSH_LINENO_VAR
  3843. /* Case:
  3844. * "while ...; do
  3845. * cmd ..."
  3846. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3847. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3848. */
  3849. if (0
  3850. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3851. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3852. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3853. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3854. ) {
  3855. done_pipe(ctx, PIPE_SEQ);
  3856. }
  3857. # endif
  3858. o_reset_to_empty_unquoted(&ctx->word);
  3859. debug_printf_parse("done_word return %d\n",
  3860. (ctx->ctx_res_w == RES_SNTX));
  3861. return (ctx->ctx_res_w == RES_SNTX);
  3862. }
  3863. # if defined(CMD_SINGLEWORD_NOGLOB)
  3864. if (0
  3865. # if BASH_TEST2
  3866. || strcmp(ctx->word.data, "[[") == 0
  3867. # endif
  3868. /* In bash, local/export/readonly are special, args
  3869. * are assignments and therefore expansion of them
  3870. * should be "one-word" expansion:
  3871. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3872. * compare with:
  3873. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3874. * ls: cannot access i=a: No such file or directory
  3875. * ls: cannot access b: No such file or directory
  3876. * Note: bash 3.2.33(1) does this only if export word
  3877. * itself is not quoted:
  3878. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3879. * aaa bbb
  3880. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3881. * aaa
  3882. */
  3883. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3884. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3885. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3886. ) {
  3887. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3888. }
  3889. /* fall through */
  3890. # endif
  3891. }
  3892. #endif /* HAS_KEYWORDS */
  3893. if (command->group) {
  3894. /* "{ echo foo; } echo bar" - bad */
  3895. syntax_error_at(ctx->word.data);
  3896. debug_printf_parse("done_word return 1: syntax error, "
  3897. "groups and arglists don't mix\n");
  3898. return 1;
  3899. }
  3900. /* If this word wasn't an assignment, next ones definitely
  3901. * can't be assignments. Even if they look like ones. */
  3902. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3903. && ctx->is_assignment != WORD_IS_KEYWORD
  3904. ) {
  3905. ctx->is_assignment = NOT_ASSIGNMENT;
  3906. } else {
  3907. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3908. command->assignment_cnt++;
  3909. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3910. }
  3911. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3912. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3913. }
  3914. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3915. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3916. debug_print_strings("word appended to argv", command->argv);
  3917. }
  3918. #if ENABLE_HUSH_LOOPS
  3919. if (ctx->ctx_res_w == RES_FOR) {
  3920. if (ctx->word.has_quoted_part
  3921. || !is_well_formed_var_name(command->argv[0], '\0')
  3922. ) {
  3923. /* bash says just "not a valid identifier" */
  3924. syntax_error("not a valid identifier in for");
  3925. return 1;
  3926. }
  3927. /* Force FOR to have just one word (variable name) */
  3928. /* NB: basically, this makes hush see "for v in ..."
  3929. * syntax as if it is "for v; in ...". FOR and IN become
  3930. * two pipe structs in parse tree. */
  3931. done_pipe(ctx, PIPE_SEQ);
  3932. }
  3933. #endif
  3934. #if ENABLE_HUSH_CASE
  3935. /* Force CASE to have just one word */
  3936. if (ctx->ctx_res_w == RES_CASE) {
  3937. done_pipe(ctx, PIPE_SEQ);
  3938. }
  3939. #endif
  3940. o_reset_to_empty_unquoted(&ctx->word);
  3941. debug_printf_parse("done_word return 0\n");
  3942. return 0;
  3943. }
  3944. /* Peek ahead in the input to find out if we have a "&n" construct,
  3945. * as in "2>&1", that represents duplicating a file descriptor.
  3946. * Return:
  3947. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3948. * REDIRFD_SYNTAX_ERR if syntax error,
  3949. * REDIRFD_TO_FILE if no & was seen,
  3950. * or the number found.
  3951. */
  3952. #if BB_MMU
  3953. #define parse_redir_right_fd(as_string, input) \
  3954. parse_redir_right_fd(input)
  3955. #endif
  3956. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3957. {
  3958. int ch, d, ok;
  3959. ch = i_peek(input);
  3960. if (ch != '&')
  3961. return REDIRFD_TO_FILE;
  3962. ch = i_getch(input); /* get the & */
  3963. nommu_addchr(as_string, ch);
  3964. ch = i_peek(input);
  3965. if (ch == '-') {
  3966. ch = i_getch(input);
  3967. nommu_addchr(as_string, ch);
  3968. return REDIRFD_CLOSE;
  3969. }
  3970. d = 0;
  3971. ok = 0;
  3972. while (ch != EOF && isdigit(ch)) {
  3973. d = d*10 + (ch-'0');
  3974. ok = 1;
  3975. ch = i_getch(input);
  3976. nommu_addchr(as_string, ch);
  3977. ch = i_peek(input);
  3978. }
  3979. if (ok) return d;
  3980. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3981. bb_error_msg("ambiguous redirect");
  3982. return REDIRFD_SYNTAX_ERR;
  3983. }
  3984. /* Return code is 0 normal, 1 if a syntax error is detected
  3985. */
  3986. static int parse_redirect(struct parse_context *ctx,
  3987. int fd,
  3988. redir_type style,
  3989. struct in_str *input)
  3990. {
  3991. struct command *command = ctx->command;
  3992. struct redir_struct *redir;
  3993. struct redir_struct **redirp;
  3994. int dup_num;
  3995. dup_num = REDIRFD_TO_FILE;
  3996. if (style != REDIRECT_HEREDOC) {
  3997. /* Check for a '>&1' type redirect */
  3998. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3999. if (dup_num == REDIRFD_SYNTAX_ERR)
  4000. return 1;
  4001. } else {
  4002. int ch = i_peek_and_eat_bkslash_nl(input);
  4003. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4004. if (dup_num) { /* <<-... */
  4005. ch = i_getch(input);
  4006. nommu_addchr(&ctx->as_string, ch);
  4007. ch = i_peek(input);
  4008. }
  4009. }
  4010. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4011. int ch = i_peek_and_eat_bkslash_nl(input);
  4012. if (ch == '|') {
  4013. /* >|FILE redirect ("clobbering" >).
  4014. * Since we do not support "set -o noclobber" yet,
  4015. * >| and > are the same for now. Just eat |.
  4016. */
  4017. ch = i_getch(input);
  4018. nommu_addchr(&ctx->as_string, ch);
  4019. }
  4020. }
  4021. /* Create a new redir_struct and append it to the linked list */
  4022. redirp = &command->redirects;
  4023. while ((redir = *redirp) != NULL) {
  4024. redirp = &(redir->next);
  4025. }
  4026. *redirp = redir = xzalloc(sizeof(*redir));
  4027. /* redir->next = NULL; */
  4028. /* redir->rd_filename = NULL; */
  4029. redir->rd_type = style;
  4030. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4031. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4032. redir_table[style].descrip);
  4033. redir->rd_dup = dup_num;
  4034. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4035. /* Erik had a check here that the file descriptor in question
  4036. * is legit; I postpone that to "run time"
  4037. * A "-" representation of "close me" shows up as a -3 here */
  4038. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4039. redir->rd_fd, redir->rd_dup);
  4040. } else {
  4041. #if 0 /* Instead we emit error message at run time */
  4042. if (ctx->pending_redirect) {
  4043. /* For example, "cmd > <file" */
  4044. syntax_error("invalid redirect");
  4045. }
  4046. #endif
  4047. /* Set ctx->pending_redirect, so we know what to do at the
  4048. * end of the next parsed word. */
  4049. ctx->pending_redirect = redir;
  4050. }
  4051. return 0;
  4052. }
  4053. /* If a redirect is immediately preceded by a number, that number is
  4054. * supposed to tell which file descriptor to redirect. This routine
  4055. * looks for such preceding numbers. In an ideal world this routine
  4056. * needs to handle all the following classes of redirects...
  4057. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4058. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4059. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4060. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4061. *
  4062. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4063. * "2.7 Redirection
  4064. * ... If n is quoted, the number shall not be recognized as part of
  4065. * the redirection expression. For example:
  4066. * echo \2>a
  4067. * writes the character 2 into file a"
  4068. * We are getting it right by setting ->has_quoted_part on any \<char>
  4069. *
  4070. * A -1 return means no valid number was found,
  4071. * the caller should use the appropriate default for this redirection.
  4072. */
  4073. static int redirect_opt_num(o_string *o)
  4074. {
  4075. int num;
  4076. if (o->data == NULL)
  4077. return -1;
  4078. num = bb_strtou(o->data, NULL, 10);
  4079. if (errno || num < 0)
  4080. return -1;
  4081. o_reset_to_empty_unquoted(o);
  4082. return num;
  4083. }
  4084. #if BB_MMU
  4085. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4086. fetch_till_str(input, word, skip_tabs)
  4087. #endif
  4088. static char *fetch_till_str(o_string *as_string,
  4089. struct in_str *input,
  4090. const char *word,
  4091. int heredoc_flags)
  4092. {
  4093. o_string heredoc = NULL_O_STRING;
  4094. unsigned past_EOL;
  4095. int prev = 0; /* not \ */
  4096. int ch;
  4097. /* Starting with "" is necessary for this case:
  4098. * cat <<EOF
  4099. *
  4100. * xxx
  4101. * EOF
  4102. */
  4103. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4104. goto jump_in;
  4105. while (1) {
  4106. ch = i_getch(input);
  4107. if (ch != EOF)
  4108. nommu_addchr(as_string, ch);
  4109. if (ch == '\n' || ch == EOF) {
  4110. check_heredoc_end:
  4111. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4112. /* End-of-line, and not a line continuation */
  4113. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4114. heredoc.data[past_EOL] = '\0';
  4115. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4116. return heredoc.data;
  4117. }
  4118. if (ch == '\n') {
  4119. /* This is a new line.
  4120. * Remember position and backslash-escaping status.
  4121. */
  4122. o_addchr(&heredoc, ch);
  4123. prev = ch;
  4124. jump_in:
  4125. past_EOL = heredoc.length;
  4126. /* Get 1st char of next line, possibly skipping leading tabs */
  4127. do {
  4128. ch = i_getch(input);
  4129. if (ch != EOF)
  4130. nommu_addchr(as_string, ch);
  4131. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4132. /* If this immediately ended the line,
  4133. * go back to end-of-line checks.
  4134. */
  4135. if (ch == '\n')
  4136. goto check_heredoc_end;
  4137. }
  4138. } else {
  4139. /* Backslash-line continuation in an unquoted
  4140. * heredoc. This does not need special handling
  4141. * for heredoc body (unquoted heredocs are
  4142. * expanded on "execution" and that would take
  4143. * care of this case too), but not the case
  4144. * of line continuation *in terminator*:
  4145. * cat <<EOF
  4146. * Ok1
  4147. * EO\
  4148. * F
  4149. */
  4150. heredoc.data[--heredoc.length] = '\0';
  4151. prev = 0; /* not '\' */
  4152. continue;
  4153. }
  4154. }
  4155. if (ch == EOF) {
  4156. o_free(&heredoc);
  4157. return NULL; /* error */
  4158. }
  4159. o_addchr(&heredoc, ch);
  4160. nommu_addchr(as_string, ch);
  4161. if (prev == '\\' && ch == '\\')
  4162. /* Correctly handle foo\\<eol> (not a line cont.) */
  4163. prev = 0; /* not '\' */
  4164. else
  4165. prev = ch;
  4166. }
  4167. }
  4168. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4169. * and load them all. There should be exactly heredoc_cnt of them.
  4170. */
  4171. #if BB_MMU
  4172. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4173. fetch_heredocs(pi, heredoc_cnt, input)
  4174. #endif
  4175. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4176. {
  4177. while (pi && heredoc_cnt) {
  4178. int i;
  4179. struct command *cmd = pi->cmds;
  4180. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4181. pi->num_cmds,
  4182. cmd->argv ? cmd->argv[0] : "NONE"
  4183. );
  4184. for (i = 0; i < pi->num_cmds; i++) {
  4185. struct redir_struct *redir = cmd->redirects;
  4186. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4187. i, cmd->argv ? cmd->argv[0] : "NONE");
  4188. while (redir) {
  4189. if (redir->rd_type == REDIRECT_HEREDOC) {
  4190. char *p;
  4191. redir->rd_type = REDIRECT_HEREDOC2;
  4192. /* redir->rd_dup is (ab)used to indicate <<- */
  4193. p = fetch_till_str(as_string, input,
  4194. redir->rd_filename, redir->rd_dup);
  4195. if (!p) {
  4196. syntax_error("unexpected EOF in here document");
  4197. return -1;
  4198. }
  4199. free(redir->rd_filename);
  4200. redir->rd_filename = p;
  4201. heredoc_cnt--;
  4202. }
  4203. redir = redir->next;
  4204. }
  4205. if (cmd->group) {
  4206. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4207. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4208. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4209. if (heredoc_cnt < 0)
  4210. return heredoc_cnt; /* error */
  4211. }
  4212. cmd++;
  4213. }
  4214. pi = pi->next;
  4215. }
  4216. return heredoc_cnt;
  4217. }
  4218. static int run_list(struct pipe *pi);
  4219. #if BB_MMU
  4220. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4221. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4222. #endif
  4223. static struct pipe *parse_stream(char **pstring,
  4224. int *heredoc_cnt_ptr,
  4225. struct in_str *input,
  4226. int end_trigger);
  4227. /* Returns number of heredocs not yet consumed,
  4228. * or -1 on error.
  4229. */
  4230. static int parse_group(struct parse_context *ctx,
  4231. struct in_str *input, int ch)
  4232. {
  4233. /* ctx->word contains characters seen prior to ( or {.
  4234. * Typically it's empty, but for function defs,
  4235. * it contains function name (without '()'). */
  4236. #if BB_MMU
  4237. # define as_string NULL
  4238. #else
  4239. char *as_string = NULL;
  4240. #endif
  4241. struct pipe *pipe_list;
  4242. int heredoc_cnt = 0;
  4243. int endch;
  4244. struct command *command = ctx->command;
  4245. debug_printf_parse("parse_group entered\n");
  4246. #if ENABLE_HUSH_FUNCTIONS
  4247. if (ch == '(' && !ctx->word.has_quoted_part) {
  4248. if (ctx->word.length)
  4249. if (done_word(ctx))
  4250. return -1;
  4251. if (!command->argv)
  4252. goto skip; /* (... */
  4253. if (command->argv[1]) { /* word word ... (... */
  4254. syntax_error_unexpected_ch('(');
  4255. return -1;
  4256. }
  4257. /* it is "word(..." or "word (..." */
  4258. do
  4259. ch = i_getch(input);
  4260. while (ch == ' ' || ch == '\t');
  4261. if (ch != ')') {
  4262. syntax_error_unexpected_ch(ch);
  4263. return -1;
  4264. }
  4265. nommu_addchr(&ctx->as_string, ch);
  4266. do
  4267. ch = i_getch(input);
  4268. while (ch == ' ' || ch == '\t' || ch == '\n');
  4269. if (ch != '{' && ch != '(') {
  4270. syntax_error_unexpected_ch(ch);
  4271. return -1;
  4272. }
  4273. nommu_addchr(&ctx->as_string, ch);
  4274. command->cmd_type = CMD_FUNCDEF;
  4275. goto skip;
  4276. }
  4277. #endif
  4278. #if 0 /* Prevented by caller */
  4279. if (command->argv /* word [word]{... */
  4280. || ctx->word.length /* word{... */
  4281. || ctx->word.has_quoted_part /* ""{... */
  4282. ) {
  4283. syntax_error(NULL);
  4284. debug_printf_parse("parse_group return -1: "
  4285. "syntax error, groups and arglists don't mix\n");
  4286. return -1;
  4287. }
  4288. #endif
  4289. IF_HUSH_FUNCTIONS(skip:)
  4290. endch = '}';
  4291. if (ch == '(') {
  4292. endch = ')';
  4293. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4294. command->cmd_type = CMD_SUBSHELL;
  4295. } else {
  4296. /* bash does not allow "{echo...", requires whitespace */
  4297. ch = i_peek(input);
  4298. if (ch != ' ' && ch != '\t' && ch != '\n'
  4299. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4300. ) {
  4301. syntax_error_unexpected_ch(ch);
  4302. return -1;
  4303. }
  4304. if (ch != '(') {
  4305. ch = i_getch(input);
  4306. nommu_addchr(&ctx->as_string, ch);
  4307. }
  4308. }
  4309. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4310. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4311. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4312. #if !BB_MMU
  4313. if (as_string)
  4314. o_addstr(&ctx->as_string, as_string);
  4315. #endif
  4316. /* empty ()/{} or parse error? */
  4317. if (!pipe_list || pipe_list == ERR_PTR) {
  4318. /* parse_stream already emitted error msg */
  4319. if (!BB_MMU)
  4320. free(as_string);
  4321. debug_printf_parse("parse_group return -1: "
  4322. "parse_stream returned %p\n", pipe_list);
  4323. return -1;
  4324. }
  4325. #if !BB_MMU
  4326. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4327. command->group_as_string = as_string;
  4328. debug_printf_parse("end of group, remembering as:'%s'\n",
  4329. command->group_as_string);
  4330. #endif
  4331. #if ENABLE_HUSH_FUNCTIONS
  4332. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4333. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4334. struct command *cmd2;
  4335. cmd2 = xzalloc(sizeof(*cmd2));
  4336. cmd2->cmd_type = CMD_SUBSHELL;
  4337. cmd2->group = pipe_list;
  4338. # if !BB_MMU
  4339. //UNTESTED!
  4340. cmd2->group_as_string = command->group_as_string;
  4341. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4342. # endif
  4343. pipe_list = new_pipe();
  4344. pipe_list->cmds = cmd2;
  4345. pipe_list->num_cmds = 1;
  4346. }
  4347. #endif
  4348. command->group = pipe_list;
  4349. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4350. return heredoc_cnt;
  4351. /* command remains "open", available for possible redirects */
  4352. #undef as_string
  4353. }
  4354. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4355. /* Subroutines for copying $(...) and `...` things */
  4356. /* '...' */
  4357. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4358. {
  4359. while (1) {
  4360. int ch = i_getch(input);
  4361. if (ch == EOF) {
  4362. syntax_error_unterm_ch('\'');
  4363. return 0;
  4364. }
  4365. if (ch == '\'')
  4366. return 1;
  4367. o_addchr(dest, ch);
  4368. }
  4369. }
  4370. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4371. {
  4372. while (1) {
  4373. int ch = i_getch(input);
  4374. if (ch == EOF) {
  4375. syntax_error_unterm_ch('\'');
  4376. return 0;
  4377. }
  4378. if (ch == '\'')
  4379. return 1;
  4380. o_addqchr(dest, ch);
  4381. }
  4382. }
  4383. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4384. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4385. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4386. {
  4387. while (1) {
  4388. int ch = i_getch(input);
  4389. if (ch == EOF) {
  4390. syntax_error_unterm_ch('"');
  4391. return 0;
  4392. }
  4393. if (ch == '"')
  4394. return 1;
  4395. if (ch == '\\') { /* \x. Copy both chars. */
  4396. o_addchr(dest, ch);
  4397. ch = i_getch(input);
  4398. }
  4399. o_addchr(dest, ch);
  4400. if (ch == '`') {
  4401. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4402. return 0;
  4403. o_addchr(dest, ch);
  4404. continue;
  4405. }
  4406. //if (ch == '$') ...
  4407. }
  4408. }
  4409. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4410. * \` quoting.
  4411. * "Within the backquoted style of command substitution, backslash
  4412. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4413. * The search for the matching backquote shall be satisfied by the first
  4414. * backquote found without a preceding backslash; during this search,
  4415. * if a non-escaped backquote is encountered within a shell comment,
  4416. * a here-document, an embedded command substitution of the $(command)
  4417. * form, or a quoted string, undefined results occur. A single-quoted
  4418. * or double-quoted string that begins, but does not end, within the
  4419. * "`...`" sequence produces undefined results."
  4420. * Example Output
  4421. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4422. */
  4423. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4424. {
  4425. while (1) {
  4426. int ch = i_getch(input);
  4427. if (ch == '`')
  4428. return 1;
  4429. if (ch == '\\') {
  4430. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4431. ch = i_getch(input);
  4432. if (ch != '`'
  4433. && ch != '$'
  4434. && ch != '\\'
  4435. && (!in_dquote || ch != '"')
  4436. ) {
  4437. o_addchr(dest, '\\');
  4438. }
  4439. }
  4440. if (ch == EOF) {
  4441. syntax_error_unterm_ch('`');
  4442. return 0;
  4443. }
  4444. o_addchr(dest, ch);
  4445. }
  4446. }
  4447. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4448. * quoting and nested ()s.
  4449. * "With the $(command) style of command substitution, all characters
  4450. * following the open parenthesis to the matching closing parenthesis
  4451. * constitute the command. Any valid shell script can be used for command,
  4452. * except a script consisting solely of redirections which produces
  4453. * unspecified results."
  4454. * Example Output
  4455. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4456. * echo $(echo 'TEST)' BEST) TEST) BEST
  4457. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4458. *
  4459. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4460. * can contain arbitrary constructs, just like $(cmd).
  4461. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4462. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4463. */
  4464. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4465. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4466. {
  4467. int ch;
  4468. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4469. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4470. char end_char2 = end_ch >> 8;
  4471. # endif
  4472. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4473. #if ENABLE_HUSH_INTERACTIVE
  4474. G.promptmode = 1; /* PS2 */
  4475. #endif
  4476. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4477. while (1) {
  4478. ch = i_getch(input);
  4479. if (ch == EOF) {
  4480. syntax_error_unterm_ch(end_ch);
  4481. return 0;
  4482. }
  4483. if (ch == end_ch
  4484. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4485. || ch == end_char2
  4486. # endif
  4487. ) {
  4488. if (!dbl)
  4489. break;
  4490. /* we look for closing )) of $((EXPR)) */
  4491. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4492. i_getch(input); /* eat second ')' */
  4493. break;
  4494. }
  4495. }
  4496. o_addchr(dest, ch);
  4497. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4498. if (ch == '(' || ch == '{') {
  4499. ch = (ch == '(' ? ')' : '}');
  4500. if (!add_till_closing_bracket(dest, input, ch))
  4501. return 0;
  4502. o_addchr(dest, ch);
  4503. continue;
  4504. }
  4505. if (ch == '\'') {
  4506. if (!add_till_single_quote(dest, input))
  4507. return 0;
  4508. o_addchr(dest, ch);
  4509. continue;
  4510. }
  4511. if (ch == '"') {
  4512. if (!add_till_double_quote(dest, input))
  4513. return 0;
  4514. o_addchr(dest, ch);
  4515. continue;
  4516. }
  4517. if (ch == '`') {
  4518. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4519. return 0;
  4520. o_addchr(dest, ch);
  4521. continue;
  4522. }
  4523. if (ch == '\\') {
  4524. /* \x. Copy verbatim. Important for \(, \) */
  4525. ch = i_getch(input);
  4526. if (ch == EOF) {
  4527. syntax_error_unterm_ch(end_ch);
  4528. return 0;
  4529. }
  4530. #if 0
  4531. if (ch == '\n') {
  4532. /* "backslash+newline", ignore both */
  4533. o_delchr(dest); /* undo insertion of '\' */
  4534. continue;
  4535. }
  4536. #endif
  4537. o_addchr(dest, ch);
  4538. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4539. continue;
  4540. }
  4541. }
  4542. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4543. return ch;
  4544. }
  4545. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4546. /* Return code: 0 for OK, 1 for syntax error */
  4547. #if BB_MMU
  4548. #define parse_dollar(as_string, dest, input, quote_mask) \
  4549. parse_dollar(dest, input, quote_mask)
  4550. #define as_string NULL
  4551. #endif
  4552. static int parse_dollar(o_string *as_string,
  4553. o_string *dest,
  4554. struct in_str *input, unsigned char quote_mask)
  4555. {
  4556. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4557. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4558. if (isalpha(ch)) {
  4559. make_var:
  4560. ch = i_getch(input);
  4561. nommu_addchr(as_string, ch);
  4562. /*make_var1:*/
  4563. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4564. while (1) {
  4565. debug_printf_parse(": '%c'\n", ch);
  4566. o_addchr(dest, ch | quote_mask);
  4567. quote_mask = 0;
  4568. ch = i_peek_and_eat_bkslash_nl(input);
  4569. if (!isalnum(ch) && ch != '_') {
  4570. /* End of variable name reached */
  4571. break;
  4572. }
  4573. ch = i_getch(input);
  4574. nommu_addchr(as_string, ch);
  4575. }
  4576. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4577. } else if (isdigit(ch)) {
  4578. make_one_char_var:
  4579. ch = i_getch(input);
  4580. nommu_addchr(as_string, ch);
  4581. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4582. debug_printf_parse(": '%c'\n", ch);
  4583. o_addchr(dest, ch | quote_mask);
  4584. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4585. } else switch (ch) {
  4586. case '$': /* pid */
  4587. case '!': /* last bg pid */
  4588. case '?': /* last exit code */
  4589. case '#': /* number of args */
  4590. case '*': /* args */
  4591. case '@': /* args */
  4592. goto make_one_char_var;
  4593. case '{': {
  4594. char len_single_ch;
  4595. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4596. ch = i_getch(input); /* eat '{' */
  4597. nommu_addchr(as_string, ch);
  4598. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4599. /* It should be ${?}, or ${#var},
  4600. * or even ${?+subst} - operator acting on a special variable,
  4601. * or the beginning of variable name.
  4602. */
  4603. if (ch == EOF
  4604. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4605. ) {
  4606. bad_dollar_syntax:
  4607. syntax_error_unterm_str("${name}");
  4608. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4609. return 0;
  4610. }
  4611. nommu_addchr(as_string, ch);
  4612. len_single_ch = ch;
  4613. ch |= quote_mask;
  4614. /* It's possible to just call add_till_closing_bracket() at this point.
  4615. * However, this regresses some of our testsuite cases
  4616. * which check invalid constructs like ${%}.
  4617. * Oh well... let's check that the var name part is fine... */
  4618. while (1) {
  4619. unsigned pos;
  4620. o_addchr(dest, ch);
  4621. debug_printf_parse(": '%c'\n", ch);
  4622. ch = i_getch(input);
  4623. nommu_addchr(as_string, ch);
  4624. if (ch == '}')
  4625. break;
  4626. if (!isalnum(ch) && ch != '_') {
  4627. unsigned end_ch;
  4628. unsigned char last_ch;
  4629. /* handle parameter expansions
  4630. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4631. */
  4632. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4633. if (len_single_ch != '#'
  4634. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4635. || i_peek(input) != '}'
  4636. ) {
  4637. goto bad_dollar_syntax;
  4638. }
  4639. /* else: it's "length of C" ${#C} op,
  4640. * where C is a single char
  4641. * special var name, e.g. ${#!}.
  4642. */
  4643. }
  4644. /* Eat everything until closing '}' (or ':') */
  4645. end_ch = '}';
  4646. if (BASH_SUBSTR
  4647. && ch == ':'
  4648. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4649. ) {
  4650. /* It's ${var:N[:M]} thing */
  4651. end_ch = '}' * 0x100 + ':';
  4652. }
  4653. if (BASH_PATTERN_SUBST
  4654. && ch == '/'
  4655. ) {
  4656. /* It's ${var/[/]pattern[/repl]} thing */
  4657. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4658. i_getch(input);
  4659. nommu_addchr(as_string, '/');
  4660. ch = '\\';
  4661. }
  4662. end_ch = '}' * 0x100 + '/';
  4663. }
  4664. o_addchr(dest, ch);
  4665. /* The pattern can't be empty.
  4666. * IOW: if the first char after "${v//" is a slash,
  4667. * it does not terminate the pattern - it's the first char of the pattern:
  4668. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4669. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4670. */
  4671. if (i_peek(input) == '/') {
  4672. o_addchr(dest, i_getch(input));
  4673. }
  4674. again:
  4675. if (!BB_MMU)
  4676. pos = dest->length;
  4677. #if ENABLE_HUSH_DOLLAR_OPS
  4678. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4679. if (last_ch == 0) /* error? */
  4680. return 0;
  4681. #else
  4682. #error Simple code to only allow ${var} is not implemented
  4683. #endif
  4684. if (as_string) {
  4685. o_addstr(as_string, dest->data + pos);
  4686. o_addchr(as_string, last_ch);
  4687. }
  4688. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4689. && (end_ch & 0xff00)
  4690. ) {
  4691. /* close the first block: */
  4692. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4693. /* while parsing N from ${var:N[:M]}
  4694. * or pattern from ${var/[/]pattern[/repl]} */
  4695. if ((end_ch & 0xff) == last_ch) {
  4696. /* got ':' or '/'- parse the rest */
  4697. end_ch = '}';
  4698. goto again;
  4699. }
  4700. /* got '}' */
  4701. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4702. /* it's ${var:N} - emulate :999999999 */
  4703. o_addstr(dest, "999999999");
  4704. } /* else: it's ${var/[/]pattern} */
  4705. }
  4706. break;
  4707. }
  4708. len_single_ch = 0; /* it can't be ${#C} op */
  4709. }
  4710. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4711. break;
  4712. }
  4713. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4714. case '(': {
  4715. unsigned pos;
  4716. ch = i_getch(input);
  4717. nommu_addchr(as_string, ch);
  4718. # if ENABLE_FEATURE_SH_MATH
  4719. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4720. ch = i_getch(input);
  4721. nommu_addchr(as_string, ch);
  4722. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4723. o_addchr(dest, /*quote_mask |*/ '+');
  4724. if (!BB_MMU)
  4725. pos = dest->length;
  4726. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4727. return 0; /* error */
  4728. if (as_string) {
  4729. o_addstr(as_string, dest->data + pos);
  4730. o_addchr(as_string, ')');
  4731. o_addchr(as_string, ')');
  4732. }
  4733. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4734. break;
  4735. }
  4736. # endif
  4737. # if ENABLE_HUSH_TICK
  4738. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4739. o_addchr(dest, quote_mask | '`');
  4740. if (!BB_MMU)
  4741. pos = dest->length;
  4742. if (!add_till_closing_bracket(dest, input, ')'))
  4743. return 0; /* error */
  4744. if (as_string) {
  4745. o_addstr(as_string, dest->data + pos);
  4746. o_addchr(as_string, ')');
  4747. }
  4748. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4749. # endif
  4750. break;
  4751. }
  4752. #endif
  4753. case '_':
  4754. goto make_var;
  4755. #if 0
  4756. /* TODO: $_ and $-: */
  4757. /* $_ Shell or shell script name; or last argument of last command
  4758. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4759. * but in command's env, set to full pathname used to invoke it */
  4760. /* $- Option flags set by set builtin or shell options (-i etc) */
  4761. ch = i_getch(input);
  4762. nommu_addchr(as_string, ch);
  4763. ch = i_peek_and_eat_bkslash_nl(input);
  4764. if (isalnum(ch)) { /* it's $_name or $_123 */
  4765. ch = '_';
  4766. goto make_var1;
  4767. }
  4768. /* else: it's $_ */
  4769. #endif
  4770. default:
  4771. o_addQchr(dest, '$');
  4772. }
  4773. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4774. return 1;
  4775. #undef as_string
  4776. }
  4777. #if BB_MMU
  4778. #define encode_string(as_string, dest, input, dquote_end) \
  4779. encode_string(dest, input, dquote_end)
  4780. #define as_string NULL
  4781. #endif
  4782. static int encode_string(o_string *as_string,
  4783. o_string *dest,
  4784. struct in_str *input,
  4785. int dquote_end)
  4786. {
  4787. int ch;
  4788. int next;
  4789. again:
  4790. ch = i_getch(input);
  4791. if (ch != EOF)
  4792. nommu_addchr(as_string, ch);
  4793. if (ch == dquote_end) { /* may be only '"' or EOF */
  4794. debug_printf_parse("encode_string return 1 (ok)\n");
  4795. return 1;
  4796. }
  4797. /* note: can't move it above ch == dquote_end check! */
  4798. if (ch == EOF) {
  4799. syntax_error_unterm_ch('"');
  4800. return 0; /* error */
  4801. }
  4802. next = '\0';
  4803. if (ch != '\n') {
  4804. next = i_peek(input);
  4805. }
  4806. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4807. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4808. if (ch == '\\') {
  4809. if (next == EOF) {
  4810. /* Testcase: in interactive shell a file with
  4811. * echo "unterminated string\<eof>
  4812. * is sourced.
  4813. */
  4814. syntax_error_unterm_ch('"');
  4815. return 0; /* error */
  4816. }
  4817. /* bash:
  4818. * "The backslash retains its special meaning [in "..."]
  4819. * only when followed by one of the following characters:
  4820. * $, `, ", \, or <newline>. A double quote may be quoted
  4821. * within double quotes by preceding it with a backslash."
  4822. * NB: in (unquoted) heredoc, above does not apply to ",
  4823. * therefore we check for it by "next == dquote_end" cond.
  4824. */
  4825. if (next == dquote_end || strchr("$`\\\n", next)) {
  4826. ch = i_getch(input); /* eat next */
  4827. if (ch == '\n')
  4828. goto again; /* skip \<newline> */
  4829. } /* else: ch remains == '\\', and we double it below: */
  4830. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4831. nommu_addchr(as_string, ch);
  4832. goto again;
  4833. }
  4834. if (ch == '$') {
  4835. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4836. debug_printf_parse("encode_string return 0: "
  4837. "parse_dollar returned 0 (error)\n");
  4838. return 0;
  4839. }
  4840. goto again;
  4841. }
  4842. #if ENABLE_HUSH_TICK
  4843. if (ch == '`') {
  4844. //unsigned pos = dest->length;
  4845. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4846. o_addchr(dest, 0x80 | '`');
  4847. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4848. return 0; /* error */
  4849. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4850. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4851. goto again;
  4852. }
  4853. #endif
  4854. o_addQchr(dest, ch);
  4855. goto again;
  4856. #undef as_string
  4857. }
  4858. /*
  4859. * Scan input until EOF or end_trigger char.
  4860. * Return a list of pipes to execute, or NULL on EOF
  4861. * or if end_trigger character is met.
  4862. * On syntax error, exit if shell is not interactive,
  4863. * reset parsing machinery and start parsing anew,
  4864. * or return ERR_PTR.
  4865. */
  4866. static struct pipe *parse_stream(char **pstring,
  4867. int *heredoc_cnt_ptr,
  4868. struct in_str *input,
  4869. int end_trigger)
  4870. {
  4871. struct parse_context ctx;
  4872. int heredoc_cnt;
  4873. /* Single-quote triggers a bypass of the main loop until its mate is
  4874. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4875. */
  4876. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4877. end_trigger ? end_trigger : 'X');
  4878. debug_enter();
  4879. initialize_context(&ctx);
  4880. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4881. * Preventing this:
  4882. */
  4883. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4884. /* We used to separate words on $IFS here. This was wrong.
  4885. * $IFS is used only for word splitting when $var is expanded,
  4886. * here we should use blank chars as separators, not $IFS
  4887. */
  4888. heredoc_cnt = 0;
  4889. while (1) {
  4890. const char *is_blank;
  4891. const char *is_special;
  4892. int ch;
  4893. int next;
  4894. int redir_fd;
  4895. redir_type redir_style;
  4896. ch = i_getch(input);
  4897. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4898. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4899. if (ch == EOF) {
  4900. struct pipe *pi;
  4901. if (heredoc_cnt) {
  4902. syntax_error_unterm_str("here document");
  4903. goto parse_error;
  4904. }
  4905. if (end_trigger == ')') {
  4906. syntax_error_unterm_ch('(');
  4907. goto parse_error;
  4908. }
  4909. if (end_trigger == '}') {
  4910. syntax_error_unterm_ch('{');
  4911. goto parse_error;
  4912. }
  4913. if (done_word(&ctx)) {
  4914. goto parse_error;
  4915. }
  4916. o_free_and_set_NULL(&ctx.word);
  4917. done_pipe(&ctx, PIPE_SEQ);
  4918. pi = ctx.list_head;
  4919. /* If we got nothing... */
  4920. /* (this makes bare "&" cmd a no-op.
  4921. * bash says: "syntax error near unexpected token '&'") */
  4922. if (pi->num_cmds == 0
  4923. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4924. ) {
  4925. free_pipe_list(pi);
  4926. pi = NULL;
  4927. }
  4928. #if !BB_MMU
  4929. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4930. if (pstring)
  4931. *pstring = ctx.as_string.data;
  4932. else
  4933. o_free(&ctx.as_string);
  4934. #endif
  4935. // heredoc_cnt must be 0 here anyway
  4936. //if (heredoc_cnt_ptr)
  4937. // *heredoc_cnt_ptr = heredoc_cnt;
  4938. debug_leave();
  4939. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4940. debug_printf_parse("parse_stream return %p\n", pi);
  4941. return pi;
  4942. }
  4943. /* Handle "'" and "\" first, as they won't play nice with
  4944. * i_peek_and_eat_bkslash_nl() anyway:
  4945. * echo z\\
  4946. * and
  4947. * echo '\
  4948. * '
  4949. * would break.
  4950. */
  4951. if (ch == '\\') {
  4952. ch = i_getch(input);
  4953. if (ch == '\n')
  4954. continue; /* drop \<newline>, get next char */
  4955. nommu_addchr(&ctx.as_string, '\\');
  4956. o_addchr(&ctx.word, '\\');
  4957. if (ch == EOF) {
  4958. /* Testcase: eval 'echo Ok\' */
  4959. /* bash-4.3.43 was removing backslash,
  4960. * but 4.4.19 retains it, most other shells too
  4961. */
  4962. continue; /* get next char */
  4963. }
  4964. /* Example: echo Hello \2>file
  4965. * we need to know that word 2 is quoted
  4966. */
  4967. ctx.word.has_quoted_part = 1;
  4968. nommu_addchr(&ctx.as_string, ch);
  4969. o_addchr(&ctx.word, ch);
  4970. continue; /* get next char */
  4971. }
  4972. nommu_addchr(&ctx.as_string, ch);
  4973. if (ch == '\'') {
  4974. ctx.word.has_quoted_part = 1;
  4975. next = i_getch(input);
  4976. if (next == '\'' && !ctx.pending_redirect)
  4977. goto insert_empty_quoted_str_marker;
  4978. ch = next;
  4979. while (1) {
  4980. if (ch == EOF) {
  4981. syntax_error_unterm_ch('\'');
  4982. goto parse_error;
  4983. }
  4984. nommu_addchr(&ctx.as_string, ch);
  4985. if (ch == '\'')
  4986. break;
  4987. if (ch == SPECIAL_VAR_SYMBOL) {
  4988. /* Convert raw ^C to corresponding special variable reference */
  4989. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4990. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4991. }
  4992. o_addqchr(&ctx.word, ch);
  4993. ch = i_getch(input);
  4994. }
  4995. continue; /* get next char */
  4996. }
  4997. next = '\0';
  4998. if (ch != '\n')
  4999. next = i_peek_and_eat_bkslash_nl(input);
  5000. is_special = "{}<>;&|()#" /* special outside of "str" */
  5001. "$\"" IF_HUSH_TICK("`") /* always special */
  5002. SPECIAL_VAR_SYMBOL_STR;
  5003. /* Are { and } special here? */
  5004. if (ctx.command->argv /* word [word]{... - non-special */
  5005. || ctx.word.length /* word{... - non-special */
  5006. || ctx.word.has_quoted_part /* ""{... - non-special */
  5007. || (next != ';' /* }; - special */
  5008. && next != ')' /* }) - special */
  5009. && next != '(' /* {( - special */
  5010. && next != '&' /* }& and }&& ... - special */
  5011. && next != '|' /* }|| ... - special */
  5012. && !strchr(defifs, next) /* {word - non-special */
  5013. )
  5014. ) {
  5015. /* They are not special, skip "{}" */
  5016. is_special += 2;
  5017. }
  5018. is_special = strchr(is_special, ch);
  5019. is_blank = strchr(defifs, ch);
  5020. if (!is_special && !is_blank) { /* ordinary char */
  5021. ordinary_char:
  5022. o_addQchr(&ctx.word, ch);
  5023. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5024. || ctx.is_assignment == WORD_IS_KEYWORD)
  5025. && ch == '='
  5026. && is_well_formed_var_name(ctx.word.data, '=')
  5027. ) {
  5028. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5029. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5030. }
  5031. continue;
  5032. }
  5033. if (is_blank) {
  5034. #if ENABLE_HUSH_LINENO_VAR
  5035. /* Case:
  5036. * "while ...; do<whitespace><newline>
  5037. * cmd ..."
  5038. * would think that "cmd" starts in <whitespace> -
  5039. * i.e., at the previous line.
  5040. * We need to skip all whitespace before newlines.
  5041. */
  5042. while (ch != '\n') {
  5043. next = i_peek(input);
  5044. if (next != ' ' && next != '\t' && next != '\n')
  5045. break; /* next char is not ws */
  5046. ch = i_getch(input);
  5047. }
  5048. /* ch == last eaten whitespace char */
  5049. #endif
  5050. if (done_word(&ctx)) {
  5051. goto parse_error;
  5052. }
  5053. if (ch == '\n') {
  5054. /* Is this a case when newline is simply ignored?
  5055. * Some examples:
  5056. * "cmd | <newline> cmd ..."
  5057. * "case ... in <newline> word) ..."
  5058. */
  5059. if (IS_NULL_CMD(ctx.command)
  5060. && ctx.word.length == 0
  5061. && !ctx.word.has_quoted_part
  5062. && heredoc_cnt == 0
  5063. ) {
  5064. /* This newline can be ignored. But...
  5065. * Without check #1, interactive shell
  5066. * ignores even bare <newline>,
  5067. * and shows the continuation prompt:
  5068. * ps1_prompt$ <enter>
  5069. * ps2> _ <=== wrong, should be ps1
  5070. * Without check #2, "cmd & <newline>"
  5071. * is similarly mistreated.
  5072. * (BTW, this makes "cmd & cmd"
  5073. * and "cmd && cmd" non-orthogonal.
  5074. * Really, ask yourself, why
  5075. * "cmd && <newline>" doesn't start
  5076. * cmd but waits for more input?
  5077. * The only reason is that it might be
  5078. * a "cmd1 && <nl> cmd2 &" construct,
  5079. * cmd1 may need to run in BG).
  5080. */
  5081. struct pipe *pi = ctx.list_head;
  5082. if (pi->num_cmds != 0 /* check #1 */
  5083. && pi->followup != PIPE_BG /* check #2 */
  5084. ) {
  5085. continue;
  5086. }
  5087. }
  5088. /* Treat newline as a command separator. */
  5089. done_pipe(&ctx, PIPE_SEQ);
  5090. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5091. if (heredoc_cnt) {
  5092. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5093. if (heredoc_cnt != 0)
  5094. goto parse_error;
  5095. }
  5096. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5097. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5098. ch = ';';
  5099. /* note: if (is_blank) continue;
  5100. * will still trigger for us */
  5101. }
  5102. }
  5103. /* "cmd}" or "cmd }..." without semicolon or &:
  5104. * } is an ordinary char in this case, even inside { cmd; }
  5105. * Pathological example: { ""}; } should exec "}" cmd
  5106. */
  5107. if (ch == '}') {
  5108. if (ctx.word.length != 0 /* word} */
  5109. || ctx.word.has_quoted_part /* ""} */
  5110. ) {
  5111. goto ordinary_char;
  5112. }
  5113. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5114. /* Generally, there should be semicolon: "cmd; }"
  5115. * However, bash allows to omit it if "cmd" is
  5116. * a group. Examples:
  5117. * { { echo 1; } }
  5118. * {(echo 1)}
  5119. * { echo 0 >&2 | { echo 1; } }
  5120. * { while false; do :; done }
  5121. * { case a in b) ;; esac }
  5122. */
  5123. if (ctx.command->group)
  5124. goto term_group;
  5125. goto ordinary_char;
  5126. }
  5127. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5128. /* Can't be an end of {cmd}, skip the check */
  5129. goto skip_end_trigger;
  5130. /* else: } does terminate a group */
  5131. }
  5132. term_group:
  5133. if (end_trigger && end_trigger == ch
  5134. && (ch != ';' || heredoc_cnt == 0)
  5135. #if ENABLE_HUSH_CASE
  5136. && (ch != ')'
  5137. || ctx.ctx_res_w != RES_MATCH
  5138. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5139. )
  5140. #endif
  5141. ) {
  5142. if (done_word(&ctx)) {
  5143. goto parse_error;
  5144. }
  5145. done_pipe(&ctx, PIPE_SEQ);
  5146. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5147. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5148. /* Do we sit outside of any if's, loops or case's? */
  5149. if (!HAS_KEYWORDS
  5150. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5151. ) {
  5152. o_free_and_set_NULL(&ctx.word);
  5153. #if !BB_MMU
  5154. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5155. if (pstring)
  5156. *pstring = ctx.as_string.data;
  5157. else
  5158. o_free(&ctx.as_string);
  5159. #endif
  5160. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5161. /* Example: bare "{ }", "()" */
  5162. G.last_exitcode = 2; /* bash compat */
  5163. syntax_error_unexpected_ch(ch);
  5164. goto parse_error2;
  5165. }
  5166. if (heredoc_cnt_ptr)
  5167. *heredoc_cnt_ptr = heredoc_cnt;
  5168. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5169. debug_printf_parse("parse_stream return %p: "
  5170. "end_trigger char found\n",
  5171. ctx.list_head);
  5172. debug_leave();
  5173. return ctx.list_head;
  5174. }
  5175. }
  5176. if (is_blank)
  5177. continue;
  5178. /* Catch <, > before deciding whether this word is
  5179. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5180. switch (ch) {
  5181. case '>':
  5182. redir_fd = redirect_opt_num(&ctx.word);
  5183. if (done_word(&ctx)) {
  5184. goto parse_error;
  5185. }
  5186. redir_style = REDIRECT_OVERWRITE;
  5187. if (next == '>') {
  5188. redir_style = REDIRECT_APPEND;
  5189. ch = i_getch(input);
  5190. nommu_addchr(&ctx.as_string, ch);
  5191. }
  5192. #if 0
  5193. else if (next == '(') {
  5194. syntax_error(">(process) not supported");
  5195. goto parse_error;
  5196. }
  5197. #endif
  5198. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5199. goto parse_error;
  5200. continue; /* get next char */
  5201. case '<':
  5202. redir_fd = redirect_opt_num(&ctx.word);
  5203. if (done_word(&ctx)) {
  5204. goto parse_error;
  5205. }
  5206. redir_style = REDIRECT_INPUT;
  5207. if (next == '<') {
  5208. redir_style = REDIRECT_HEREDOC;
  5209. heredoc_cnt++;
  5210. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5211. ch = i_getch(input);
  5212. nommu_addchr(&ctx.as_string, ch);
  5213. } else if (next == '>') {
  5214. redir_style = REDIRECT_IO;
  5215. ch = i_getch(input);
  5216. nommu_addchr(&ctx.as_string, ch);
  5217. }
  5218. #if 0
  5219. else if (next == '(') {
  5220. syntax_error("<(process) not supported");
  5221. goto parse_error;
  5222. }
  5223. #endif
  5224. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5225. goto parse_error;
  5226. continue; /* get next char */
  5227. case '#':
  5228. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5229. /* skip "#comment" */
  5230. /* note: we do not add it to &ctx.as_string */
  5231. /* TODO: in bash:
  5232. * comment inside $() goes to the next \n, even inside quoted string (!):
  5233. * cmd "$(cmd2 #comment)" - syntax error
  5234. * cmd "`cmd2 #comment`" - ok
  5235. * We accept both (comment ends where command subst ends, in both cases).
  5236. */
  5237. while (1) {
  5238. ch = i_peek(input);
  5239. if (ch == '\n') {
  5240. nommu_addchr(&ctx.as_string, '\n');
  5241. break;
  5242. }
  5243. ch = i_getch(input);
  5244. if (ch == EOF)
  5245. break;
  5246. }
  5247. continue; /* get next char */
  5248. }
  5249. break;
  5250. }
  5251. skip_end_trigger:
  5252. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5253. /* check that we are not in word in "a=1 2>word b=1": */
  5254. && !ctx.pending_redirect
  5255. ) {
  5256. /* ch is a special char and thus this word
  5257. * cannot be an assignment */
  5258. ctx.is_assignment = NOT_ASSIGNMENT;
  5259. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5260. }
  5261. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5262. switch (ch) {
  5263. case SPECIAL_VAR_SYMBOL:
  5264. /* Convert raw ^C to corresponding special variable reference */
  5265. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5266. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5267. /* fall through */
  5268. case '#':
  5269. /* non-comment #: "echo a#b" etc */
  5270. o_addchr(&ctx.word, ch);
  5271. continue; /* get next char */
  5272. case '$':
  5273. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5274. debug_printf_parse("parse_stream parse error: "
  5275. "parse_dollar returned 0 (error)\n");
  5276. goto parse_error;
  5277. }
  5278. continue; /* get next char */
  5279. case '"':
  5280. ctx.word.has_quoted_part = 1;
  5281. if (next == '"' && !ctx.pending_redirect) {
  5282. i_getch(input); /* eat second " */
  5283. insert_empty_quoted_str_marker:
  5284. nommu_addchr(&ctx.as_string, next);
  5285. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5286. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5287. continue; /* get next char */
  5288. }
  5289. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5290. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5291. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5292. goto parse_error;
  5293. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5294. continue; /* get next char */
  5295. #if ENABLE_HUSH_TICK
  5296. case '`': {
  5297. USE_FOR_NOMMU(unsigned pos;)
  5298. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5299. o_addchr(&ctx.word, '`');
  5300. USE_FOR_NOMMU(pos = ctx.word.length;)
  5301. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5302. goto parse_error;
  5303. # if !BB_MMU
  5304. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5305. o_addchr(&ctx.as_string, '`');
  5306. # endif
  5307. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5308. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5309. continue; /* get next char */
  5310. }
  5311. #endif
  5312. case ';':
  5313. #if ENABLE_HUSH_CASE
  5314. case_semi:
  5315. #endif
  5316. if (done_word(&ctx)) {
  5317. goto parse_error;
  5318. }
  5319. done_pipe(&ctx, PIPE_SEQ);
  5320. #if ENABLE_HUSH_CASE
  5321. /* Eat multiple semicolons, detect
  5322. * whether it means something special */
  5323. while (1) {
  5324. ch = i_peek_and_eat_bkslash_nl(input);
  5325. if (ch != ';')
  5326. break;
  5327. ch = i_getch(input);
  5328. nommu_addchr(&ctx.as_string, ch);
  5329. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5330. ctx.ctx_dsemicolon = 1;
  5331. ctx.ctx_res_w = RES_MATCH;
  5332. break;
  5333. }
  5334. }
  5335. #endif
  5336. new_cmd:
  5337. /* We just finished a cmd. New one may start
  5338. * with an assignment */
  5339. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5340. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5341. continue; /* get next char */
  5342. case '&':
  5343. if (done_word(&ctx)) {
  5344. goto parse_error;
  5345. }
  5346. if (next == '&') {
  5347. ch = i_getch(input);
  5348. nommu_addchr(&ctx.as_string, ch);
  5349. done_pipe(&ctx, PIPE_AND);
  5350. } else {
  5351. done_pipe(&ctx, PIPE_BG);
  5352. }
  5353. goto new_cmd;
  5354. case '|':
  5355. if (done_word(&ctx)) {
  5356. goto parse_error;
  5357. }
  5358. #if ENABLE_HUSH_CASE
  5359. if (ctx.ctx_res_w == RES_MATCH)
  5360. break; /* we are in case's "word | word)" */
  5361. #endif
  5362. if (next == '|') { /* || */
  5363. ch = i_getch(input);
  5364. nommu_addchr(&ctx.as_string, ch);
  5365. done_pipe(&ctx, PIPE_OR);
  5366. } else {
  5367. /* we could pick up a file descriptor choice here
  5368. * with redirect_opt_num(), but bash doesn't do it.
  5369. * "echo foo 2| cat" yields "foo 2". */
  5370. done_command(&ctx);
  5371. }
  5372. goto new_cmd;
  5373. case '(':
  5374. #if ENABLE_HUSH_CASE
  5375. /* "case... in [(]word)..." - skip '(' */
  5376. if (ctx.ctx_res_w == RES_MATCH
  5377. && ctx.command->argv == NULL /* not (word|(... */
  5378. && ctx.word.length == 0 /* not word(... */
  5379. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5380. ) {
  5381. continue; /* get next char */
  5382. }
  5383. #endif
  5384. /* fall through */
  5385. case '{': {
  5386. int n = parse_group(&ctx, input, ch);
  5387. if (n < 0) {
  5388. goto parse_error;
  5389. }
  5390. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5391. heredoc_cnt += n;
  5392. goto new_cmd;
  5393. }
  5394. case ')':
  5395. #if ENABLE_HUSH_CASE
  5396. if (ctx.ctx_res_w == RES_MATCH)
  5397. goto case_semi;
  5398. #endif
  5399. case '}':
  5400. /* proper use of this character is caught by end_trigger:
  5401. * if we see {, we call parse_group(..., end_trigger='}')
  5402. * and it will match } earlier (not here). */
  5403. G.last_exitcode = 2;
  5404. syntax_error_unexpected_ch(ch);
  5405. goto parse_error2;
  5406. default:
  5407. if (HUSH_DEBUG)
  5408. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5409. }
  5410. } /* while (1) */
  5411. parse_error:
  5412. G.last_exitcode = 1;
  5413. parse_error2:
  5414. {
  5415. struct parse_context *pctx;
  5416. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5417. /* Clean up allocated tree.
  5418. * Sample for finding leaks on syntax error recovery path.
  5419. * Run it from interactive shell, watch pmap `pidof hush`.
  5420. * while if false; then false; fi; do break; fi
  5421. * Samples to catch leaks at execution:
  5422. * while if (true | { true;}); then echo ok; fi; do break; done
  5423. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5424. */
  5425. pctx = &ctx;
  5426. do {
  5427. /* Update pipe/command counts,
  5428. * otherwise freeing may miss some */
  5429. done_pipe(pctx, PIPE_SEQ);
  5430. debug_printf_clean("freeing list %p from ctx %p\n",
  5431. pctx->list_head, pctx);
  5432. debug_print_tree(pctx->list_head, 0);
  5433. free_pipe_list(pctx->list_head);
  5434. debug_printf_clean("freed list %p\n", pctx->list_head);
  5435. #if !BB_MMU
  5436. o_free(&pctx->as_string);
  5437. #endif
  5438. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5439. if (pctx != &ctx) {
  5440. free(pctx);
  5441. }
  5442. IF_HAS_KEYWORDS(pctx = p2;)
  5443. } while (HAS_KEYWORDS && pctx);
  5444. o_free(&ctx.word);
  5445. #if !BB_MMU
  5446. if (pstring)
  5447. *pstring = NULL;
  5448. #endif
  5449. debug_leave();
  5450. return ERR_PTR;
  5451. }
  5452. }
  5453. /*** Execution routines ***/
  5454. /* Expansion can recurse, need forward decls: */
  5455. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5456. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5457. expand_string_to_string(str)
  5458. #endif
  5459. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5460. #if ENABLE_HUSH_TICK
  5461. static int process_command_subs(o_string *dest, const char *s);
  5462. #endif
  5463. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5464. /* expand_strvec_to_strvec() takes a list of strings, expands
  5465. * all variable references within and returns a pointer to
  5466. * a list of expanded strings, possibly with larger number
  5467. * of strings. (Think VAR="a b"; echo $VAR).
  5468. * This new list is allocated as a single malloc block.
  5469. * NULL-terminated list of char* pointers is at the beginning of it,
  5470. * followed by strings themselves.
  5471. * Caller can deallocate entire list by single free(list). */
  5472. /* A horde of its helpers come first: */
  5473. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5474. {
  5475. while (--len >= 0) {
  5476. char c = *str++;
  5477. #if ENABLE_HUSH_BRACE_EXPANSION
  5478. if (c == '{' || c == '}') {
  5479. /* { -> \{, } -> \} */
  5480. o_addchr(o, '\\');
  5481. /* And now we want to add { or } and continue:
  5482. * o_addchr(o, c);
  5483. * continue;
  5484. * luckily, just falling through achieves this.
  5485. */
  5486. }
  5487. #endif
  5488. o_addchr(o, c);
  5489. if (c == '\\') {
  5490. /* \z -> \\\z; \<eol> -> \\<eol> */
  5491. o_addchr(o, '\\');
  5492. if (len) {
  5493. len--;
  5494. o_addchr(o, '\\');
  5495. o_addchr(o, *str++);
  5496. }
  5497. }
  5498. }
  5499. }
  5500. /* Store given string, finalizing the word and starting new one whenever
  5501. * we encounter IFS char(s). This is used for expanding variable values.
  5502. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5503. * Return in output->ended_in_ifs:
  5504. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5505. */
  5506. static int expand_on_ifs(o_string *output, int n, const char *str)
  5507. {
  5508. int last_is_ifs = 0;
  5509. while (1) {
  5510. int word_len;
  5511. if (!*str) /* EOL - do not finalize word */
  5512. break;
  5513. word_len = strcspn(str, G.ifs);
  5514. if (word_len) {
  5515. /* We have WORD_LEN leading non-IFS chars */
  5516. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5517. o_addblock(output, str, word_len);
  5518. } else {
  5519. /* Protect backslashes against globbing up :)
  5520. * Example: "v='\*'; echo b$v" prints "b\*"
  5521. * (and does not try to glob on "*")
  5522. */
  5523. o_addblock_duplicate_backslash(output, str, word_len);
  5524. /*/ Why can't we do it easier? */
  5525. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5526. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5527. }
  5528. last_is_ifs = 0;
  5529. str += word_len;
  5530. if (!*str) /* EOL - do not finalize word */
  5531. break;
  5532. }
  5533. /* We know str here points to at least one IFS char */
  5534. last_is_ifs = 1;
  5535. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5536. if (!*str) /* EOL - do not finalize word */
  5537. break;
  5538. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5539. && strchr(G.ifs, *str) /* the second check would fail */
  5540. ) {
  5541. /* This is a non-whitespace $IFS char */
  5542. /* Skip it and IFS whitespace chars, start new word */
  5543. str++;
  5544. str += strspn(str, G.ifs_whitespace);
  5545. goto new_word;
  5546. }
  5547. /* Start new word... but not always! */
  5548. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5549. if (output->has_quoted_part
  5550. /*
  5551. * Case "v=' a'; echo $v":
  5552. * here nothing precedes the space in $v expansion,
  5553. * therefore we should not finish the word
  5554. * (IOW: if there *is* word to finalize, only then do it):
  5555. * It's okay if this accesses the byte before first argv[]:
  5556. * past call to o_save_ptr() cleared it to zero byte
  5557. * (grep for -prev-ifs-check-).
  5558. */
  5559. || output->data[output->length - 1]
  5560. ) {
  5561. new_word:
  5562. o_addchr(output, '\0');
  5563. debug_print_list("expand_on_ifs", output, n);
  5564. n = o_save_ptr(output, n);
  5565. }
  5566. }
  5567. output->ended_in_ifs = last_is_ifs;
  5568. debug_print_list("expand_on_ifs[1]", output, n);
  5569. return n;
  5570. }
  5571. /* Helper to expand $((...)) and heredoc body. These act as if
  5572. * they are in double quotes, with the exception that they are not :).
  5573. * Just the rules are similar: "expand only $var and `cmd`"
  5574. *
  5575. * Returns malloced string.
  5576. * As an optimization, we return NULL if expansion is not needed.
  5577. */
  5578. static char *encode_then_expand_string(const char *str)
  5579. {
  5580. char *exp_str;
  5581. struct in_str input;
  5582. o_string dest = NULL_O_STRING;
  5583. const char *cp;
  5584. cp = str;
  5585. for (;;) {
  5586. if (!*cp) return NULL; /* string has no special chars */
  5587. if (*cp == '$') break;
  5588. if (*cp == '\\') break;
  5589. #if ENABLE_HUSH_TICK
  5590. if (*cp == '`') break;
  5591. #endif
  5592. cp++;
  5593. }
  5594. /* We need to expand. Example:
  5595. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5596. */
  5597. setup_string_in_str(&input, str);
  5598. encode_string(NULL, &dest, &input, EOF);
  5599. //TODO: error check (encode_string returns 0 on error)?
  5600. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5601. exp_str = expand_string_to_string(dest.data,
  5602. EXP_FLAG_ESC_GLOB_CHARS,
  5603. /*unbackslash:*/ 1
  5604. );
  5605. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5606. o_free(&dest);
  5607. return exp_str;
  5608. }
  5609. static const char *first_special_char_in_vararg(const char *cp)
  5610. {
  5611. for (;;) {
  5612. if (!*cp) return NULL; /* string has no special chars */
  5613. if (*cp == '$') return cp;
  5614. if (*cp == '\\') return cp;
  5615. if (*cp == '\'') return cp;
  5616. if (*cp == '"') return cp;
  5617. #if ENABLE_HUSH_TICK
  5618. if (*cp == '`') return cp;
  5619. #endif
  5620. /* dquoted "${x:+ARG}" should not glob, therefore
  5621. * '*' et al require some non-literal processing: */
  5622. if (*cp == '*') return cp;
  5623. if (*cp == '?') return cp;
  5624. if (*cp == '[') return cp;
  5625. cp++;
  5626. }
  5627. }
  5628. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5629. * These can contain single- and double-quoted strings,
  5630. * and treated as if the ARG string is initially unquoted. IOW:
  5631. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5632. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5633. * (word splitting and globbing of the ${var...} result).
  5634. */
  5635. #if !BASH_PATTERN_SUBST
  5636. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5637. encode_then_expand_vararg(str, handle_squotes)
  5638. #endif
  5639. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5640. {
  5641. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5642. const int do_unbackslash = 0;
  5643. #endif
  5644. char *exp_str;
  5645. struct in_str input;
  5646. o_string dest = NULL_O_STRING;
  5647. if (!first_special_char_in_vararg(str)) {
  5648. /* string has no special chars */
  5649. return NULL;
  5650. }
  5651. setup_string_in_str(&input, str);
  5652. dest.data = xzalloc(1); /* start as "", not as NULL */
  5653. exp_str = NULL;
  5654. for (;;) {
  5655. int ch;
  5656. ch = i_getch(&input);
  5657. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5658. __func__, ch, ch, !!dest.o_expflags);
  5659. if (!dest.o_expflags) {
  5660. if (ch == EOF)
  5661. break;
  5662. if (handle_squotes && ch == '\'') {
  5663. if (!add_till_single_quote_dquoted(&dest, &input))
  5664. goto ret; /* error */
  5665. continue;
  5666. }
  5667. }
  5668. if (ch == EOF) {
  5669. syntax_error_unterm_ch('"');
  5670. goto ret; /* error */
  5671. }
  5672. if (ch == '"') {
  5673. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5674. continue;
  5675. }
  5676. if (ch == '\\') {
  5677. ch = i_getch(&input);
  5678. if (ch == EOF) {
  5679. //example? error message? syntax_error_unterm_ch('"');
  5680. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5681. goto ret;
  5682. }
  5683. o_addqchr(&dest, ch);
  5684. continue;
  5685. }
  5686. if (ch == '$') {
  5687. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5688. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5689. goto ret;
  5690. }
  5691. continue;
  5692. }
  5693. #if ENABLE_HUSH_TICK
  5694. if (ch == '`') {
  5695. //unsigned pos = dest->length;
  5696. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5697. o_addchr(&dest, 0x80 | '`');
  5698. if (!add_till_backquote(&dest, &input,
  5699. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5700. )
  5701. ) {
  5702. goto ret; /* error */
  5703. }
  5704. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5705. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5706. continue;
  5707. }
  5708. #endif
  5709. o_addQchr(&dest, ch);
  5710. } /* for (;;) */
  5711. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5712. exp_str = expand_string_to_string(dest.data,
  5713. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5714. do_unbackslash
  5715. );
  5716. ret:
  5717. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5718. o_free(&dest);
  5719. return exp_str;
  5720. }
  5721. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5722. */
  5723. static int encode_then_append_var_plusminus(o_string *output, int n,
  5724. char *str, int dquoted)
  5725. {
  5726. struct in_str input;
  5727. o_string dest = NULL_O_STRING;
  5728. if (!first_special_char_in_vararg(str)
  5729. && '\0' == str[strcspn(str, G.ifs)]
  5730. ) {
  5731. /* string has no special chars
  5732. * && string has no $IFS chars
  5733. */
  5734. return expand_vars_to_list(output, n, str);
  5735. }
  5736. setup_string_in_str(&input, str);
  5737. for (;;) {
  5738. int ch;
  5739. ch = i_getch(&input);
  5740. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5741. __func__, ch, ch, dest.o_expflags);
  5742. if (!dest.o_expflags) {
  5743. if (ch == EOF)
  5744. break;
  5745. if (!dquoted && strchr(G.ifs, ch)) {
  5746. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5747. * do not assume we are at the start of the word (PREFIX above).
  5748. */
  5749. if (dest.data) {
  5750. n = expand_vars_to_list(output, n, dest.data);
  5751. o_free_and_set_NULL(&dest);
  5752. o_addchr(output, '\0');
  5753. n = o_save_ptr(output, n); /* create next word */
  5754. } else
  5755. if (output->length != o_get_last_ptr(output, n)
  5756. || output->has_quoted_part
  5757. ) {
  5758. /* For these cases:
  5759. * f() { for i; do echo "|$i|"; done; }; x=x
  5760. * f a${x:+ }b # 1st condition
  5761. * |a|
  5762. * |b|
  5763. * f ""${x:+ }b # 2nd condition
  5764. * ||
  5765. * |b|
  5766. */
  5767. o_addchr(output, '\0');
  5768. n = o_save_ptr(output, n); /* create next word */
  5769. }
  5770. continue;
  5771. }
  5772. if (!dquoted && ch == '\'') {
  5773. if (!add_till_single_quote_dquoted(&dest, &input))
  5774. goto ret; /* error */
  5775. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5776. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5777. continue;
  5778. }
  5779. }
  5780. if (ch == EOF) {
  5781. syntax_error_unterm_ch('"');
  5782. goto ret; /* error */
  5783. }
  5784. if (ch == '"') {
  5785. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5786. if (dest.o_expflags) {
  5787. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5788. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5789. }
  5790. continue;
  5791. }
  5792. if (ch == '\\') {
  5793. ch = i_getch(&input);
  5794. if (ch == EOF) {
  5795. //example? error message? syntax_error_unterm_ch('"');
  5796. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5797. goto ret;
  5798. }
  5799. o_addqchr(&dest, ch);
  5800. continue;
  5801. }
  5802. if (ch == '$') {
  5803. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5804. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5805. goto ret;
  5806. }
  5807. continue;
  5808. }
  5809. #if ENABLE_HUSH_TICK
  5810. if (ch == '`') {
  5811. //unsigned pos = dest->length;
  5812. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5813. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5814. if (!add_till_backquote(&dest, &input,
  5815. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5816. )
  5817. ) {
  5818. goto ret; /* error */
  5819. }
  5820. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5821. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5822. continue;
  5823. }
  5824. #endif
  5825. if (dquoted) {
  5826. /* Always glob-protect if in dquotes:
  5827. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5828. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5829. */
  5830. o_addqchr(&dest, ch);
  5831. } else {
  5832. /* Glob-protect only if char is quoted:
  5833. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5834. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5835. */
  5836. o_addQchr(&dest, ch);
  5837. }
  5838. } /* for (;;) */
  5839. if (dest.data) {
  5840. n = expand_vars_to_list(output, n, dest.data);
  5841. }
  5842. ret:
  5843. o_free(&dest);
  5844. return n;
  5845. }
  5846. #if ENABLE_FEATURE_SH_MATH
  5847. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5848. {
  5849. arith_state_t math_state;
  5850. arith_t res;
  5851. char *exp_str;
  5852. math_state.lookupvar = get_local_var_value;
  5853. math_state.setvar = set_local_var_from_halves;
  5854. //math_state.endofname = endofname;
  5855. exp_str = encode_then_expand_string(arg);
  5856. res = arith(&math_state, exp_str ? exp_str : arg);
  5857. free(exp_str);
  5858. if (errmsg_p)
  5859. *errmsg_p = math_state.errmsg;
  5860. if (math_state.errmsg)
  5861. msg_and_die_if_script(math_state.errmsg);
  5862. return res;
  5863. }
  5864. #endif
  5865. #if BASH_PATTERN_SUBST
  5866. /* ${var/[/]pattern[/repl]} helpers */
  5867. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5868. {
  5869. while (1) {
  5870. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5871. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5872. if (end) {
  5873. *size = end - val;
  5874. return val;
  5875. }
  5876. if (*val == '\0')
  5877. return NULL;
  5878. /* Optimization: if "*pat" did not match the start of "string",
  5879. * we know that "tring", "ring" etc will not match too:
  5880. */
  5881. if (pattern[0] == '*')
  5882. return NULL;
  5883. val++;
  5884. }
  5885. }
  5886. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5887. {
  5888. char *result = NULL;
  5889. unsigned res_len = 0;
  5890. unsigned repl_len = strlen(repl);
  5891. /* Null pattern never matches, including if "var" is empty */
  5892. if (!pattern[0])
  5893. return result; /* NULL, no replaces happened */
  5894. while (1) {
  5895. int size;
  5896. char *s = strstr_pattern(val, pattern, &size);
  5897. if (!s)
  5898. break;
  5899. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5900. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5901. res_len += (s - val) + repl_len;
  5902. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5903. val = s + size;
  5904. if (exp_op == '/')
  5905. break;
  5906. }
  5907. if (*val && result) {
  5908. result = xrealloc(result, res_len + strlen(val) + 1);
  5909. strcpy(result + res_len, val);
  5910. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5911. }
  5912. debug_printf_varexp("result:'%s'\n", result);
  5913. return result;
  5914. }
  5915. #endif /* BASH_PATTERN_SUBST */
  5916. static int append_str_maybe_ifs_split(o_string *output, int n,
  5917. int first_ch, const char *val)
  5918. {
  5919. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5920. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5921. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5922. if (val && val[0])
  5923. n = expand_on_ifs(output, n, val);
  5924. } else { /* quoted "$VAR" */
  5925. output->has_quoted_part = 1;
  5926. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5927. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5928. if (val && val[0])
  5929. o_addQstr(output, val);
  5930. }
  5931. return n;
  5932. }
  5933. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5934. */
  5935. static NOINLINE int expand_one_var(o_string *output, int n,
  5936. int first_ch, char *arg, char **pp)
  5937. {
  5938. const char *val;
  5939. char *to_be_freed;
  5940. char *p;
  5941. char *var;
  5942. char exp_op;
  5943. char exp_save = exp_save; /* for compiler */
  5944. char *exp_saveptr; /* points to expansion operator */
  5945. char *exp_word = exp_word; /* for compiler */
  5946. char arg0;
  5947. val = NULL;
  5948. to_be_freed = NULL;
  5949. p = *pp;
  5950. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5951. var = arg;
  5952. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5953. arg0 = arg[0];
  5954. arg[0] = (arg0 & 0x7f);
  5955. exp_op = 0;
  5956. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5957. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5958. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5959. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5960. ) {
  5961. /* It must be length operator: ${#var} */
  5962. var++;
  5963. exp_op = 'L';
  5964. } else {
  5965. /* Maybe handle parameter expansion */
  5966. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5967. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5968. ) {
  5969. /* ${?:0}, ${#[:]%0} etc */
  5970. exp_saveptr = var + 1;
  5971. } else {
  5972. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5973. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5974. }
  5975. exp_op = exp_save = *exp_saveptr;
  5976. if (exp_op) {
  5977. exp_word = exp_saveptr + 1;
  5978. if (exp_op == ':') {
  5979. exp_op = *exp_word++;
  5980. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5981. if (BASH_SUBSTR
  5982. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5983. ) {
  5984. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5985. exp_op = ':';
  5986. exp_word--;
  5987. }
  5988. }
  5989. *exp_saveptr = '\0';
  5990. } /* else: it's not an expansion op, but bare ${var} */
  5991. }
  5992. /* Look up the variable in question */
  5993. if (isdigit(var[0])) {
  5994. /* parse_dollar should have vetted var for us */
  5995. int nn = xatoi_positive(var);
  5996. if (nn < G.global_argc)
  5997. val = G.global_argv[nn];
  5998. /* else val remains NULL: $N with too big N */
  5999. } else {
  6000. switch (var[0]) {
  6001. case '$': /* pid */
  6002. val = utoa(G.root_pid);
  6003. break;
  6004. case '!': /* bg pid */
  6005. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6006. break;
  6007. case '?': /* exitcode */
  6008. val = utoa(G.last_exitcode);
  6009. break;
  6010. case '#': /* argc */
  6011. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6012. break;
  6013. default:
  6014. val = get_local_var_value(var);
  6015. }
  6016. }
  6017. /* Handle any expansions */
  6018. if (exp_op == 'L') {
  6019. reinit_unicode_for_hush();
  6020. debug_printf_expand("expand: length(%s)=", val);
  6021. val = utoa(val ? unicode_strlen(val) : 0);
  6022. debug_printf_expand("%s\n", val);
  6023. } else if (exp_op) {
  6024. if (exp_op == '%' || exp_op == '#') {
  6025. /* Standard-mandated substring removal ops:
  6026. * ${parameter%word} - remove smallest suffix pattern
  6027. * ${parameter%%word} - remove largest suffix pattern
  6028. * ${parameter#word} - remove smallest prefix pattern
  6029. * ${parameter##word} - remove largest prefix pattern
  6030. *
  6031. * Word is expanded to produce a glob pattern.
  6032. * Then var's value is matched to it and matching part removed.
  6033. */
  6034. //FIXME: ${x#...${...}...}
  6035. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6036. //inner ${...} may have side effects!
  6037. if (val && val[0]) {
  6038. char *t;
  6039. char *exp_exp_word;
  6040. char *loc;
  6041. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6042. if (exp_op == *exp_word) /* ## or %% */
  6043. exp_word++;
  6044. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6045. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6046. if (exp_exp_word)
  6047. exp_word = exp_exp_word;
  6048. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6049. /*
  6050. * HACK ALERT. We depend here on the fact that
  6051. * G.global_argv and results of utoa and get_local_var_value
  6052. * are actually in writable memory:
  6053. * scan_and_match momentarily stores NULs there.
  6054. */
  6055. t = (char*)val;
  6056. loc = scan_and_match(t, exp_word, scan_flags);
  6057. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6058. free(exp_exp_word);
  6059. if (loc) { /* match was found */
  6060. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6061. val = loc; /* take right part */
  6062. else /* %[%] */
  6063. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6064. }
  6065. }
  6066. }
  6067. #if BASH_PATTERN_SUBST
  6068. else if (exp_op == '/' || exp_op == '\\') {
  6069. /* It's ${var/[/]pattern[/repl]} thing.
  6070. * Note that in encoded form it has TWO parts:
  6071. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6072. * and if // is used, it is encoded as \:
  6073. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6074. */
  6075. if (val && val[0]) {
  6076. /* pattern uses non-standard expansion.
  6077. * repl should be unbackslashed and globbed
  6078. * by the usual expansion rules:
  6079. * >az >bz
  6080. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6081. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6082. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6083. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6084. * (note that a*z _pattern_ is never globbed!)
  6085. */
  6086. char *pattern, *repl, *t;
  6087. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6088. if (!pattern)
  6089. pattern = xstrdup(exp_word);
  6090. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6091. *p++ = SPECIAL_VAR_SYMBOL;
  6092. exp_word = p;
  6093. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6094. *p = '\0';
  6095. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6096. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6097. /* HACK ALERT. We depend here on the fact that
  6098. * G.global_argv and results of utoa and get_local_var_value
  6099. * are actually in writable memory:
  6100. * replace_pattern momentarily stores NULs there. */
  6101. t = (char*)val;
  6102. to_be_freed = replace_pattern(t,
  6103. pattern,
  6104. (repl ? repl : exp_word),
  6105. exp_op);
  6106. if (to_be_freed) /* at least one replace happened */
  6107. val = to_be_freed;
  6108. free(pattern);
  6109. free(repl);
  6110. } else {
  6111. /* Empty variable always gives nothing */
  6112. // "v=''; echo ${v/*/w}" prints "", not "w"
  6113. /* Just skip "replace" part */
  6114. *p++ = SPECIAL_VAR_SYMBOL;
  6115. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6116. *p = '\0';
  6117. }
  6118. }
  6119. #endif /* BASH_PATTERN_SUBST */
  6120. else if (exp_op == ':') {
  6121. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6122. /* It's ${var:N[:M]} bashism.
  6123. * Note that in encoded form it has TWO parts:
  6124. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6125. */
  6126. arith_t beg, len;
  6127. const char *errmsg;
  6128. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6129. if (errmsg)
  6130. goto arith_err;
  6131. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6132. *p++ = SPECIAL_VAR_SYMBOL;
  6133. exp_word = p;
  6134. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6135. *p = '\0';
  6136. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6137. if (errmsg)
  6138. goto arith_err;
  6139. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6140. if (beg < 0) {
  6141. /* negative beg counts from the end */
  6142. beg = (arith_t)strlen(val) + beg;
  6143. if (beg < 0) /* ${v: -999999} is "" */
  6144. beg = len = 0;
  6145. }
  6146. debug_printf_varexp("from val:'%s'\n", val);
  6147. if (len < 0) {
  6148. /* in bash, len=-n means strlen()-n */
  6149. len = (arith_t)strlen(val) - beg + len;
  6150. if (len < 0) /* bash compat */
  6151. msg_and_die_if_script("%s: substring expression < 0", var);
  6152. }
  6153. if (len <= 0 || !val || beg >= strlen(val)) {
  6154. arith_err:
  6155. val = NULL;
  6156. } else {
  6157. /* Paranoia. What if user entered 9999999999999
  6158. * which fits in arith_t but not int? */
  6159. if (len >= INT_MAX)
  6160. len = INT_MAX;
  6161. val = to_be_freed = xstrndup(val + beg, len);
  6162. }
  6163. debug_printf_varexp("val:'%s'\n", val);
  6164. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6165. msg_and_die_if_script("malformed ${%s:...}", var);
  6166. val = NULL;
  6167. #endif
  6168. } else { /* one of "-=+?" */
  6169. /* Standard-mandated substitution ops:
  6170. * ${var?word} - indicate error if unset
  6171. * If var is unset, word (or a message indicating it is unset
  6172. * if word is null) is written to standard error
  6173. * and the shell exits with a non-zero exit status.
  6174. * Otherwise, the value of var is substituted.
  6175. * ${var-word} - use default value
  6176. * If var is unset, word is substituted.
  6177. * ${var=word} - assign and use default value
  6178. * If var is unset, word is assigned to var.
  6179. * In all cases, final value of var is substituted.
  6180. * ${var+word} - use alternative value
  6181. * If var is unset, null is substituted.
  6182. * Otherwise, word is substituted.
  6183. *
  6184. * Word is subjected to tilde expansion, parameter expansion,
  6185. * command substitution, and arithmetic expansion.
  6186. * If word is not needed, it is not expanded.
  6187. *
  6188. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6189. * but also treat null var as if it is unset.
  6190. *
  6191. * Word-splitting and single quote behavior:
  6192. *
  6193. * $ f() { for i; do echo "|$i|"; done; };
  6194. *
  6195. * $ x=; f ${x:?'x y' z}
  6196. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6197. * $ x=; f "${x:?'x y' z}"
  6198. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6199. *
  6200. * $ x=; f ${x:='x y' z}
  6201. * |x|
  6202. * |y|
  6203. * |z|
  6204. * $ x=; f "${x:='x y' z}"
  6205. * |'x y' z|
  6206. *
  6207. * $ x=x; f ${x:+'x y' z}
  6208. * |x y|
  6209. * |z|
  6210. * $ x=x; f "${x:+'x y' z}"
  6211. * |'x y' z|
  6212. *
  6213. * $ x=; f ${x:-'x y' z}
  6214. * |x y|
  6215. * |z|
  6216. * $ x=; f "${x:-'x y' z}"
  6217. * |'x y' z|
  6218. */
  6219. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6220. if (exp_op == '+')
  6221. use_word = !use_word;
  6222. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6223. (exp_save == ':') ? "true" : "false", use_word);
  6224. if (use_word) {
  6225. if (exp_op == '+' || exp_op == '-') {
  6226. /* ${var+word} - use alternative value */
  6227. /* ${var-word} - use default value */
  6228. n = encode_then_append_var_plusminus(output, n, exp_word,
  6229. /*dquoted:*/ (arg0 & 0x80)
  6230. );
  6231. val = NULL;
  6232. } else {
  6233. /* ${var?word} - indicate error if unset */
  6234. /* ${var=word} - assign and use default value */
  6235. to_be_freed = encode_then_expand_vararg(exp_word,
  6236. /*handle_squotes:*/ !(arg0 & 0x80),
  6237. /*unbackslash:*/ 0
  6238. );
  6239. if (to_be_freed)
  6240. exp_word = to_be_freed;
  6241. if (exp_op == '?') {
  6242. /* mimic bash message */
  6243. msg_and_die_if_script("%s: %s",
  6244. var,
  6245. exp_word[0]
  6246. ? exp_word
  6247. : "parameter null or not set"
  6248. /* ash has more specific messages, a-la: */
  6249. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6250. );
  6251. //TODO: how interactive bash aborts expansion mid-command?
  6252. //It aborts the entire line, returns to prompt:
  6253. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6254. // bash: x: x y z
  6255. // $
  6256. // ("echo YO" is not executed, neither the f function call)
  6257. } else {
  6258. val = exp_word;
  6259. }
  6260. if (exp_op == '=') {
  6261. /* ${var=[word]} or ${var:=[word]} */
  6262. if (isdigit(var[0]) || var[0] == '#') {
  6263. /* mimic bash message */
  6264. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6265. val = NULL;
  6266. } else {
  6267. char *new_var = xasprintf("%s=%s", var, val);
  6268. set_local_var(new_var, /*flag:*/ 0);
  6269. }
  6270. }
  6271. }
  6272. }
  6273. } /* one of "-=+?" */
  6274. *exp_saveptr = exp_save;
  6275. } /* if (exp_op) */
  6276. arg[0] = arg0;
  6277. *pp = p;
  6278. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6279. free(to_be_freed);
  6280. return n;
  6281. }
  6282. /* Expand all variable references in given string, adding words to list[]
  6283. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6284. * to be filled). This routine is extremely tricky: has to deal with
  6285. * variables/parameters with whitespace, $* and $@, and constructs like
  6286. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6287. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6288. {
  6289. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6290. * expansion of right-hand side of assignment == 1-element expand.
  6291. */
  6292. char cant_be_null = 0; /* only bit 0x80 matters */
  6293. char *p;
  6294. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6295. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6296. debug_print_list("expand_vars_to_list[0]", output, n);
  6297. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6298. char first_ch;
  6299. #if ENABLE_FEATURE_SH_MATH
  6300. char arith_buf[sizeof(arith_t)*3 + 2];
  6301. #endif
  6302. if (output->ended_in_ifs) {
  6303. o_addchr(output, '\0');
  6304. n = o_save_ptr(output, n);
  6305. output->ended_in_ifs = 0;
  6306. }
  6307. o_addblock(output, arg, p - arg);
  6308. debug_print_list("expand_vars_to_list[1]", output, n);
  6309. arg = ++p;
  6310. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6311. /* Fetch special var name (if it is indeed one of them)
  6312. * and quote bit, force the bit on if singleword expansion -
  6313. * important for not getting v=$@ expand to many words. */
  6314. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6315. /* Is this variable quoted and thus expansion can't be null?
  6316. * "$@" is special. Even if quoted, it can still
  6317. * expand to nothing (not even an empty string),
  6318. * thus it is excluded. */
  6319. if ((first_ch & 0x7f) != '@')
  6320. cant_be_null |= first_ch;
  6321. switch (first_ch & 0x7f) {
  6322. /* Highest bit in first_ch indicates that var is double-quoted */
  6323. case '*':
  6324. case '@': {
  6325. int i;
  6326. if (!G.global_argv[1])
  6327. break;
  6328. i = 1;
  6329. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6330. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6331. while (G.global_argv[i]) {
  6332. n = expand_on_ifs(output, n, G.global_argv[i]);
  6333. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6334. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6335. /* this argv[] is not empty and not last:
  6336. * put terminating NUL, start new word */
  6337. o_addchr(output, '\0');
  6338. debug_print_list("expand_vars_to_list[2]", output, n);
  6339. n = o_save_ptr(output, n);
  6340. debug_print_list("expand_vars_to_list[3]", output, n);
  6341. }
  6342. }
  6343. } else
  6344. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6345. * and in this case should treat it like '$*' - see 'else...' below */
  6346. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6347. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6348. ) {
  6349. while (1) {
  6350. o_addQstr(output, G.global_argv[i]);
  6351. if (++i >= G.global_argc)
  6352. break;
  6353. o_addchr(output, '\0');
  6354. debug_print_list("expand_vars_to_list[4]", output, n);
  6355. n = o_save_ptr(output, n);
  6356. }
  6357. } else { /* quoted $* (or v="$@" case): add as one word */
  6358. while (1) {
  6359. o_addQstr(output, G.global_argv[i]);
  6360. if (!G.global_argv[++i])
  6361. break;
  6362. if (G.ifs[0])
  6363. o_addchr(output, G.ifs[0]);
  6364. }
  6365. output->has_quoted_part = 1;
  6366. }
  6367. break;
  6368. }
  6369. case SPECIAL_VAR_SYMBOL: {
  6370. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6371. /* "Empty variable", used to make "" etc to not disappear */
  6372. output->has_quoted_part = 1;
  6373. cant_be_null = 0x80;
  6374. arg++;
  6375. break;
  6376. }
  6377. case SPECIAL_VAR_QUOTED_SVS:
  6378. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6379. /* "^C variable", represents literal ^C char (possible in scripts) */
  6380. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6381. arg++;
  6382. break;
  6383. #if ENABLE_HUSH_TICK
  6384. case '`': {
  6385. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6386. o_string subst_result = NULL_O_STRING;
  6387. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6388. arg++;
  6389. /* Can't just stuff it into output o_string,
  6390. * expanded result may need to be globbed
  6391. * and $IFS-split */
  6392. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6393. G.last_exitcode = process_command_subs(&subst_result, arg);
  6394. G.expand_exitcode = G.last_exitcode;
  6395. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6396. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6397. o_free(&subst_result);
  6398. break;
  6399. }
  6400. #endif
  6401. #if ENABLE_FEATURE_SH_MATH
  6402. case '+': {
  6403. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6404. arith_t res;
  6405. arg++; /* skip '+' */
  6406. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6407. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6408. res = expand_and_evaluate_arith(arg, NULL);
  6409. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6410. sprintf(arith_buf, ARITH_FMT, res);
  6411. o_addstr(output, arith_buf);
  6412. break;
  6413. }
  6414. #endif
  6415. default:
  6416. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6417. n = expand_one_var(output, n, first_ch, arg, &p);
  6418. break;
  6419. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6420. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6421. * Do the check to avoid writing to a const string. */
  6422. if (*p != SPECIAL_VAR_SYMBOL)
  6423. *p = SPECIAL_VAR_SYMBOL;
  6424. arg = ++p;
  6425. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6426. if (*arg) {
  6427. /* handle trailing string */
  6428. if (output->ended_in_ifs) {
  6429. o_addchr(output, '\0');
  6430. n = o_save_ptr(output, n);
  6431. }
  6432. debug_print_list("expand_vars_to_list[a]", output, n);
  6433. /* this part is literal, and it was already pre-quoted
  6434. * if needed (much earlier), do not use o_addQstr here!
  6435. */
  6436. o_addstr(output, arg);
  6437. debug_print_list("expand_vars_to_list[b]", output, n);
  6438. } else
  6439. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6440. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6441. && !output->has_quoted_part
  6442. ) {
  6443. n--;
  6444. /* allow to reuse list[n] later without re-growth */
  6445. output->has_empty_slot = 1;
  6446. }
  6447. return n;
  6448. }
  6449. static char **expand_variables(char **argv, unsigned expflags)
  6450. {
  6451. int n;
  6452. char **list;
  6453. o_string output = NULL_O_STRING;
  6454. output.o_expflags = expflags;
  6455. n = 0;
  6456. for (;;) {
  6457. /* go to next list[n] */
  6458. output.ended_in_ifs = 0;
  6459. n = o_save_ptr(&output, n);
  6460. if (!*argv)
  6461. break;
  6462. /* expand argv[i] */
  6463. n = expand_vars_to_list(&output, n, *argv++);
  6464. /* if (!output->has_empty_slot) -- need this?? */
  6465. o_addchr(&output, '\0');
  6466. }
  6467. debug_print_list("expand_variables", &output, n);
  6468. /* output.data (malloced in one block) gets returned in "list" */
  6469. list = o_finalize_list(&output, n);
  6470. debug_print_strings("expand_variables[1]", list);
  6471. return list;
  6472. }
  6473. static char **expand_strvec_to_strvec(char **argv)
  6474. {
  6475. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6476. }
  6477. #if defined(CMD_SINGLEWORD_NOGLOB)
  6478. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6479. {
  6480. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6481. }
  6482. #endif
  6483. /* Used for expansion of right hand of assignments,
  6484. * $((...)), heredocs, variable expansion parts.
  6485. *
  6486. * NB: should NOT do globbing!
  6487. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6488. */
  6489. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6490. {
  6491. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6492. const int do_unbackslash = 1;
  6493. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6494. #endif
  6495. char *argv[2], **list;
  6496. debug_printf_expand("string_to_string<='%s'\n", str);
  6497. /* This is generally an optimization, but it also
  6498. * handles "", which otherwise trips over !list[0] check below.
  6499. * (is this ever happens that we actually get str="" here?)
  6500. */
  6501. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6502. //TODO: Can use on strings with \ too, just unbackslash() them?
  6503. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6504. return xstrdup(str);
  6505. }
  6506. argv[0] = (char*)str;
  6507. argv[1] = NULL;
  6508. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6509. if (!list[0]) {
  6510. /* Example where it happens:
  6511. * x=; echo ${x:-"$@"}
  6512. */
  6513. ((char*)list)[0] = '\0';
  6514. } else {
  6515. if (HUSH_DEBUG)
  6516. if (list[1])
  6517. bb_error_msg_and_die("BUG in varexp2");
  6518. /* actually, just move string 2*sizeof(char*) bytes back */
  6519. overlapping_strcpy((char*)list, list[0]);
  6520. if (do_unbackslash)
  6521. unbackslash((char*)list);
  6522. }
  6523. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6524. return (char*)list;
  6525. }
  6526. #if 0
  6527. static char* expand_strvec_to_string(char **argv)
  6528. {
  6529. char **list;
  6530. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6531. /* Convert all NULs to spaces */
  6532. if (list[0]) {
  6533. int n = 1;
  6534. while (list[n]) {
  6535. if (HUSH_DEBUG)
  6536. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6537. bb_error_msg_and_die("BUG in varexp3");
  6538. /* bash uses ' ' regardless of $IFS contents */
  6539. list[n][-1] = ' ';
  6540. n++;
  6541. }
  6542. }
  6543. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6544. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6545. return (char*)list;
  6546. }
  6547. #endif
  6548. static char **expand_assignments(char **argv, int count)
  6549. {
  6550. int i;
  6551. char **p;
  6552. G.expanded_assignments = p = NULL;
  6553. /* Expand assignments into one string each */
  6554. for (i = 0; i < count; i++) {
  6555. p = add_string_to_strings(p,
  6556. expand_string_to_string(argv[i],
  6557. EXP_FLAG_ESC_GLOB_CHARS,
  6558. /*unbackslash:*/ 1
  6559. )
  6560. );
  6561. G.expanded_assignments = p;
  6562. }
  6563. G.expanded_assignments = NULL;
  6564. return p;
  6565. }
  6566. static void switch_off_special_sigs(unsigned mask)
  6567. {
  6568. unsigned sig = 0;
  6569. while ((mask >>= 1) != 0) {
  6570. sig++;
  6571. if (!(mask & 1))
  6572. continue;
  6573. #if ENABLE_HUSH_TRAP
  6574. if (G_traps) {
  6575. if (G_traps[sig] && !G_traps[sig][0])
  6576. /* trap is '', has to remain SIG_IGN */
  6577. continue;
  6578. free(G_traps[sig]);
  6579. G_traps[sig] = NULL;
  6580. }
  6581. #endif
  6582. /* We are here only if no trap or trap was not '' */
  6583. install_sighandler(sig, SIG_DFL);
  6584. }
  6585. }
  6586. #if BB_MMU
  6587. /* never called */
  6588. void re_execute_shell(char ***to_free, const char *s,
  6589. char *g_argv0, char **g_argv,
  6590. char **builtin_argv) NORETURN;
  6591. static void reset_traps_to_defaults(void)
  6592. {
  6593. /* This function is always called in a child shell
  6594. * after fork (not vfork, NOMMU doesn't use this function).
  6595. */
  6596. IF_HUSH_TRAP(unsigned sig;)
  6597. unsigned mask;
  6598. /* Child shells are not interactive.
  6599. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6600. * Testcase: (while :; do :; done) + ^Z should background.
  6601. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6602. */
  6603. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6604. if (!G_traps && !mask)
  6605. return; /* already no traps and no special sigs */
  6606. /* Switch off special sigs */
  6607. switch_off_special_sigs(mask);
  6608. # if ENABLE_HUSH_JOB
  6609. G_fatal_sig_mask = 0;
  6610. # endif
  6611. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6612. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6613. * remain set in G.special_sig_mask */
  6614. # if ENABLE_HUSH_TRAP
  6615. if (!G_traps)
  6616. return;
  6617. /* Reset all sigs to default except ones with empty traps */
  6618. for (sig = 0; sig < NSIG; sig++) {
  6619. if (!G_traps[sig])
  6620. continue; /* no trap: nothing to do */
  6621. if (!G_traps[sig][0])
  6622. continue; /* empty trap: has to remain SIG_IGN */
  6623. /* sig has non-empty trap, reset it: */
  6624. free(G_traps[sig]);
  6625. G_traps[sig] = NULL;
  6626. /* There is no signal for trap 0 (EXIT) */
  6627. if (sig == 0)
  6628. continue;
  6629. install_sighandler(sig, pick_sighandler(sig));
  6630. }
  6631. # endif
  6632. }
  6633. #else /* !BB_MMU */
  6634. static void re_execute_shell(char ***to_free, const char *s,
  6635. char *g_argv0, char **g_argv,
  6636. char **builtin_argv) NORETURN;
  6637. static void re_execute_shell(char ***to_free, const char *s,
  6638. char *g_argv0, char **g_argv,
  6639. char **builtin_argv)
  6640. {
  6641. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6642. /* delims + 2 * (number of bytes in printed hex numbers) */
  6643. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6644. char *heredoc_argv[4];
  6645. struct variable *cur;
  6646. # if ENABLE_HUSH_FUNCTIONS
  6647. struct function *funcp;
  6648. # endif
  6649. char **argv, **pp;
  6650. unsigned cnt;
  6651. unsigned long long empty_trap_mask;
  6652. if (!g_argv0) { /* heredoc */
  6653. argv = heredoc_argv;
  6654. argv[0] = (char *) G.argv0_for_re_execing;
  6655. argv[1] = (char *) "-<";
  6656. argv[2] = (char *) s;
  6657. argv[3] = NULL;
  6658. pp = &argv[3]; /* used as pointer to empty environment */
  6659. goto do_exec;
  6660. }
  6661. cnt = 0;
  6662. pp = builtin_argv;
  6663. if (pp) while (*pp++)
  6664. cnt++;
  6665. empty_trap_mask = 0;
  6666. if (G_traps) {
  6667. int sig;
  6668. for (sig = 1; sig < NSIG; sig++) {
  6669. if (G_traps[sig] && !G_traps[sig][0])
  6670. empty_trap_mask |= 1LL << sig;
  6671. }
  6672. }
  6673. sprintf(param_buf, NOMMU_HACK_FMT
  6674. , (unsigned) G.root_pid
  6675. , (unsigned) G.root_ppid
  6676. , (unsigned) G.last_bg_pid
  6677. , (unsigned) G.last_exitcode
  6678. , cnt
  6679. , empty_trap_mask
  6680. IF_HUSH_LOOPS(, G.depth_of_loop)
  6681. );
  6682. # undef NOMMU_HACK_FMT
  6683. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6684. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6685. */
  6686. cnt += 6;
  6687. for (cur = G.top_var; cur; cur = cur->next) {
  6688. if (!cur->flg_export || cur->flg_read_only)
  6689. cnt += 2;
  6690. }
  6691. # if ENABLE_HUSH_FUNCTIONS
  6692. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6693. cnt += 3;
  6694. # endif
  6695. pp = g_argv;
  6696. while (*pp++)
  6697. cnt++;
  6698. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6699. *pp++ = (char *) G.argv0_for_re_execing;
  6700. *pp++ = param_buf;
  6701. for (cur = G.top_var; cur; cur = cur->next) {
  6702. if (strcmp(cur->varstr, hush_version_str) == 0)
  6703. continue;
  6704. if (cur->flg_read_only) {
  6705. *pp++ = (char *) "-R";
  6706. *pp++ = cur->varstr;
  6707. } else if (!cur->flg_export) {
  6708. *pp++ = (char *) "-V";
  6709. *pp++ = cur->varstr;
  6710. }
  6711. }
  6712. # if ENABLE_HUSH_FUNCTIONS
  6713. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6714. *pp++ = (char *) "-F";
  6715. *pp++ = funcp->name;
  6716. *pp++ = funcp->body_as_string;
  6717. }
  6718. # endif
  6719. /* We can pass activated traps here. Say, -Tnn:trap_string
  6720. *
  6721. * However, POSIX says that subshells reset signals with traps
  6722. * to SIG_DFL.
  6723. * I tested bash-3.2 and it not only does that with true subshells
  6724. * of the form ( list ), but with any forked children shells.
  6725. * I set trap "echo W" WINCH; and then tried:
  6726. *
  6727. * { echo 1; sleep 20; echo 2; } &
  6728. * while true; do echo 1; sleep 20; echo 2; break; done &
  6729. * true | { echo 1; sleep 20; echo 2; } | cat
  6730. *
  6731. * In all these cases sending SIGWINCH to the child shell
  6732. * did not run the trap. If I add trap "echo V" WINCH;
  6733. * _inside_ group (just before echo 1), it works.
  6734. *
  6735. * I conclude it means we don't need to pass active traps here.
  6736. */
  6737. *pp++ = (char *) "-c";
  6738. *pp++ = (char *) s;
  6739. if (builtin_argv) {
  6740. while (*++builtin_argv)
  6741. *pp++ = *builtin_argv;
  6742. *pp++ = (char *) "";
  6743. }
  6744. *pp++ = g_argv0;
  6745. while (*g_argv)
  6746. *pp++ = *g_argv++;
  6747. /* *pp = NULL; - is already there */
  6748. pp = environ;
  6749. do_exec:
  6750. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6751. /* Don't propagate SIG_IGN to the child */
  6752. if (SPECIAL_JOBSTOP_SIGS != 0)
  6753. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6754. execve(bb_busybox_exec_path, argv, pp);
  6755. /* Fallback. Useful for init=/bin/hush usage etc */
  6756. if (argv[0][0] == '/')
  6757. execve(argv[0], argv, pp);
  6758. xfunc_error_retval = 127;
  6759. bb_error_msg_and_die("can't re-execute the shell");
  6760. }
  6761. #endif /* !BB_MMU */
  6762. static int run_and_free_list(struct pipe *pi);
  6763. /* Executing from string: eval, sh -c '...'
  6764. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6765. * end_trigger controls how often we stop parsing
  6766. * NUL: parse all, execute, return
  6767. * ';': parse till ';' or newline, execute, repeat till EOF
  6768. */
  6769. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6770. {
  6771. /* Why we need empty flag?
  6772. * An obscure corner case "false; ``; echo $?":
  6773. * empty command in `` should still set $? to 0.
  6774. * But we can't just set $? to 0 at the start,
  6775. * this breaks "false; echo `echo $?`" case.
  6776. */
  6777. bool empty = 1;
  6778. while (1) {
  6779. struct pipe *pipe_list;
  6780. #if ENABLE_HUSH_INTERACTIVE
  6781. if (end_trigger == ';') {
  6782. G.promptmode = 0; /* PS1 */
  6783. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6784. }
  6785. #endif
  6786. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6787. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6788. /* If we are in "big" script
  6789. * (not in `cmd` or something similar)...
  6790. */
  6791. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6792. /* Discard cached input (rest of line) */
  6793. int ch = inp->last_char;
  6794. while (ch != EOF && ch != '\n') {
  6795. //bb_error_msg("Discarded:'%c'", ch);
  6796. ch = i_getch(inp);
  6797. }
  6798. /* Force prompt */
  6799. inp->p = NULL;
  6800. /* This stream isn't empty */
  6801. empty = 0;
  6802. continue;
  6803. }
  6804. if (!pipe_list && empty)
  6805. G.last_exitcode = 0;
  6806. break;
  6807. }
  6808. debug_print_tree(pipe_list, 0);
  6809. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6810. run_and_free_list(pipe_list);
  6811. empty = 0;
  6812. if (G_flag_return_in_progress == 1)
  6813. break;
  6814. }
  6815. }
  6816. static void parse_and_run_string(const char *s)
  6817. {
  6818. struct in_str input;
  6819. //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6820. setup_string_in_str(&input, s);
  6821. parse_and_run_stream(&input, '\0');
  6822. //IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6823. }
  6824. static void parse_and_run_file(HFILE *fp)
  6825. {
  6826. struct in_str input;
  6827. IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6828. IF_HUSH_LINENO_VAR(G.lineno = 1;)
  6829. setup_file_in_str(&input, fp);
  6830. parse_and_run_stream(&input, ';');
  6831. IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6832. }
  6833. #if ENABLE_HUSH_TICK
  6834. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6835. {
  6836. pid_t pid;
  6837. int channel[2];
  6838. # if !BB_MMU
  6839. char **to_free = NULL;
  6840. # endif
  6841. xpipe(channel);
  6842. pid = BB_MMU ? xfork() : xvfork();
  6843. if (pid == 0) { /* child */
  6844. disable_restore_tty_pgrp_on_exit();
  6845. /* Process substitution is not considered to be usual
  6846. * 'command execution'.
  6847. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6848. */
  6849. bb_signals(0
  6850. + (1 << SIGTSTP)
  6851. + (1 << SIGTTIN)
  6852. + (1 << SIGTTOU)
  6853. , SIG_IGN);
  6854. close(channel[0]); /* NB: close _first_, then move fd! */
  6855. xmove_fd(channel[1], 1);
  6856. # if ENABLE_HUSH_TRAP
  6857. /* Awful hack for `trap` or $(trap).
  6858. *
  6859. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6860. * contains an example where "trap" is executed in a subshell:
  6861. *
  6862. * save_traps=$(trap)
  6863. * ...
  6864. * eval "$save_traps"
  6865. *
  6866. * Standard does not say that "trap" in subshell shall print
  6867. * parent shell's traps. It only says that its output
  6868. * must have suitable form, but then, in the above example
  6869. * (which is not supposed to be normative), it implies that.
  6870. *
  6871. * bash (and probably other shell) does implement it
  6872. * (traps are reset to defaults, but "trap" still shows them),
  6873. * but as a result, "trap" logic is hopelessly messed up:
  6874. *
  6875. * # trap
  6876. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6877. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6878. * # true | trap <--- trap is in subshell - no output (ditto)
  6879. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6880. * trap -- 'echo Ho' SIGWINCH
  6881. * # echo `(trap)` <--- in subshell in subshell - output
  6882. * trap -- 'echo Ho' SIGWINCH
  6883. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6884. * trap -- 'echo Ho' SIGWINCH
  6885. *
  6886. * The rules when to forget and when to not forget traps
  6887. * get really complex and nonsensical.
  6888. *
  6889. * Our solution: ONLY bare $(trap) or `trap` is special.
  6890. */
  6891. s = skip_whitespace(s);
  6892. if (is_prefixed_with(s, "trap")
  6893. && skip_whitespace(s + 4)[0] == '\0'
  6894. ) {
  6895. static const char *const argv[] = { NULL, NULL };
  6896. builtin_trap((char**)argv);
  6897. fflush_all(); /* important */
  6898. _exit(0);
  6899. }
  6900. # endif
  6901. # if BB_MMU
  6902. /* Prevent it from trying to handle ctrl-z etc */
  6903. IF_HUSH_JOB(G.run_list_level = 1;)
  6904. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6905. reset_traps_to_defaults();
  6906. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6907. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6908. parse_and_run_string(s);
  6909. _exit(G.last_exitcode);
  6910. # else
  6911. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6912. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6913. * huge=`cat BIG` # was blocking here forever
  6914. * echo OK
  6915. */
  6916. re_execute_shell(&to_free,
  6917. s,
  6918. G.global_argv[0],
  6919. G.global_argv + 1,
  6920. NULL);
  6921. # endif
  6922. }
  6923. /* parent */
  6924. *pid_p = pid;
  6925. # if ENABLE_HUSH_FAST
  6926. G.count_SIGCHLD++;
  6927. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6928. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6929. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6930. # endif
  6931. enable_restore_tty_pgrp_on_exit();
  6932. # if !BB_MMU
  6933. free(to_free);
  6934. # endif
  6935. close(channel[1]);
  6936. return channel[0];
  6937. }
  6938. /* Return code is exit status of the process that is run. */
  6939. static int process_command_subs(o_string *dest, const char *s)
  6940. {
  6941. FILE *fp;
  6942. pid_t pid;
  6943. int status, ch, eol_cnt;
  6944. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6945. /* Now send results of command back into original context */
  6946. eol_cnt = 0;
  6947. while ((ch = getc(fp)) != EOF) {
  6948. if (ch == '\0')
  6949. continue;
  6950. if (ch == '\n') {
  6951. eol_cnt++;
  6952. continue;
  6953. }
  6954. while (eol_cnt) {
  6955. o_addchr(dest, '\n');
  6956. eol_cnt--;
  6957. }
  6958. o_addQchr(dest, ch);
  6959. }
  6960. debug_printf("done reading from `cmd` pipe, closing it\n");
  6961. fclose(fp);
  6962. /* We need to extract exitcode. Test case
  6963. * "true; echo `sleep 1; false` $?"
  6964. * should print 1 */
  6965. safe_waitpid(pid, &status, 0);
  6966. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6967. return WEXITSTATUS(status);
  6968. }
  6969. #endif /* ENABLE_HUSH_TICK */
  6970. static void setup_heredoc(struct redir_struct *redir)
  6971. {
  6972. struct fd_pair pair;
  6973. pid_t pid;
  6974. int len, written;
  6975. /* the _body_ of heredoc (misleading field name) */
  6976. const char *heredoc = redir->rd_filename;
  6977. char *expanded;
  6978. #if !BB_MMU
  6979. char **to_free;
  6980. #endif
  6981. expanded = NULL;
  6982. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6983. expanded = encode_then_expand_string(heredoc);
  6984. if (expanded)
  6985. heredoc = expanded;
  6986. }
  6987. len = strlen(heredoc);
  6988. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  6989. xpiped_pair(pair);
  6990. xmove_fd(pair.rd, redir->rd_fd);
  6991. /* Try writing without forking. Newer kernels have
  6992. * dynamically growing pipes. Must use non-blocking write! */
  6993. ndelay_on(pair.wr);
  6994. while (1) {
  6995. written = write(pair.wr, heredoc, len);
  6996. if (written <= 0)
  6997. break;
  6998. len -= written;
  6999. if (len == 0) {
  7000. close(pair.wr);
  7001. free(expanded);
  7002. return;
  7003. }
  7004. heredoc += written;
  7005. }
  7006. ndelay_off(pair.wr);
  7007. /* Okay, pipe buffer was not big enough */
  7008. /* Note: we must not create a stray child (bastard? :)
  7009. * for the unsuspecting parent process. Child creates a grandchild
  7010. * and exits before parent execs the process which consumes heredoc
  7011. * (that exec happens after we return from this function) */
  7012. #if !BB_MMU
  7013. to_free = NULL;
  7014. #endif
  7015. pid = xvfork();
  7016. if (pid == 0) {
  7017. /* child */
  7018. disable_restore_tty_pgrp_on_exit();
  7019. pid = BB_MMU ? xfork() : xvfork();
  7020. if (pid != 0)
  7021. _exit(0);
  7022. /* grandchild */
  7023. close(redir->rd_fd); /* read side of the pipe */
  7024. #if BB_MMU
  7025. full_write(pair.wr, heredoc, len); /* may loop or block */
  7026. _exit(0);
  7027. #else
  7028. /* Delegate blocking writes to another process */
  7029. xmove_fd(pair.wr, STDOUT_FILENO);
  7030. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7031. #endif
  7032. }
  7033. /* parent */
  7034. #if ENABLE_HUSH_FAST
  7035. G.count_SIGCHLD++;
  7036. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7037. #endif
  7038. enable_restore_tty_pgrp_on_exit();
  7039. #if !BB_MMU
  7040. free(to_free);
  7041. #endif
  7042. close(pair.wr);
  7043. free(expanded);
  7044. wait(NULL); /* wait till child has died */
  7045. }
  7046. struct squirrel {
  7047. int orig_fd;
  7048. int moved_to;
  7049. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7050. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7051. };
  7052. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7053. {
  7054. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7055. sq[i].orig_fd = orig;
  7056. sq[i].moved_to = moved;
  7057. sq[i+1].orig_fd = -1; /* end marker */
  7058. return sq;
  7059. }
  7060. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7061. {
  7062. int moved_to;
  7063. int i;
  7064. i = 0;
  7065. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7066. /* If we collide with an already moved fd... */
  7067. if (fd == sq[i].moved_to) {
  7068. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7069. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7070. if (sq[i].moved_to < 0) /* what? */
  7071. xfunc_die();
  7072. return sq;
  7073. }
  7074. if (fd == sq[i].orig_fd) {
  7075. /* Example: echo Hello >/dev/null 1>&2 */
  7076. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7077. return sq;
  7078. }
  7079. }
  7080. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7081. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7082. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7083. if (moved_to < 0 && errno != EBADF)
  7084. xfunc_die();
  7085. return append_squirrel(sq, i, fd, moved_to);
  7086. }
  7087. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7088. {
  7089. int i;
  7090. i = 0;
  7091. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7092. /* If we collide with an already moved fd... */
  7093. if (fd == sq[i].orig_fd) {
  7094. /* Examples:
  7095. * "echo 3>FILE 3>&- 3>FILE"
  7096. * "echo 3>&- 3>FILE"
  7097. * No need for last redirect to insert
  7098. * another "need to close 3" indicator.
  7099. */
  7100. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7101. return sq;
  7102. }
  7103. }
  7104. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7105. return append_squirrel(sq, i, fd, -1);
  7106. }
  7107. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7108. * Move all conflicting internally used fds,
  7109. * and remember them so that we can restore them later.
  7110. */
  7111. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7112. {
  7113. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7114. avoid_fd = 9;
  7115. #if ENABLE_HUSH_INTERACTIVE
  7116. if (fd == G.interactive_fd) {
  7117. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7118. G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
  7119. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
  7120. return 1; /* "we closed fd" */
  7121. }
  7122. #endif
  7123. /* Are we called from setup_redirects(squirrel==NULL)
  7124. * in redirect in a [v]forked child?
  7125. */
  7126. if (sqp == NULL) {
  7127. /* No need to move script fds.
  7128. * For NOMMU case, it's actively wrong: we'd change ->fd
  7129. * fields in memory for the parent, but parent's fds
  7130. * aren't be moved, it would use wrong fd!
  7131. * Reproducer: "cmd 3>FILE" in script.
  7132. * If we would call move_HFILEs_on_redirect(), child would:
  7133. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7134. * close(3) = 0
  7135. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7136. */
  7137. //bb_error_msg("sqp == NULL: [v]forked child");
  7138. return 0;
  7139. }
  7140. /* If this one of script's fds? */
  7141. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7142. return 1; /* yes. "we closed fd" (actually moved it) */
  7143. /* Are we called for "exec 3>FILE"? Came through
  7144. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7145. * This case used to fail for this script:
  7146. * exec 3>FILE
  7147. * echo Ok
  7148. * ...100000 more lines...
  7149. * echo Ok
  7150. * as follows:
  7151. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7152. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7153. * dup2(4, 3) = 3
  7154. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7155. * close(4) = 0
  7156. * write(1, "Ok\n", 3) = 3
  7157. * ... = 3
  7158. * write(1, "Ok\n", 3) = 3
  7159. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7160. * ^^^^^^^^ oops, wrong fd!!!
  7161. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7162. * it now works:
  7163. */
  7164. if (sqp == ERR_PTR) {
  7165. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7166. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7167. return 0;
  7168. }
  7169. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7170. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7171. return 0; /* "we did not close fd" */
  7172. }
  7173. static void restore_redirects(struct squirrel *sq)
  7174. {
  7175. if (sq) {
  7176. int i;
  7177. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7178. if (sq[i].moved_to >= 0) {
  7179. /* We simply die on error */
  7180. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7181. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7182. } else {
  7183. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7184. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7185. close(sq[i].orig_fd);
  7186. }
  7187. }
  7188. free(sq);
  7189. }
  7190. /* If moved, G.interactive_fd stays on new fd, not restoring it */
  7191. }
  7192. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7193. static void close_saved_fds_and_FILE_fds(void)
  7194. {
  7195. if (G_interactive_fd)
  7196. close(G_interactive_fd);
  7197. close_all_HFILE_list();
  7198. }
  7199. #endif
  7200. static int internally_opened_fd(int fd, struct squirrel *sq)
  7201. {
  7202. int i;
  7203. #if ENABLE_HUSH_INTERACTIVE
  7204. if (fd == G.interactive_fd)
  7205. return 1;
  7206. #endif
  7207. /* If this one of script's fds? */
  7208. if (fd_in_HFILEs(fd))
  7209. return 1;
  7210. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7211. if (fd == sq[i].moved_to)
  7212. return 1;
  7213. }
  7214. return 0;
  7215. }
  7216. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7217. * and stderr if they are redirected. */
  7218. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7219. {
  7220. struct redir_struct *redir;
  7221. for (redir = prog->redirects; redir; redir = redir->next) {
  7222. int newfd;
  7223. int closed;
  7224. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7225. /* "rd_fd<<HERE" case */
  7226. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7227. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7228. * of the heredoc */
  7229. debug_printf_redir("set heredoc '%s'\n",
  7230. redir->rd_filename);
  7231. setup_heredoc(redir);
  7232. continue;
  7233. }
  7234. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7235. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7236. char *p;
  7237. int mode;
  7238. if (redir->rd_filename == NULL) {
  7239. /* Examples:
  7240. * "cmd >" (no filename)
  7241. * "cmd > <file" (2nd redirect starts too early)
  7242. */
  7243. syntax_error("invalid redirect");
  7244. continue;
  7245. }
  7246. mode = redir_table[redir->rd_type].mode;
  7247. p = expand_string_to_string(redir->rd_filename,
  7248. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7249. newfd = open_or_warn(p, mode);
  7250. free(p);
  7251. if (newfd < 0) {
  7252. /* Error message from open_or_warn can be lost
  7253. * if stderr has been redirected, but bash
  7254. * and ash both lose it as well
  7255. * (though zsh doesn't!)
  7256. */
  7257. return 1;
  7258. }
  7259. if (newfd == redir->rd_fd && sqp) {
  7260. /* open() gave us precisely the fd we wanted.
  7261. * This means that this fd was not busy
  7262. * (not opened to anywhere).
  7263. * Remember to close it on restore:
  7264. */
  7265. *sqp = add_squirrel_closed(*sqp, newfd);
  7266. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7267. }
  7268. } else {
  7269. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7270. newfd = redir->rd_dup;
  7271. }
  7272. if (newfd == redir->rd_fd)
  7273. continue;
  7274. /* if "N>FILE": move newfd to redir->rd_fd */
  7275. /* if "N>&M": dup newfd to redir->rd_fd */
  7276. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7277. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7278. if (newfd == REDIRFD_CLOSE) {
  7279. /* "N>&-" means "close me" */
  7280. if (!closed) {
  7281. /* ^^^ optimization: saving may already
  7282. * have closed it. If not... */
  7283. close(redir->rd_fd);
  7284. }
  7285. /* Sometimes we do another close on restore, getting EBADF.
  7286. * Consider "echo 3>FILE 3>&-"
  7287. * first redirect remembers "need to close 3",
  7288. * and second redirect closes 3! Restore code then closes 3 again.
  7289. */
  7290. } else {
  7291. /* if newfd is a script fd or saved fd, simulate EBADF */
  7292. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7293. //errno = EBADF;
  7294. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7295. newfd = -1; /* same effect as code above */
  7296. }
  7297. xdup2(newfd, redir->rd_fd);
  7298. if (redir->rd_dup == REDIRFD_TO_FILE)
  7299. /* "rd_fd > FILE" */
  7300. close(newfd);
  7301. /* else: "rd_fd > rd_dup" */
  7302. }
  7303. }
  7304. return 0;
  7305. }
  7306. static char *find_in_path(const char *arg)
  7307. {
  7308. char *ret = NULL;
  7309. const char *PATH = get_local_var_value("PATH");
  7310. if (!PATH)
  7311. return NULL;
  7312. while (1) {
  7313. const char *end = strchrnul(PATH, ':');
  7314. int sz = end - PATH; /* must be int! */
  7315. free(ret);
  7316. if (sz != 0) {
  7317. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7318. } else {
  7319. /* We have xxx::yyyy in $PATH,
  7320. * it means "use current dir" */
  7321. ret = xstrdup(arg);
  7322. }
  7323. if (access(ret, F_OK) == 0)
  7324. break;
  7325. if (*end == '\0') {
  7326. free(ret);
  7327. return NULL;
  7328. }
  7329. PATH = end + 1;
  7330. }
  7331. return ret;
  7332. }
  7333. static const struct built_in_command *find_builtin_helper(const char *name,
  7334. const struct built_in_command *x,
  7335. const struct built_in_command *end)
  7336. {
  7337. while (x != end) {
  7338. if (strcmp(name, x->b_cmd) != 0) {
  7339. x++;
  7340. continue;
  7341. }
  7342. debug_printf_exec("found builtin '%s'\n", name);
  7343. return x;
  7344. }
  7345. return NULL;
  7346. }
  7347. static const struct built_in_command *find_builtin1(const char *name)
  7348. {
  7349. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7350. }
  7351. static const struct built_in_command *find_builtin(const char *name)
  7352. {
  7353. const struct built_in_command *x = find_builtin1(name);
  7354. if (x)
  7355. return x;
  7356. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7357. }
  7358. static void remove_nested_vars(void)
  7359. {
  7360. struct variable *cur;
  7361. struct variable **cur_pp;
  7362. cur_pp = &G.top_var;
  7363. while ((cur = *cur_pp) != NULL) {
  7364. if (cur->var_nest_level <= G.var_nest_level) {
  7365. cur_pp = &cur->next;
  7366. continue;
  7367. }
  7368. /* Unexport */
  7369. if (cur->flg_export) {
  7370. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7371. bb_unsetenv(cur->varstr);
  7372. }
  7373. /* Remove from global list */
  7374. *cur_pp = cur->next;
  7375. /* Free */
  7376. if (!cur->max_len) {
  7377. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7378. free(cur->varstr);
  7379. }
  7380. free(cur);
  7381. }
  7382. }
  7383. static void enter_var_nest_level(void)
  7384. {
  7385. G.var_nest_level++;
  7386. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7387. /* Try: f() { echo -n .; f; }; f
  7388. * struct variable::var_nest_level is uint16_t,
  7389. * thus limiting recursion to < 2^16.
  7390. * In any case, with 8 Mbyte stack SEGV happens
  7391. * not too long after 2^16 recursions anyway.
  7392. */
  7393. if (G.var_nest_level > 0xff00)
  7394. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7395. }
  7396. static void leave_var_nest_level(void)
  7397. {
  7398. G.var_nest_level--;
  7399. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7400. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7401. bb_error_msg_and_die("BUG: nesting underflow");
  7402. remove_nested_vars();
  7403. }
  7404. #if ENABLE_HUSH_FUNCTIONS
  7405. static struct function **find_function_slot(const char *name)
  7406. {
  7407. struct function *funcp;
  7408. struct function **funcpp = &G.top_func;
  7409. while ((funcp = *funcpp) != NULL) {
  7410. if (strcmp(name, funcp->name) == 0) {
  7411. debug_printf_exec("found function '%s'\n", name);
  7412. break;
  7413. }
  7414. funcpp = &funcp->next;
  7415. }
  7416. return funcpp;
  7417. }
  7418. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7419. {
  7420. const struct function *funcp = *find_function_slot(name);
  7421. return funcp;
  7422. }
  7423. /* Note: takes ownership on name ptr */
  7424. static struct function *new_function(char *name)
  7425. {
  7426. struct function **funcpp = find_function_slot(name);
  7427. struct function *funcp = *funcpp;
  7428. if (funcp != NULL) {
  7429. struct command *cmd = funcp->parent_cmd;
  7430. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7431. if (!cmd) {
  7432. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7433. free(funcp->name);
  7434. /* Note: if !funcp->body, do not free body_as_string!
  7435. * This is a special case of "-F name body" function:
  7436. * body_as_string was not malloced! */
  7437. if (funcp->body) {
  7438. free_pipe_list(funcp->body);
  7439. # if !BB_MMU
  7440. free(funcp->body_as_string);
  7441. # endif
  7442. }
  7443. } else {
  7444. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7445. cmd->argv[0] = funcp->name;
  7446. cmd->group = funcp->body;
  7447. # if !BB_MMU
  7448. cmd->group_as_string = funcp->body_as_string;
  7449. # endif
  7450. }
  7451. } else {
  7452. debug_printf_exec("remembering new function '%s'\n", name);
  7453. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7454. /*funcp->next = NULL;*/
  7455. }
  7456. funcp->name = name;
  7457. return funcp;
  7458. }
  7459. # if ENABLE_HUSH_UNSET
  7460. static void unset_func(const char *name)
  7461. {
  7462. struct function **funcpp = find_function_slot(name);
  7463. struct function *funcp = *funcpp;
  7464. if (funcp != NULL) {
  7465. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7466. *funcpp = funcp->next;
  7467. /* funcp is unlinked now, deleting it.
  7468. * Note: if !funcp->body, the function was created by
  7469. * "-F name body", do not free ->body_as_string
  7470. * and ->name as they were not malloced. */
  7471. if (funcp->body) {
  7472. free_pipe_list(funcp->body);
  7473. free(funcp->name);
  7474. # if !BB_MMU
  7475. free(funcp->body_as_string);
  7476. # endif
  7477. }
  7478. free(funcp);
  7479. }
  7480. }
  7481. # endif
  7482. # if BB_MMU
  7483. #define exec_function(to_free, funcp, argv) \
  7484. exec_function(funcp, argv)
  7485. # endif
  7486. static void exec_function(char ***to_free,
  7487. const struct function *funcp,
  7488. char **argv) NORETURN;
  7489. static void exec_function(char ***to_free,
  7490. const struct function *funcp,
  7491. char **argv)
  7492. {
  7493. # if BB_MMU
  7494. int n;
  7495. argv[0] = G.global_argv[0];
  7496. G.global_argv = argv;
  7497. G.global_argc = n = 1 + string_array_len(argv + 1);
  7498. // Example when we are here: "cmd | func"
  7499. // func will run with saved-redirect fds open.
  7500. // $ f() { echo /proc/self/fd/*; }
  7501. // $ true | f
  7502. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7503. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7504. // Same in script:
  7505. // $ . ./SCRIPT
  7506. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7507. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7508. // They are CLOEXEC so external programs won't see them, but
  7509. // for "more correctness" we might want to close those extra fds here:
  7510. //? close_saved_fds_and_FILE_fds();
  7511. /* "we are in a function, ok to use return" */
  7512. G_flag_return_in_progress = -1;
  7513. enter_var_nest_level();
  7514. IF_HUSH_LOCAL(G.func_nest_level++;)
  7515. /* On MMU, funcp->body is always non-NULL */
  7516. n = run_list(funcp->body);
  7517. fflush_all();
  7518. _exit(n);
  7519. # else
  7520. //? close_saved_fds_and_FILE_fds();
  7521. //TODO: check whether "true | func_with_return" works
  7522. re_execute_shell(to_free,
  7523. funcp->body_as_string,
  7524. G.global_argv[0],
  7525. argv + 1,
  7526. NULL);
  7527. # endif
  7528. }
  7529. static int run_function(const struct function *funcp, char **argv)
  7530. {
  7531. int rc;
  7532. save_arg_t sv;
  7533. smallint sv_flg;
  7534. save_and_replace_G_args(&sv, argv);
  7535. /* "We are in function, ok to use return" */
  7536. sv_flg = G_flag_return_in_progress;
  7537. G_flag_return_in_progress = -1;
  7538. /* Make "local" variables properly shadow previous ones */
  7539. IF_HUSH_LOCAL(enter_var_nest_level();)
  7540. IF_HUSH_LOCAL(G.func_nest_level++;)
  7541. /* On MMU, funcp->body is always non-NULL */
  7542. # if !BB_MMU
  7543. if (!funcp->body) {
  7544. /* Function defined by -F */
  7545. parse_and_run_string(funcp->body_as_string);
  7546. rc = G.last_exitcode;
  7547. } else
  7548. # endif
  7549. {
  7550. rc = run_list(funcp->body);
  7551. }
  7552. IF_HUSH_LOCAL(G.func_nest_level--;)
  7553. IF_HUSH_LOCAL(leave_var_nest_level();)
  7554. G_flag_return_in_progress = sv_flg;
  7555. restore_G_args(&sv, argv);
  7556. return rc;
  7557. }
  7558. #endif /* ENABLE_HUSH_FUNCTIONS */
  7559. #if BB_MMU
  7560. #define exec_builtin(to_free, x, argv) \
  7561. exec_builtin(x, argv)
  7562. #else
  7563. #define exec_builtin(to_free, x, argv) \
  7564. exec_builtin(to_free, argv)
  7565. #endif
  7566. static void exec_builtin(char ***to_free,
  7567. const struct built_in_command *x,
  7568. char **argv) NORETURN;
  7569. static void exec_builtin(char ***to_free,
  7570. const struct built_in_command *x,
  7571. char **argv)
  7572. {
  7573. #if BB_MMU
  7574. int rcode;
  7575. fflush_all();
  7576. //? close_saved_fds_and_FILE_fds();
  7577. rcode = x->b_function(argv);
  7578. fflush_all();
  7579. _exit(rcode);
  7580. #else
  7581. fflush_all();
  7582. /* On NOMMU, we must never block!
  7583. * Example: { sleep 99 | read line; } & echo Ok
  7584. */
  7585. re_execute_shell(to_free,
  7586. argv[0],
  7587. G.global_argv[0],
  7588. G.global_argv + 1,
  7589. argv);
  7590. #endif
  7591. }
  7592. static void execvp_or_die(char **argv) NORETURN;
  7593. static void execvp_or_die(char **argv)
  7594. {
  7595. int e;
  7596. debug_printf_exec("execing '%s'\n", argv[0]);
  7597. /* Don't propagate SIG_IGN to the child */
  7598. if (SPECIAL_JOBSTOP_SIGS != 0)
  7599. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7600. execvp(argv[0], argv);
  7601. e = 2;
  7602. if (errno == EACCES) e = 126;
  7603. if (errno == ENOENT) e = 127;
  7604. bb_perror_msg("can't execute '%s'", argv[0]);
  7605. _exit(e);
  7606. }
  7607. #if ENABLE_HUSH_MODE_X
  7608. static void x_mode_print_optionally_squoted(const char *str)
  7609. {
  7610. unsigned len;
  7611. const char *cp;
  7612. cp = str;
  7613. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7614. /* test a char with: bash -c 'set -x; echo "CH"' */
  7615. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7616. " " "\001\002\003\004\005\006\007"
  7617. "\010\011\012\013\014\015\016\017"
  7618. "\020\021\022\023\024\025\026\027"
  7619. "\030\031\032\033\034\035\036\037"
  7620. )
  7621. ] == '\0'
  7622. ) {
  7623. /* string has no special chars */
  7624. x_mode_addstr(str);
  7625. return;
  7626. }
  7627. cp = str;
  7628. for (;;) {
  7629. /* print '....' up to EOL or first squote */
  7630. len = (int)(strchrnul(cp, '\'') - cp);
  7631. if (len != 0) {
  7632. x_mode_addchr('\'');
  7633. x_mode_addblock(cp, len);
  7634. x_mode_addchr('\'');
  7635. cp += len;
  7636. }
  7637. if (*cp == '\0')
  7638. break;
  7639. /* string contains squote(s), print them as \' */
  7640. x_mode_addchr('\\');
  7641. x_mode_addchr('\'');
  7642. cp++;
  7643. }
  7644. }
  7645. static void dump_cmd_in_x_mode(char **argv)
  7646. {
  7647. if (G_x_mode && argv) {
  7648. unsigned n;
  7649. /* "+[+++...][ cmd...]\n\0" */
  7650. x_mode_prefix();
  7651. n = 0;
  7652. while (argv[n]) {
  7653. x_mode_addchr(' ');
  7654. if (argv[n][0] == '\0') {
  7655. x_mode_addchr('\'');
  7656. x_mode_addchr('\'');
  7657. } else {
  7658. x_mode_print_optionally_squoted(argv[n]);
  7659. }
  7660. n++;
  7661. }
  7662. x_mode_flush();
  7663. }
  7664. }
  7665. #else
  7666. # define dump_cmd_in_x_mode(argv) ((void)0)
  7667. #endif
  7668. #if ENABLE_HUSH_COMMAND
  7669. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7670. {
  7671. char *to_free;
  7672. if (!opt_vV)
  7673. return;
  7674. to_free = NULL;
  7675. if (!explanation) {
  7676. char *path = getenv("PATH");
  7677. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7678. if (!explanation)
  7679. _exit(1); /* PROG was not found */
  7680. if (opt_vV != 'V')
  7681. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7682. }
  7683. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7684. free(to_free);
  7685. fflush_all();
  7686. _exit(0);
  7687. }
  7688. #else
  7689. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7690. #endif
  7691. #if BB_MMU
  7692. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7693. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7694. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7695. pseudo_exec(command, argv_expanded)
  7696. #endif
  7697. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7698. * Never returns.
  7699. * Don't exit() here. If you don't exec, use _exit instead.
  7700. * The at_exit handlers apparently confuse the calling process,
  7701. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7702. */
  7703. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7704. char **argv, int assignment_cnt,
  7705. char **argv_expanded) NORETURN;
  7706. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7707. char **argv, int assignment_cnt,
  7708. char **argv_expanded)
  7709. {
  7710. const struct built_in_command *x;
  7711. struct variable **sv_shadowed;
  7712. char **new_env;
  7713. IF_HUSH_COMMAND(char opt_vV = 0;)
  7714. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7715. new_env = expand_assignments(argv, assignment_cnt);
  7716. dump_cmd_in_x_mode(new_env);
  7717. if (!argv[assignment_cnt]) {
  7718. /* Case when we are here: ... | var=val | ...
  7719. * (note that we do not exit early, i.e., do not optimize out
  7720. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7721. */
  7722. free_strings(new_env);
  7723. _exit(EXIT_SUCCESS);
  7724. }
  7725. sv_shadowed = G.shadowed_vars_pp;
  7726. #if BB_MMU
  7727. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7728. #else
  7729. G.shadowed_vars_pp = &nommu_save->old_vars;
  7730. G.var_nest_level++;
  7731. #endif
  7732. set_vars_and_save_old(new_env);
  7733. G.shadowed_vars_pp = sv_shadowed;
  7734. if (argv_expanded) {
  7735. argv = argv_expanded;
  7736. } else {
  7737. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7738. #if !BB_MMU
  7739. nommu_save->argv = argv;
  7740. #endif
  7741. }
  7742. dump_cmd_in_x_mode(argv);
  7743. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7744. if (strchr(argv[0], '/') != NULL)
  7745. goto skip;
  7746. #endif
  7747. #if ENABLE_HUSH_FUNCTIONS
  7748. /* Check if the command matches any functions (this goes before bltins) */
  7749. funcp = find_function(argv[0]);
  7750. if (funcp)
  7751. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7752. #endif
  7753. #if ENABLE_HUSH_COMMAND
  7754. /* "command BAR": run BAR without looking it up among functions
  7755. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7756. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7757. */
  7758. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7759. char *p;
  7760. argv++;
  7761. p = *argv;
  7762. if (p[0] != '-' || !p[1])
  7763. continue; /* bash allows "command command command [-OPT] BAR" */
  7764. for (;;) {
  7765. p++;
  7766. switch (*p) {
  7767. case '\0':
  7768. argv++;
  7769. p = *argv;
  7770. if (p[0] != '-' || !p[1])
  7771. goto after_opts;
  7772. continue; /* next arg is also -opts, process it too */
  7773. case 'v':
  7774. case 'V':
  7775. opt_vV = *p;
  7776. continue;
  7777. default:
  7778. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7779. }
  7780. }
  7781. }
  7782. after_opts:
  7783. # if ENABLE_HUSH_FUNCTIONS
  7784. if (opt_vV && find_function(argv[0]))
  7785. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7786. # endif
  7787. #endif
  7788. /* Check if the command matches any of the builtins.
  7789. * Depending on context, this might be redundant. But it's
  7790. * easier to waste a few CPU cycles than it is to figure out
  7791. * if this is one of those cases.
  7792. */
  7793. /* Why "BB_MMU ? :" difference in logic? -
  7794. * On NOMMU, it is more expensive to re-execute shell
  7795. * just in order to run echo or test builtin.
  7796. * It's better to skip it here and run corresponding
  7797. * non-builtin later. */
  7798. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7799. if (x) {
  7800. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7801. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7802. }
  7803. #if ENABLE_FEATURE_SH_STANDALONE
  7804. /* Check if the command matches any busybox applets */
  7805. {
  7806. int a = find_applet_by_name(argv[0]);
  7807. if (a >= 0) {
  7808. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7809. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7810. if (APPLET_IS_NOEXEC(a)) {
  7811. /* Do not leak open fds from opened script files etc.
  7812. * Testcase: interactive "ls -l /proc/self/fd"
  7813. * should not show tty fd open.
  7814. */
  7815. close_saved_fds_and_FILE_fds();
  7816. //FIXME: should also close saved redir fds
  7817. //This casuses test failures in
  7818. //redir_children_should_not_see_saved_fd_2.tests
  7819. //redir_children_should_not_see_saved_fd_3.tests
  7820. //if you replace "busybox find" with just "find" in them
  7821. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7822. switch_off_special_sigs(G.special_sig_mask);
  7823. debug_printf_exec("running applet '%s'\n", argv[0]);
  7824. run_noexec_applet_and_exit(a, argv[0], argv);
  7825. }
  7826. # endif
  7827. /* Re-exec ourselves */
  7828. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7829. /* Don't propagate SIG_IGN to the child */
  7830. if (SPECIAL_JOBSTOP_SIGS != 0)
  7831. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7832. execv(bb_busybox_exec_path, argv);
  7833. /* If they called chroot or otherwise made the binary no longer
  7834. * executable, fall through */
  7835. }
  7836. }
  7837. #endif
  7838. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7839. skip:
  7840. #endif
  7841. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7842. execvp_or_die(argv);
  7843. }
  7844. /* Called after [v]fork() in run_pipe
  7845. */
  7846. static void pseudo_exec(nommu_save_t *nommu_save,
  7847. struct command *command,
  7848. char **argv_expanded) NORETURN;
  7849. static void pseudo_exec(nommu_save_t *nommu_save,
  7850. struct command *command,
  7851. char **argv_expanded)
  7852. {
  7853. #if ENABLE_HUSH_FUNCTIONS
  7854. if (command->cmd_type == CMD_FUNCDEF) {
  7855. /* Ignore funcdefs in pipes:
  7856. * true | f() { cmd }
  7857. */
  7858. _exit(0);
  7859. }
  7860. #endif
  7861. if (command->argv) {
  7862. pseudo_exec_argv(nommu_save, command->argv,
  7863. command->assignment_cnt, argv_expanded);
  7864. }
  7865. if (command->group) {
  7866. /* Cases when we are here:
  7867. * ( list )
  7868. * { list } &
  7869. * ... | ( list ) | ...
  7870. * ... | { list } | ...
  7871. */
  7872. #if BB_MMU
  7873. int rcode;
  7874. debug_printf_exec("pseudo_exec: run_list\n");
  7875. reset_traps_to_defaults();
  7876. rcode = run_list(command->group);
  7877. /* OK to leak memory by not calling free_pipe_list,
  7878. * since this process is about to exit */
  7879. _exit(rcode);
  7880. #else
  7881. re_execute_shell(&nommu_save->argv_from_re_execing,
  7882. command->group_as_string,
  7883. G.global_argv[0],
  7884. G.global_argv + 1,
  7885. NULL);
  7886. #endif
  7887. }
  7888. /* Case when we are here: ... | >file */
  7889. debug_printf_exec("pseudo_exec'ed null command\n");
  7890. _exit(EXIT_SUCCESS);
  7891. }
  7892. #if ENABLE_HUSH_JOB
  7893. static const char *get_cmdtext(struct pipe *pi)
  7894. {
  7895. char **argv;
  7896. char *p;
  7897. int len;
  7898. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7899. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7900. * On subsequent bg argv is trashed, but we won't use it */
  7901. if (pi->cmdtext)
  7902. return pi->cmdtext;
  7903. argv = pi->cmds[0].argv;
  7904. if (!argv) {
  7905. pi->cmdtext = xzalloc(1);
  7906. return pi->cmdtext;
  7907. }
  7908. len = 0;
  7909. do {
  7910. len += strlen(*argv) + 1;
  7911. } while (*++argv);
  7912. p = xmalloc(len);
  7913. pi->cmdtext = p;
  7914. argv = pi->cmds[0].argv;
  7915. do {
  7916. p = stpcpy(p, *argv);
  7917. *p++ = ' ';
  7918. } while (*++argv);
  7919. p[-1] = '\0';
  7920. return pi->cmdtext;
  7921. }
  7922. static void remove_job_from_table(struct pipe *pi)
  7923. {
  7924. struct pipe *prev_pipe;
  7925. if (pi == G.job_list) {
  7926. G.job_list = pi->next;
  7927. } else {
  7928. prev_pipe = G.job_list;
  7929. while (prev_pipe->next != pi)
  7930. prev_pipe = prev_pipe->next;
  7931. prev_pipe->next = pi->next;
  7932. }
  7933. G.last_jobid = 0;
  7934. if (G.job_list)
  7935. G.last_jobid = G.job_list->jobid;
  7936. }
  7937. static void delete_finished_job(struct pipe *pi)
  7938. {
  7939. remove_job_from_table(pi);
  7940. free_pipe(pi);
  7941. }
  7942. static void clean_up_last_dead_job(void)
  7943. {
  7944. if (G.job_list && !G.job_list->alive_cmds)
  7945. delete_finished_job(G.job_list);
  7946. }
  7947. static void insert_job_into_table(struct pipe *pi)
  7948. {
  7949. struct pipe *job, **jobp;
  7950. int i;
  7951. clean_up_last_dead_job();
  7952. /* Find the end of the list, and find next job ID to use */
  7953. i = 0;
  7954. jobp = &G.job_list;
  7955. while ((job = *jobp) != NULL) {
  7956. if (job->jobid > i)
  7957. i = job->jobid;
  7958. jobp = &job->next;
  7959. }
  7960. pi->jobid = i + 1;
  7961. /* Create a new job struct at the end */
  7962. job = *jobp = xmemdup(pi, sizeof(*pi));
  7963. job->next = NULL;
  7964. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7965. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7966. for (i = 0; i < pi->num_cmds; i++) {
  7967. job->cmds[i].pid = pi->cmds[i].pid;
  7968. /* all other fields are not used and stay zero */
  7969. }
  7970. job->cmdtext = xstrdup(get_cmdtext(pi));
  7971. if (G_interactive_fd)
  7972. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  7973. G.last_jobid = job->jobid;
  7974. }
  7975. #endif /* JOB */
  7976. static int job_exited_or_stopped(struct pipe *pi)
  7977. {
  7978. int rcode, i;
  7979. if (pi->alive_cmds != pi->stopped_cmds)
  7980. return -1;
  7981. /* All processes in fg pipe have exited or stopped */
  7982. rcode = 0;
  7983. i = pi->num_cmds;
  7984. while (--i >= 0) {
  7985. rcode = pi->cmds[i].cmd_exitcode;
  7986. /* usually last process gives overall exitstatus,
  7987. * but with "set -o pipefail", last *failed* process does */
  7988. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  7989. break;
  7990. }
  7991. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7992. return rcode;
  7993. }
  7994. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  7995. {
  7996. #if ENABLE_HUSH_JOB
  7997. struct pipe *pi;
  7998. #endif
  7999. int i, dead;
  8000. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8001. #if DEBUG_JOBS
  8002. if (WIFSTOPPED(status))
  8003. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8004. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8005. if (WIFSIGNALED(status))
  8006. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8007. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8008. if (WIFEXITED(status))
  8009. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8010. childpid, WEXITSTATUS(status));
  8011. #endif
  8012. /* Were we asked to wait for a fg pipe? */
  8013. if (fg_pipe) {
  8014. i = fg_pipe->num_cmds;
  8015. while (--i >= 0) {
  8016. int rcode;
  8017. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8018. if (fg_pipe->cmds[i].pid != childpid)
  8019. continue;
  8020. if (dead) {
  8021. int ex;
  8022. fg_pipe->cmds[i].pid = 0;
  8023. fg_pipe->alive_cmds--;
  8024. ex = WEXITSTATUS(status);
  8025. /* bash prints killer signal's name for *last*
  8026. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8027. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8028. */
  8029. if (WIFSIGNALED(status)) {
  8030. int sig = WTERMSIG(status);
  8031. if (i == fg_pipe->num_cmds-1)
  8032. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8033. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8034. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8035. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8036. * Maybe we need to use sig | 128? */
  8037. ex = sig + 128;
  8038. }
  8039. fg_pipe->cmds[i].cmd_exitcode = ex;
  8040. } else {
  8041. fg_pipe->stopped_cmds++;
  8042. }
  8043. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8044. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8045. rcode = job_exited_or_stopped(fg_pipe);
  8046. if (rcode >= 0) {
  8047. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8048. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8049. * and "killall -STOP cat" */
  8050. if (G_interactive_fd) {
  8051. #if ENABLE_HUSH_JOB
  8052. if (fg_pipe->alive_cmds != 0)
  8053. insert_job_into_table(fg_pipe);
  8054. #endif
  8055. return rcode;
  8056. }
  8057. if (fg_pipe->alive_cmds == 0)
  8058. return rcode;
  8059. }
  8060. /* There are still running processes in the fg_pipe */
  8061. return -1;
  8062. }
  8063. /* It wasn't in fg_pipe, look for process in bg pipes */
  8064. }
  8065. #if ENABLE_HUSH_JOB
  8066. /* We were asked to wait for bg or orphaned children */
  8067. /* No need to remember exitcode in this case */
  8068. for (pi = G.job_list; pi; pi = pi->next) {
  8069. for (i = 0; i < pi->num_cmds; i++) {
  8070. if (pi->cmds[i].pid == childpid)
  8071. goto found_pi_and_prognum;
  8072. }
  8073. }
  8074. /* Happens when shell is used as init process (init=/bin/sh) */
  8075. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8076. return -1; /* this wasn't a process from fg_pipe */
  8077. found_pi_and_prognum:
  8078. if (dead) {
  8079. /* child exited */
  8080. int rcode = WEXITSTATUS(status);
  8081. if (WIFSIGNALED(status))
  8082. rcode = 128 + WTERMSIG(status);
  8083. pi->cmds[i].cmd_exitcode = rcode;
  8084. if (G.last_bg_pid == pi->cmds[i].pid)
  8085. G.last_bg_pid_exitcode = rcode;
  8086. pi->cmds[i].pid = 0;
  8087. pi->alive_cmds--;
  8088. if (!pi->alive_cmds) {
  8089. #if ENABLE_HUSH_BASH_COMPAT
  8090. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8091. #endif
  8092. if (G_interactive_fd) {
  8093. printf(JOB_STATUS_FORMAT, pi->jobid,
  8094. "Done", pi->cmdtext);
  8095. delete_finished_job(pi);
  8096. } else {
  8097. /*
  8098. * bash deletes finished jobs from job table only in interactive mode,
  8099. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8100. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8101. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8102. * We only retain one "dead" job, if it's the single job on the list.
  8103. * This covers most of real-world scenarios where this is useful.
  8104. */
  8105. if (pi != G.job_list)
  8106. delete_finished_job(pi);
  8107. }
  8108. }
  8109. } else {
  8110. /* child stopped */
  8111. pi->stopped_cmds++;
  8112. }
  8113. #endif
  8114. return -1; /* this wasn't a process from fg_pipe */
  8115. }
  8116. /* Check to see if any processes have exited -- if they have,
  8117. * figure out why and see if a job has completed.
  8118. *
  8119. * If non-NULL fg_pipe: wait for its completion or stop.
  8120. * Return its exitcode or zero if stopped.
  8121. *
  8122. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8123. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8124. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8125. * or 0 if no children changed status.
  8126. *
  8127. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8128. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8129. * or 0 if no children changed status.
  8130. */
  8131. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8132. {
  8133. int attributes;
  8134. int status;
  8135. int rcode = 0;
  8136. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8137. attributes = WUNTRACED;
  8138. if (fg_pipe == NULL)
  8139. attributes |= WNOHANG;
  8140. errno = 0;
  8141. #if ENABLE_HUSH_FAST
  8142. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8143. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8144. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8145. /* There was neither fork nor SIGCHLD since last waitpid */
  8146. /* Avoid doing waitpid syscall if possible */
  8147. if (!G.we_have_children) {
  8148. errno = ECHILD;
  8149. return -1;
  8150. }
  8151. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8152. /* We have children, but they did not exit
  8153. * or stop yet (we saw no SIGCHLD) */
  8154. return 0;
  8155. }
  8156. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8157. }
  8158. #endif
  8159. /* Do we do this right?
  8160. * bash-3.00# sleep 20 | false
  8161. * <ctrl-Z pressed>
  8162. * [3]+ Stopped sleep 20 | false
  8163. * bash-3.00# echo $?
  8164. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8165. * [hush 1.14.0: yes we do it right]
  8166. */
  8167. while (1) {
  8168. pid_t childpid;
  8169. #if ENABLE_HUSH_FAST
  8170. int i;
  8171. i = G.count_SIGCHLD;
  8172. #endif
  8173. childpid = waitpid(-1, &status, attributes);
  8174. if (childpid <= 0) {
  8175. if (childpid && errno != ECHILD)
  8176. bb_perror_msg("waitpid");
  8177. #if ENABLE_HUSH_FAST
  8178. else { /* Until next SIGCHLD, waitpid's are useless */
  8179. G.we_have_children = (childpid == 0);
  8180. G.handled_SIGCHLD = i;
  8181. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8182. }
  8183. #endif
  8184. /* ECHILD (no children), or 0 (no change in children status) */
  8185. rcode = childpid;
  8186. break;
  8187. }
  8188. rcode = process_wait_result(fg_pipe, childpid, status);
  8189. if (rcode >= 0) {
  8190. /* fg_pipe exited or stopped */
  8191. break;
  8192. }
  8193. if (childpid == waitfor_pid) { /* "wait PID" */
  8194. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8195. rcode = WEXITSTATUS(status);
  8196. if (WIFSIGNALED(status))
  8197. rcode = 128 + WTERMSIG(status);
  8198. if (WIFSTOPPED(status))
  8199. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8200. rcode = 128 + WSTOPSIG(status);
  8201. rcode++;
  8202. break; /* "wait PID" called us, give it exitcode+1 */
  8203. }
  8204. #if ENABLE_HUSH_BASH_COMPAT
  8205. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8206. && G.dead_job_exitcode >= 0 /* some job did finish */
  8207. ) {
  8208. debug_printf_exec("waitfor_pid:-1\n");
  8209. rcode = G.dead_job_exitcode + 1;
  8210. break;
  8211. }
  8212. #endif
  8213. /* This wasn't one of our processes, or */
  8214. /* fg_pipe still has running processes, do waitpid again */
  8215. } /* while (waitpid succeeds)... */
  8216. return rcode;
  8217. }
  8218. #if ENABLE_HUSH_JOB
  8219. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8220. {
  8221. pid_t p;
  8222. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8223. if (G_saved_tty_pgrp) {
  8224. /* Job finished, move the shell to the foreground */
  8225. p = getpgrp(); /* our process group id */
  8226. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8227. tcsetpgrp(G_interactive_fd, p);
  8228. }
  8229. return rcode;
  8230. }
  8231. #endif
  8232. /* Start all the jobs, but don't wait for anything to finish.
  8233. * See checkjobs().
  8234. *
  8235. * Return code is normally -1, when the caller has to wait for children
  8236. * to finish to determine the exit status of the pipe. If the pipe
  8237. * is a simple builtin command, however, the action is done by the
  8238. * time run_pipe returns, and the exit code is provided as the
  8239. * return value.
  8240. *
  8241. * Returns -1 only if started some children. IOW: we have to
  8242. * mask out retvals of builtins etc with 0xff!
  8243. *
  8244. * The only case when we do not need to [v]fork is when the pipe
  8245. * is single, non-backgrounded, non-subshell command. Examples:
  8246. * cmd ; ... { list } ; ...
  8247. * cmd && ... { list } && ...
  8248. * cmd || ... { list } || ...
  8249. * If it is, then we can run cmd as a builtin, NOFORK,
  8250. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8251. * with run_list. If it isn't one of these, we fork and exec cmd.
  8252. *
  8253. * Cases when we must fork:
  8254. * non-single: cmd | cmd
  8255. * backgrounded: cmd & { list } &
  8256. * subshell: ( list ) [&]
  8257. */
  8258. #if !ENABLE_HUSH_MODE_X
  8259. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8260. redirect_and_varexp_helper(command, sqp)
  8261. #endif
  8262. static int redirect_and_varexp_helper(
  8263. struct command *command,
  8264. struct squirrel **sqp,
  8265. char **argv_expanded)
  8266. {
  8267. /* Assignments occur before redirects. Try:
  8268. * a=`sleep 1` sleep 2 3>/qwe/rty
  8269. */
  8270. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8271. dump_cmd_in_x_mode(new_env);
  8272. dump_cmd_in_x_mode(argv_expanded);
  8273. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8274. set_vars_and_save_old(new_env);
  8275. return setup_redirects(command, sqp);
  8276. }
  8277. static NOINLINE int run_pipe(struct pipe *pi)
  8278. {
  8279. static const char *const null_ptr = NULL;
  8280. int cmd_no;
  8281. int next_infd;
  8282. struct command *command;
  8283. char **argv_expanded;
  8284. char **argv;
  8285. struct squirrel *squirrel = NULL;
  8286. int rcode;
  8287. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8288. debug_enter();
  8289. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8290. * Result should be 3 lines: q w e, qwe, q w e
  8291. */
  8292. if (G.ifs_whitespace != G.ifs)
  8293. free(G.ifs_whitespace);
  8294. G.ifs = get_local_var_value("IFS");
  8295. if (G.ifs) {
  8296. char *p;
  8297. G.ifs_whitespace = (char*)G.ifs;
  8298. p = skip_whitespace(G.ifs);
  8299. if (*p) {
  8300. /* Not all $IFS is whitespace */
  8301. char *d;
  8302. int len = p - G.ifs;
  8303. p = skip_non_whitespace(p);
  8304. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8305. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8306. while (*p) {
  8307. if (isspace(*p))
  8308. *d++ = *p;
  8309. p++;
  8310. }
  8311. *d = '\0';
  8312. }
  8313. } else {
  8314. G.ifs = defifs;
  8315. G.ifs_whitespace = (char*)G.ifs;
  8316. }
  8317. IF_HUSH_JOB(pi->pgrp = -1;)
  8318. pi->stopped_cmds = 0;
  8319. command = &pi->cmds[0];
  8320. argv_expanded = NULL;
  8321. if (pi->num_cmds != 1
  8322. || pi->followup == PIPE_BG
  8323. || command->cmd_type == CMD_SUBSHELL
  8324. ) {
  8325. goto must_fork;
  8326. }
  8327. pi->alive_cmds = 1;
  8328. debug_printf_exec(": group:%p argv:'%s'\n",
  8329. command->group, command->argv ? command->argv[0] : "NONE");
  8330. if (command->group) {
  8331. #if ENABLE_HUSH_FUNCTIONS
  8332. if (command->cmd_type == CMD_FUNCDEF) {
  8333. /* "executing" func () { list } */
  8334. struct function *funcp;
  8335. funcp = new_function(command->argv[0]);
  8336. /* funcp->name is already set to argv[0] */
  8337. funcp->body = command->group;
  8338. # if !BB_MMU
  8339. funcp->body_as_string = command->group_as_string;
  8340. command->group_as_string = NULL;
  8341. # endif
  8342. command->group = NULL;
  8343. command->argv[0] = NULL;
  8344. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8345. funcp->parent_cmd = command;
  8346. command->child_func = funcp;
  8347. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8348. debug_leave();
  8349. return EXIT_SUCCESS;
  8350. }
  8351. #endif
  8352. /* { list } */
  8353. debug_printf_exec("non-subshell group\n");
  8354. rcode = 1; /* exitcode if redir failed */
  8355. if (setup_redirects(command, &squirrel) == 0) {
  8356. debug_printf_exec(": run_list\n");
  8357. //FIXME: we need to pass squirrel down into run_list()
  8358. //for SH_STANDALONE case, or else this construct:
  8359. // { find /proc/self/fd; true; } >FILE; cmd2
  8360. //has no way of closing saved fd#1 for "find",
  8361. //and in SH_STANDALONE mode, "find" is not execed,
  8362. //therefore CLOEXEC on saved fd does not help.
  8363. rcode = run_list(command->group) & 0xff;
  8364. }
  8365. restore_redirects(squirrel);
  8366. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8367. debug_leave();
  8368. debug_printf_exec("run_pipe: return %d\n", rcode);
  8369. return rcode;
  8370. }
  8371. argv = command->argv ? command->argv : (char **) &null_ptr;
  8372. {
  8373. const struct built_in_command *x;
  8374. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8375. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8376. struct variable **sv_shadowed;
  8377. struct variable *old_vars;
  8378. #if ENABLE_HUSH_LINENO_VAR
  8379. if (G.lineno_var)
  8380. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  8381. #endif
  8382. if (argv[command->assignment_cnt] == NULL) {
  8383. /* Assignments, but no command.
  8384. * Ensure redirects take effect (that is, create files).
  8385. * Try "a=t >file"
  8386. */
  8387. unsigned i;
  8388. G.expand_exitcode = 0;
  8389. only_assignments:
  8390. rcode = setup_redirects(command, &squirrel);
  8391. restore_redirects(squirrel);
  8392. /* Set shell variables */
  8393. i = 0;
  8394. while (i < command->assignment_cnt) {
  8395. char *p = expand_string_to_string(argv[i],
  8396. EXP_FLAG_ESC_GLOB_CHARS,
  8397. /*unbackslash:*/ 1
  8398. );
  8399. #if ENABLE_HUSH_MODE_X
  8400. if (G_x_mode) {
  8401. char *eq;
  8402. if (i == 0)
  8403. x_mode_prefix();
  8404. x_mode_addchr(' ');
  8405. eq = strchrnul(p, '=');
  8406. if (*eq) eq++;
  8407. x_mode_addblock(p, (eq - p));
  8408. x_mode_print_optionally_squoted(eq);
  8409. x_mode_flush();
  8410. }
  8411. #endif
  8412. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8413. if (set_local_var(p, /*flag:*/ 0)) {
  8414. /* assignment to readonly var / putenv error? */
  8415. rcode = 1;
  8416. }
  8417. i++;
  8418. }
  8419. /* Redirect error sets $? to 1. Otherwise,
  8420. * if evaluating assignment value set $?, retain it.
  8421. * Else, clear $?:
  8422. * false; q=`exit 2`; echo $? - should print 2
  8423. * false; x=1; echo $? - should print 0
  8424. * Because of the 2nd case, we can't just use G.last_exitcode.
  8425. */
  8426. if (rcode == 0)
  8427. rcode = G.expand_exitcode;
  8428. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8429. debug_leave();
  8430. debug_printf_exec("run_pipe: return %d\n", rcode);
  8431. return rcode;
  8432. }
  8433. /* Expand the rest into (possibly) many strings each */
  8434. #if defined(CMD_SINGLEWORD_NOGLOB)
  8435. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8436. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8437. else
  8438. #endif
  8439. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8440. /* If someone gives us an empty string: `cmd with empty output` */
  8441. if (!argv_expanded[0]) {
  8442. free(argv_expanded);
  8443. /* `false` still has to set exitcode 1 */
  8444. G.expand_exitcode = G.last_exitcode;
  8445. goto only_assignments;
  8446. }
  8447. old_vars = NULL;
  8448. sv_shadowed = G.shadowed_vars_pp;
  8449. /* Check if argv[0] matches any functions (this goes before bltins) */
  8450. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8451. IF_HUSH_FUNCTIONS(x = NULL;)
  8452. IF_HUSH_FUNCTIONS(if (!funcp))
  8453. x = find_builtin(argv_expanded[0]);
  8454. if (x || funcp) {
  8455. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8456. debug_printf("exec with redirects only\n");
  8457. /*
  8458. * Variable assignments are executed, but then "forgotten":
  8459. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8460. * sleeps, but prints nothing.
  8461. */
  8462. enter_var_nest_level();
  8463. G.shadowed_vars_pp = &old_vars;
  8464. rcode = redirect_and_varexp_helper(command,
  8465. /*squirrel:*/ ERR_PTR,
  8466. argv_expanded
  8467. );
  8468. G.shadowed_vars_pp = sv_shadowed;
  8469. /* rcode=1 can be if redir file can't be opened */
  8470. goto clean_up_and_ret1;
  8471. }
  8472. /* Bump var nesting, or this will leak exported $a:
  8473. * a=b true; env | grep ^a=
  8474. */
  8475. enter_var_nest_level();
  8476. /* Collect all variables "shadowed" by helper
  8477. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8478. * into old_vars list:
  8479. */
  8480. G.shadowed_vars_pp = &old_vars;
  8481. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8482. if (rcode == 0) {
  8483. if (!funcp) {
  8484. /* Do not collect *to old_vars list* vars shadowed
  8485. * by e.g. "local VAR" builtin (collect them
  8486. * in the previously nested list instead):
  8487. * don't want them to be restored immediately
  8488. * after "local" completes.
  8489. */
  8490. G.shadowed_vars_pp = sv_shadowed;
  8491. debug_printf_exec(": builtin '%s' '%s'...\n",
  8492. x->b_cmd, argv_expanded[1]);
  8493. fflush_all();
  8494. rcode = x->b_function(argv_expanded) & 0xff;
  8495. fflush_all();
  8496. }
  8497. #if ENABLE_HUSH_FUNCTIONS
  8498. else {
  8499. debug_printf_exec(": function '%s' '%s'...\n",
  8500. funcp->name, argv_expanded[1]);
  8501. rcode = run_function(funcp, argv_expanded) & 0xff;
  8502. /*
  8503. * But do collect *to old_vars list* vars shadowed
  8504. * within function execution. To that end, restore
  8505. * this pointer _after_ function run:
  8506. */
  8507. G.shadowed_vars_pp = sv_shadowed;
  8508. }
  8509. #endif
  8510. }
  8511. } else
  8512. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8513. int n = find_applet_by_name(argv_expanded[0]);
  8514. if (n < 0 || !APPLET_IS_NOFORK(n))
  8515. goto must_fork;
  8516. enter_var_nest_level();
  8517. /* Collect all variables "shadowed" by helper into old_vars list */
  8518. G.shadowed_vars_pp = &old_vars;
  8519. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8520. G.shadowed_vars_pp = sv_shadowed;
  8521. if (rcode == 0) {
  8522. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8523. argv_expanded[0], argv_expanded[1]);
  8524. /*
  8525. * Note: signals (^C) can't interrupt here.
  8526. * We remember them and they will be acted upon
  8527. * after applet returns.
  8528. * This makes applets which can run for a long time
  8529. * and/or wait for user input ineligible for NOFORK:
  8530. * for example, "yes" or "rm" (rm -i waits for input).
  8531. */
  8532. rcode = run_nofork_applet(n, argv_expanded);
  8533. }
  8534. } else
  8535. goto must_fork;
  8536. restore_redirects(squirrel);
  8537. clean_up_and_ret1:
  8538. leave_var_nest_level();
  8539. add_vars(old_vars);
  8540. /*
  8541. * Try "usleep 99999999" + ^C + "echo $?"
  8542. * with FEATURE_SH_NOFORK=y.
  8543. */
  8544. if (!funcp) {
  8545. /* It was builtin or nofork.
  8546. * if this would be a real fork/execed program,
  8547. * it should have died if a fatal sig was received.
  8548. * But OTOH, there was no separate process,
  8549. * the sig was sent to _shell_, not to non-existing
  8550. * child.
  8551. * Let's just handle ^C only, this one is obvious:
  8552. * we aren't ok with exitcode 0 when ^C was pressed
  8553. * during builtin/nofork.
  8554. */
  8555. if (sigismember(&G.pending_set, SIGINT))
  8556. rcode = 128 + SIGINT;
  8557. }
  8558. free(argv_expanded);
  8559. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8560. debug_leave();
  8561. debug_printf_exec("run_pipe return %d\n", rcode);
  8562. return rcode;
  8563. }
  8564. must_fork:
  8565. /* NB: argv_expanded may already be created, and that
  8566. * might include `cmd` runs! Do not rerun it! We *must*
  8567. * use argv_expanded if it's non-NULL */
  8568. /* Going to fork a child per each pipe member */
  8569. pi->alive_cmds = 0;
  8570. next_infd = 0;
  8571. cmd_no = 0;
  8572. while (cmd_no < pi->num_cmds) {
  8573. struct fd_pair pipefds;
  8574. #if !BB_MMU
  8575. int sv_var_nest_level = G.var_nest_level;
  8576. volatile nommu_save_t nommu_save;
  8577. nommu_save.old_vars = NULL;
  8578. nommu_save.argv = NULL;
  8579. nommu_save.argv_from_re_execing = NULL;
  8580. #endif
  8581. command = &pi->cmds[cmd_no];
  8582. cmd_no++;
  8583. if (command->argv) {
  8584. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8585. command->argv[0], command->argv[1]);
  8586. } else {
  8587. debug_printf_exec(": pipe member with no argv\n");
  8588. }
  8589. /* pipes are inserted between pairs of commands */
  8590. pipefds.rd = 0;
  8591. pipefds.wr = 1;
  8592. if (cmd_no < pi->num_cmds)
  8593. xpiped_pair(pipefds);
  8594. #if ENABLE_HUSH_LINENO_VAR
  8595. if (G.lineno_var)
  8596. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  8597. #endif
  8598. command->pid = BB_MMU ? fork() : vfork();
  8599. if (!command->pid) { /* child */
  8600. #if ENABLE_HUSH_JOB
  8601. disable_restore_tty_pgrp_on_exit();
  8602. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8603. /* Every child adds itself to new process group
  8604. * with pgid == pid_of_first_child_in_pipe */
  8605. if (G.run_list_level == 1 && G_interactive_fd) {
  8606. pid_t pgrp;
  8607. pgrp = pi->pgrp;
  8608. if (pgrp < 0) /* true for 1st process only */
  8609. pgrp = getpid();
  8610. if (setpgid(0, pgrp) == 0
  8611. && pi->followup != PIPE_BG
  8612. && G_saved_tty_pgrp /* we have ctty */
  8613. ) {
  8614. /* We do it in *every* child, not just first,
  8615. * to avoid races */
  8616. tcsetpgrp(G_interactive_fd, pgrp);
  8617. }
  8618. }
  8619. #endif
  8620. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8621. /* 1st cmd in backgrounded pipe
  8622. * should have its stdin /dev/null'ed */
  8623. close(0);
  8624. if (open(bb_dev_null, O_RDONLY))
  8625. xopen("/", O_RDONLY);
  8626. } else {
  8627. xmove_fd(next_infd, 0);
  8628. }
  8629. xmove_fd(pipefds.wr, 1);
  8630. if (pipefds.rd > 1)
  8631. close(pipefds.rd);
  8632. /* Like bash, explicit redirects override pipes,
  8633. * and the pipe fd (fd#1) is available for dup'ing:
  8634. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8635. * of cmd1 goes into pipe.
  8636. */
  8637. if (setup_redirects(command, NULL)) {
  8638. /* Happens when redir file can't be opened:
  8639. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8640. * FOO
  8641. * hush: can't open '/qwe/rty': No such file or directory
  8642. * BAZ
  8643. * (echo BAR is not executed, it hits _exit(1) below)
  8644. */
  8645. _exit(1);
  8646. }
  8647. /* Stores to nommu_save list of env vars putenv'ed
  8648. * (NOMMU, on MMU we don't need that) */
  8649. /* cast away volatility... */
  8650. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8651. /* pseudo_exec() does not return */
  8652. }
  8653. /* parent or error */
  8654. #if ENABLE_HUSH_FAST
  8655. G.count_SIGCHLD++;
  8656. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8657. #endif
  8658. enable_restore_tty_pgrp_on_exit();
  8659. #if !BB_MMU
  8660. /* Clean up after vforked child */
  8661. free(nommu_save.argv);
  8662. free(nommu_save.argv_from_re_execing);
  8663. G.var_nest_level = sv_var_nest_level;
  8664. remove_nested_vars();
  8665. add_vars(nommu_save.old_vars);
  8666. #endif
  8667. free(argv_expanded);
  8668. argv_expanded = NULL;
  8669. if (command->pid < 0) { /* [v]fork failed */
  8670. /* Clearly indicate, was it fork or vfork */
  8671. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8672. } else {
  8673. pi->alive_cmds++;
  8674. #if ENABLE_HUSH_JOB
  8675. /* Second and next children need to know pid of first one */
  8676. if (pi->pgrp < 0)
  8677. pi->pgrp = command->pid;
  8678. #endif
  8679. }
  8680. if (cmd_no > 1)
  8681. close(next_infd);
  8682. if (cmd_no < pi->num_cmds)
  8683. close(pipefds.wr);
  8684. /* Pass read (output) pipe end to next iteration */
  8685. next_infd = pipefds.rd;
  8686. }
  8687. if (!pi->alive_cmds) {
  8688. debug_leave();
  8689. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8690. return 1;
  8691. }
  8692. debug_leave();
  8693. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8694. return -1;
  8695. }
  8696. /* NB: called by pseudo_exec, and therefore must not modify any
  8697. * global data until exec/_exit (we can be a child after vfork!) */
  8698. static int run_list(struct pipe *pi)
  8699. {
  8700. #if ENABLE_HUSH_CASE
  8701. char *case_word = NULL;
  8702. #endif
  8703. #if ENABLE_HUSH_LOOPS
  8704. struct pipe *loop_top = NULL;
  8705. char **for_lcur = NULL;
  8706. char **for_list = NULL;
  8707. #endif
  8708. smallint last_followup;
  8709. smalluint rcode;
  8710. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8711. smalluint cond_code = 0;
  8712. #else
  8713. enum { cond_code = 0 };
  8714. #endif
  8715. #if HAS_KEYWORDS
  8716. smallint rword; /* RES_foo */
  8717. smallint last_rword; /* ditto */
  8718. #endif
  8719. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8720. debug_enter();
  8721. #if ENABLE_HUSH_LOOPS
  8722. /* Check syntax for "for" */
  8723. {
  8724. struct pipe *cpipe;
  8725. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8726. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8727. continue;
  8728. /* current word is FOR or IN (BOLD in comments below) */
  8729. if (cpipe->next == NULL) {
  8730. syntax_error("malformed for");
  8731. debug_leave();
  8732. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8733. return 1;
  8734. }
  8735. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8736. if (cpipe->next->res_word == RES_DO)
  8737. continue;
  8738. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8739. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8740. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8741. ) {
  8742. syntax_error("malformed for");
  8743. debug_leave();
  8744. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8745. return 1;
  8746. }
  8747. }
  8748. }
  8749. #endif
  8750. /* Past this point, all code paths should jump to ret: label
  8751. * in order to return, no direct "return" statements please.
  8752. * This helps to ensure that no memory is leaked. */
  8753. #if ENABLE_HUSH_JOB
  8754. G.run_list_level++;
  8755. #endif
  8756. #if HAS_KEYWORDS
  8757. rword = RES_NONE;
  8758. last_rword = RES_XXXX;
  8759. #endif
  8760. last_followup = PIPE_SEQ;
  8761. rcode = G.last_exitcode;
  8762. /* Go through list of pipes, (maybe) executing them. */
  8763. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8764. int r;
  8765. int sv_errexit_depth;
  8766. if (G.flag_SIGINT)
  8767. break;
  8768. if (G_flag_return_in_progress == 1)
  8769. break;
  8770. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8771. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8772. rword, cond_code, last_rword);
  8773. sv_errexit_depth = G.errexit_depth;
  8774. if (
  8775. #if ENABLE_HUSH_IF
  8776. rword == RES_IF || rword == RES_ELIF ||
  8777. #endif
  8778. pi->followup != PIPE_SEQ
  8779. ) {
  8780. G.errexit_depth++;
  8781. }
  8782. #if ENABLE_HUSH_LOOPS
  8783. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8784. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8785. ) {
  8786. /* start of a loop: remember where loop starts */
  8787. loop_top = pi;
  8788. G.depth_of_loop++;
  8789. }
  8790. #endif
  8791. /* Still in the same "if...", "then..." or "do..." branch? */
  8792. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8793. if ((rcode == 0 && last_followup == PIPE_OR)
  8794. || (rcode != 0 && last_followup == PIPE_AND)
  8795. ) {
  8796. /* It is "<true> || CMD" or "<false> && CMD"
  8797. * and we should not execute CMD */
  8798. debug_printf_exec("skipped cmd because of || or &&\n");
  8799. last_followup = pi->followup;
  8800. goto dont_check_jobs_but_continue;
  8801. }
  8802. }
  8803. last_followup = pi->followup;
  8804. IF_HAS_KEYWORDS(last_rword = rword;)
  8805. #if ENABLE_HUSH_IF
  8806. if (cond_code) {
  8807. if (rword == RES_THEN) {
  8808. /* if false; then ... fi has exitcode 0! */
  8809. G.last_exitcode = rcode = EXIT_SUCCESS;
  8810. /* "if <false> THEN cmd": skip cmd */
  8811. continue;
  8812. }
  8813. } else {
  8814. if (rword == RES_ELSE || rword == RES_ELIF) {
  8815. /* "if <true> then ... ELSE/ELIF cmd":
  8816. * skip cmd and all following ones */
  8817. break;
  8818. }
  8819. }
  8820. #endif
  8821. #if ENABLE_HUSH_LOOPS
  8822. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8823. if (!for_lcur) {
  8824. /* first loop through for */
  8825. static const char encoded_dollar_at[] ALIGN1 = {
  8826. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8827. }; /* encoded representation of "$@" */
  8828. static const char *const encoded_dollar_at_argv[] = {
  8829. encoded_dollar_at, NULL
  8830. }; /* argv list with one element: "$@" */
  8831. char **vals;
  8832. G.last_exitcode = rcode = EXIT_SUCCESS;
  8833. vals = (char**)encoded_dollar_at_argv;
  8834. if (pi->next->res_word == RES_IN) {
  8835. /* if no variable values after "in" we skip "for" */
  8836. if (!pi->next->cmds[0].argv) {
  8837. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8838. break;
  8839. }
  8840. vals = pi->next->cmds[0].argv;
  8841. } /* else: "for var; do..." -> assume "$@" list */
  8842. /* create list of variable values */
  8843. debug_print_strings("for_list made from", vals);
  8844. for_list = expand_strvec_to_strvec(vals);
  8845. for_lcur = for_list;
  8846. debug_print_strings("for_list", for_list);
  8847. }
  8848. if (!*for_lcur) {
  8849. /* "for" loop is over, clean up */
  8850. free(for_list);
  8851. for_list = NULL;
  8852. for_lcur = NULL;
  8853. break;
  8854. }
  8855. /* Insert next value from for_lcur */
  8856. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8857. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8858. continue;
  8859. }
  8860. if (rword == RES_IN) {
  8861. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8862. }
  8863. if (rword == RES_DONE) {
  8864. continue; /* "done" has no cmds too */
  8865. }
  8866. #endif
  8867. #if ENABLE_HUSH_CASE
  8868. if (rword == RES_CASE) {
  8869. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8870. case_word = expand_string_to_string(pi->cmds->argv[0],
  8871. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8872. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8873. //unbackslash(case_word);
  8874. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8875. continue;
  8876. }
  8877. if (rword == RES_MATCH) {
  8878. char **argv;
  8879. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8880. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8881. break;
  8882. /* all prev words didn't match, does this one match? */
  8883. argv = pi->cmds->argv;
  8884. while (*argv) {
  8885. char *pattern;
  8886. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8887. pattern = expand_string_to_string(*argv,
  8888. EXP_FLAG_ESC_GLOB_CHARS,
  8889. /*unbackslash:*/ 0
  8890. );
  8891. /* TODO: which FNM_xxx flags to use? */
  8892. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8893. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8894. pattern, case_word, cond_code);
  8895. free(pattern);
  8896. if (cond_code == 0) {
  8897. /* match! we will execute this branch */
  8898. free(case_word);
  8899. case_word = NULL; /* make future "word)" stop */
  8900. break;
  8901. }
  8902. argv++;
  8903. }
  8904. continue;
  8905. }
  8906. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8907. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8908. if (cond_code != 0)
  8909. continue; /* not matched yet, skip this pipe */
  8910. }
  8911. if (rword == RES_ESAC) {
  8912. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8913. if (case_word) {
  8914. /* "case" did not match anything: still set $? (to 0) */
  8915. G.last_exitcode = rcode = EXIT_SUCCESS;
  8916. }
  8917. }
  8918. #endif
  8919. /* Just pressing <enter> in shell should check for jobs.
  8920. * OTOH, in non-interactive shell this is useless
  8921. * and only leads to extra job checks */
  8922. if (pi->num_cmds == 0) {
  8923. if (G_interactive_fd)
  8924. goto check_jobs_and_continue;
  8925. continue;
  8926. }
  8927. /* After analyzing all keywords and conditions, we decided
  8928. * to execute this pipe. NB: have to do checkjobs(NULL)
  8929. * after run_pipe to collect any background children,
  8930. * even if list execution is to be stopped. */
  8931. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8932. #if ENABLE_HUSH_LOOPS
  8933. G.flag_break_continue = 0;
  8934. #endif
  8935. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8936. if (r != -1) {
  8937. /* We ran a builtin, function, or group.
  8938. * rcode is already known
  8939. * and we don't need to wait for anything. */
  8940. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8941. G.last_exitcode = rcode;
  8942. check_and_run_traps();
  8943. #if ENABLE_HUSH_LOOPS
  8944. /* Was it "break" or "continue"? */
  8945. if (G.flag_break_continue) {
  8946. smallint fbc = G.flag_break_continue;
  8947. /* We might fall into outer *loop*,
  8948. * don't want to break it too */
  8949. if (loop_top) {
  8950. G.depth_break_continue--;
  8951. if (G.depth_break_continue == 0)
  8952. G.flag_break_continue = 0;
  8953. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8954. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8955. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8956. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8957. break;
  8958. }
  8959. /* "continue": simulate end of loop */
  8960. rword = RES_DONE;
  8961. continue;
  8962. }
  8963. #endif
  8964. if (G_flag_return_in_progress == 1) {
  8965. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8966. break;
  8967. }
  8968. } else if (pi->followup == PIPE_BG) {
  8969. /* What does bash do with attempts to background builtins? */
  8970. /* even bash 3.2 doesn't do that well with nested bg:
  8971. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8972. * I'm NOT treating inner &'s as jobs */
  8973. #if ENABLE_HUSH_JOB
  8974. if (G.run_list_level == 1)
  8975. insert_job_into_table(pi);
  8976. #endif
  8977. /* Last command's pid goes to $! */
  8978. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  8979. G.last_bg_pid_exitcode = 0;
  8980. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  8981. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  8982. rcode = EXIT_SUCCESS;
  8983. goto check_traps;
  8984. } else {
  8985. #if ENABLE_HUSH_JOB
  8986. if (G.run_list_level == 1 && G_interactive_fd) {
  8987. /* Waits for completion, then fg's main shell */
  8988. rcode = checkjobs_and_fg_shell(pi);
  8989. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  8990. goto check_traps;
  8991. }
  8992. #endif
  8993. /* This one just waits for completion */
  8994. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  8995. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  8996. check_traps:
  8997. G.last_exitcode = rcode;
  8998. check_and_run_traps();
  8999. }
  9000. /* Handle "set -e" */
  9001. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9002. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9003. if (G.errexit_depth == 0)
  9004. hush_exit(rcode);
  9005. }
  9006. G.errexit_depth = sv_errexit_depth;
  9007. /* Analyze how result affects subsequent commands */
  9008. #if ENABLE_HUSH_IF
  9009. if (rword == RES_IF || rword == RES_ELIF)
  9010. cond_code = rcode;
  9011. #endif
  9012. check_jobs_and_continue:
  9013. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9014. dont_check_jobs_but_continue: ;
  9015. #if ENABLE_HUSH_LOOPS
  9016. /* Beware of "while false; true; do ..."! */
  9017. if (pi->next
  9018. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9019. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9020. ) {
  9021. if (rword == RES_WHILE) {
  9022. if (rcode) {
  9023. /* "while false; do...done" - exitcode 0 */
  9024. G.last_exitcode = rcode = EXIT_SUCCESS;
  9025. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9026. break;
  9027. }
  9028. }
  9029. if (rword == RES_UNTIL) {
  9030. if (!rcode) {
  9031. debug_printf_exec(": until expr is true: breaking\n");
  9032. break;
  9033. }
  9034. }
  9035. }
  9036. #endif
  9037. } /* for (pi) */
  9038. #if ENABLE_HUSH_JOB
  9039. G.run_list_level--;
  9040. #endif
  9041. #if ENABLE_HUSH_LOOPS
  9042. if (loop_top)
  9043. G.depth_of_loop--;
  9044. free(for_list);
  9045. #endif
  9046. #if ENABLE_HUSH_CASE
  9047. free(case_word);
  9048. #endif
  9049. debug_leave();
  9050. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9051. return rcode;
  9052. }
  9053. /* Select which version we will use */
  9054. static int run_and_free_list(struct pipe *pi)
  9055. {
  9056. int rcode = 0;
  9057. debug_printf_exec("run_and_free_list entered\n");
  9058. if (!G.o_opt[OPT_O_NOEXEC]) {
  9059. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9060. rcode = run_list(pi);
  9061. }
  9062. /* free_pipe_list has the side effect of clearing memory.
  9063. * In the long run that function can be merged with run_list,
  9064. * but doing that now would hobble the debugging effort. */
  9065. free_pipe_list(pi);
  9066. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9067. return rcode;
  9068. }
  9069. static void install_sighandlers(unsigned mask)
  9070. {
  9071. sighandler_t old_handler;
  9072. unsigned sig = 0;
  9073. while ((mask >>= 1) != 0) {
  9074. sig++;
  9075. if (!(mask & 1))
  9076. continue;
  9077. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9078. /* POSIX allows shell to re-enable SIGCHLD
  9079. * even if it was SIG_IGN on entry.
  9080. * Therefore we skip IGN check for it:
  9081. */
  9082. if (sig == SIGCHLD)
  9083. continue;
  9084. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  9085. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  9086. */
  9087. //if (sig == SIGHUP) continue; - TODO?
  9088. if (old_handler == SIG_IGN) {
  9089. /* oops... restore back to IGN, and record this fact */
  9090. install_sighandler(sig, old_handler);
  9091. #if ENABLE_HUSH_TRAP
  9092. if (!G_traps)
  9093. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9094. free(G_traps[sig]);
  9095. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9096. #endif
  9097. }
  9098. }
  9099. }
  9100. /* Called a few times only (or even once if "sh -c") */
  9101. static void install_special_sighandlers(void)
  9102. {
  9103. unsigned mask;
  9104. /* Which signals are shell-special? */
  9105. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9106. if (G_interactive_fd) {
  9107. mask |= SPECIAL_INTERACTIVE_SIGS;
  9108. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9109. mask |= SPECIAL_JOBSTOP_SIGS;
  9110. }
  9111. /* Careful, do not re-install handlers we already installed */
  9112. if (G.special_sig_mask != mask) {
  9113. unsigned diff = mask & ~G.special_sig_mask;
  9114. G.special_sig_mask = mask;
  9115. install_sighandlers(diff);
  9116. }
  9117. }
  9118. #if ENABLE_HUSH_JOB
  9119. /* helper */
  9120. /* Set handlers to restore tty pgrp and exit */
  9121. static void install_fatal_sighandlers(void)
  9122. {
  9123. unsigned mask;
  9124. /* We will restore tty pgrp on these signals */
  9125. mask = 0
  9126. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9127. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9128. + (1 << SIGBUS ) * HUSH_DEBUG
  9129. + (1 << SIGSEGV) * HUSH_DEBUG
  9130. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9131. + (1 << SIGABRT)
  9132. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9133. + (1 << SIGPIPE)
  9134. + (1 << SIGALRM)
  9135. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9136. * if we aren't interactive... but in this case
  9137. * we never want to restore pgrp on exit, and this fn is not called
  9138. */
  9139. /*+ (1 << SIGHUP )*/
  9140. /*+ (1 << SIGTERM)*/
  9141. /*+ (1 << SIGINT )*/
  9142. ;
  9143. G_fatal_sig_mask = mask;
  9144. install_sighandlers(mask);
  9145. }
  9146. #endif
  9147. static int set_mode(int state, char mode, const char *o_opt)
  9148. {
  9149. int idx;
  9150. switch (mode) {
  9151. case 'n':
  9152. G.o_opt[OPT_O_NOEXEC] = state;
  9153. break;
  9154. case 'x':
  9155. IF_HUSH_MODE_X(G_x_mode = state;)
  9156. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9157. break;
  9158. case 'o':
  9159. if (!o_opt) {
  9160. /* "set -+o" without parameter.
  9161. * in bash, set -o produces this output:
  9162. * pipefail off
  9163. * and set +o:
  9164. * set +o pipefail
  9165. * We always use the second form.
  9166. */
  9167. const char *p = o_opt_strings;
  9168. idx = 0;
  9169. while (*p) {
  9170. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9171. idx++;
  9172. p += strlen(p) + 1;
  9173. }
  9174. break;
  9175. }
  9176. idx = index_in_strings(o_opt_strings, o_opt);
  9177. if (idx >= 0) {
  9178. G.o_opt[idx] = state;
  9179. break;
  9180. }
  9181. case 'e':
  9182. G.o_opt[OPT_O_ERREXIT] = state;
  9183. break;
  9184. default:
  9185. return EXIT_FAILURE;
  9186. }
  9187. return EXIT_SUCCESS;
  9188. }
  9189. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9190. int hush_main(int argc, char **argv)
  9191. {
  9192. enum {
  9193. OPT_login = (1 << 0),
  9194. OPT_s = (1 << 1),
  9195. };
  9196. unsigned flags;
  9197. unsigned builtin_argc;
  9198. char **e;
  9199. struct variable *cur_var;
  9200. struct variable *shell_ver;
  9201. INIT_G();
  9202. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9203. G.last_exitcode = EXIT_SUCCESS;
  9204. #if ENABLE_HUSH_FAST
  9205. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9206. #endif
  9207. #if !BB_MMU
  9208. G.argv0_for_re_execing = argv[0];
  9209. #endif
  9210. /* Deal with HUSH_VERSION */
  9211. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9212. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9213. shell_ver = xzalloc(sizeof(*shell_ver));
  9214. shell_ver->flg_export = 1;
  9215. shell_ver->flg_read_only = 1;
  9216. /* Code which handles ${var<op>...} needs writable values for all variables,
  9217. * therefore we xstrdup: */
  9218. shell_ver->varstr = xstrdup(hush_version_str);
  9219. /* Create shell local variables from the values
  9220. * currently living in the environment */
  9221. G.top_var = shell_ver;
  9222. cur_var = G.top_var;
  9223. e = environ;
  9224. if (e) while (*e) {
  9225. char *value = strchr(*e, '=');
  9226. if (value) { /* paranoia */
  9227. cur_var->next = xzalloc(sizeof(*cur_var));
  9228. cur_var = cur_var->next;
  9229. cur_var->varstr = *e;
  9230. cur_var->max_len = strlen(*e);
  9231. cur_var->flg_export = 1;
  9232. }
  9233. e++;
  9234. }
  9235. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9236. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9237. putenv(shell_ver->varstr);
  9238. /* Export PWD */
  9239. set_pwd_var(SETFLAG_EXPORT);
  9240. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9241. /* Set (but not export) PS1/2 unless already set */
  9242. if (!get_local_var_value("PS1"))
  9243. set_local_var_from_halves("PS1", "\\w \\$ ");
  9244. if (!get_local_var_value("PS2"))
  9245. set_local_var_from_halves("PS2", "> ");
  9246. #endif
  9247. #if BASH_HOSTNAME_VAR
  9248. /* Set (but not export) HOSTNAME unless already set */
  9249. if (!get_local_var_value("HOSTNAME")) {
  9250. struct utsname uts;
  9251. uname(&uts);
  9252. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9253. }
  9254. #endif
  9255. /* IFS is not inherited from the parent environment */
  9256. set_local_var_from_halves("IFS", defifs);
  9257. /* bash also exports SHLVL and _,
  9258. * and sets (but doesn't export) the following variables:
  9259. * BASH=/bin/bash
  9260. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9261. * BASH_VERSION='3.2.0(1)-release'
  9262. * HOSTTYPE=i386
  9263. * MACHTYPE=i386-pc-linux-gnu
  9264. * OSTYPE=linux-gnu
  9265. * PPID=<NNNNN> - we also do it elsewhere
  9266. * EUID=<NNNNN>
  9267. * UID=<NNNNN>
  9268. * GROUPS=()
  9269. * LINES=<NNN>
  9270. * COLUMNS=<NNN>
  9271. * BASH_ARGC=()
  9272. * BASH_ARGV=()
  9273. * BASH_LINENO=()
  9274. * BASH_SOURCE=()
  9275. * DIRSTACK=()
  9276. * PIPESTATUS=([0]="0")
  9277. * HISTFILE=/<xxx>/.bash_history
  9278. * HISTFILESIZE=500
  9279. * HISTSIZE=500
  9280. * MAILCHECK=60
  9281. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9282. * SHELL=/bin/bash
  9283. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9284. * TERM=dumb
  9285. * OPTERR=1
  9286. * OPTIND=1
  9287. * PS4='+ '
  9288. */
  9289. #if ENABLE_HUSH_LINENO_VAR
  9290. if (ENABLE_HUSH_LINENO_VAR) {
  9291. char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
  9292. set_local_var(p, /*flags*/ 0);
  9293. G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
  9294. }
  9295. #endif
  9296. #if ENABLE_FEATURE_EDITING
  9297. G.line_input_state = new_line_input_t(FOR_SHELL);
  9298. #endif
  9299. /* Initialize some more globals to non-zero values */
  9300. cmdedit_update_prompt();
  9301. die_func = restore_ttypgrp_and__exit;
  9302. /* Shell is non-interactive at first. We need to call
  9303. * install_special_sighandlers() if we are going to execute "sh <script>",
  9304. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9305. * If we later decide that we are interactive, we run install_special_sighandlers()
  9306. * in order to intercept (more) signals.
  9307. */
  9308. /* Parse options */
  9309. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9310. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9311. builtin_argc = 0;
  9312. #if NUM_SCRIPTS > 0
  9313. if (argc < 0) {
  9314. optarg = get_script_content(-argc - 1);
  9315. optind = 0;
  9316. argc = string_array_len(argv);
  9317. goto run_script;
  9318. }
  9319. #endif
  9320. while (1) {
  9321. int opt = getopt(argc, argv, "+c:exinsl"
  9322. #if !BB_MMU
  9323. "<:$:R:V:"
  9324. # if ENABLE_HUSH_FUNCTIONS
  9325. "F:"
  9326. # endif
  9327. #endif
  9328. );
  9329. if (opt <= 0)
  9330. break;
  9331. switch (opt) {
  9332. case 'c':
  9333. /* Possibilities:
  9334. * sh ... -c 'script'
  9335. * sh ... -c 'script' ARG0 [ARG1...]
  9336. * On NOMMU, if builtin_argc != 0,
  9337. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9338. * "" needs to be replaced with NULL
  9339. * and BARGV vector fed to builtin function.
  9340. * Note: the form without ARG0 never happens:
  9341. * sh ... -c 'builtin' BARGV... ""
  9342. */
  9343. #if NUM_SCRIPTS > 0
  9344. run_script:
  9345. #endif
  9346. if (!G.root_pid) {
  9347. G.root_pid = getpid();
  9348. G.root_ppid = getppid();
  9349. }
  9350. G.global_argv = argv + optind;
  9351. G.global_argc = argc - optind;
  9352. if (builtin_argc) {
  9353. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9354. const struct built_in_command *x;
  9355. install_special_sighandlers();
  9356. x = find_builtin(optarg);
  9357. if (x) { /* paranoia */
  9358. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9359. G.global_argv += builtin_argc;
  9360. G.global_argv[-1] = NULL; /* replace "" */
  9361. fflush_all();
  9362. G.last_exitcode = x->b_function(argv + optind - 1);
  9363. }
  9364. goto final_return;
  9365. }
  9366. if (!G.global_argv[0]) {
  9367. /* -c 'script' (no params): prevent empty $0 */
  9368. G.global_argv--; /* points to argv[i] of 'script' */
  9369. G.global_argv[0] = argv[0];
  9370. G.global_argc++;
  9371. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9372. install_special_sighandlers();
  9373. parse_and_run_string(optarg);
  9374. goto final_return;
  9375. case 'i':
  9376. /* Well, we cannot just declare interactiveness,
  9377. * we have to have some stuff (ctty, etc) */
  9378. /* G_interactive_fd++; */
  9379. break;
  9380. case 's':
  9381. flags |= OPT_s;
  9382. break;
  9383. case 'l':
  9384. flags |= OPT_login;
  9385. break;
  9386. #if !BB_MMU
  9387. case '<': /* "big heredoc" support */
  9388. full_write1_str(optarg);
  9389. _exit(0);
  9390. case '$': {
  9391. unsigned long long empty_trap_mask;
  9392. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9393. optarg++;
  9394. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9395. optarg++;
  9396. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9397. optarg++;
  9398. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9399. optarg++;
  9400. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9401. optarg++;
  9402. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9403. if (empty_trap_mask != 0) {
  9404. IF_HUSH_TRAP(int sig;)
  9405. install_special_sighandlers();
  9406. # if ENABLE_HUSH_TRAP
  9407. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9408. for (sig = 1; sig < NSIG; sig++) {
  9409. if (empty_trap_mask & (1LL << sig)) {
  9410. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9411. install_sighandler(sig, SIG_IGN);
  9412. }
  9413. }
  9414. # endif
  9415. }
  9416. # if ENABLE_HUSH_LOOPS
  9417. optarg++;
  9418. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9419. # endif
  9420. # if ENABLE_HUSH_FUNCTIONS
  9421. /* nommu uses re-exec trick for "... | func | ...",
  9422. * should allow "return".
  9423. * This accidentally allows returns in subshells.
  9424. */
  9425. G_flag_return_in_progress = -1;
  9426. # endif
  9427. break;
  9428. }
  9429. case 'R':
  9430. case 'V':
  9431. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9432. break;
  9433. # if ENABLE_HUSH_FUNCTIONS
  9434. case 'F': {
  9435. struct function *funcp = new_function(optarg);
  9436. /* funcp->name is already set to optarg */
  9437. /* funcp->body is set to NULL. It's a special case. */
  9438. funcp->body_as_string = argv[optind];
  9439. optind++;
  9440. break;
  9441. }
  9442. # endif
  9443. #endif
  9444. case 'n':
  9445. case 'x':
  9446. case 'e':
  9447. if (set_mode(1, opt, NULL) == 0) /* no error */
  9448. break;
  9449. default:
  9450. #ifndef BB_VER
  9451. fprintf(stderr, "Usage: sh [FILE]...\n"
  9452. " or: sh -c command [args]...\n\n");
  9453. exit(EXIT_FAILURE);
  9454. #else
  9455. bb_show_usage();
  9456. #endif
  9457. }
  9458. } /* option parsing loop */
  9459. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9460. G.global_argc = argc - (optind - 1);
  9461. G.global_argv = argv + (optind - 1);
  9462. G.global_argv[0] = argv[0];
  9463. if (!G.root_pid) {
  9464. G.root_pid = getpid();
  9465. G.root_ppid = getppid();
  9466. }
  9467. /* If we are login shell... */
  9468. if (flags & OPT_login) {
  9469. HFILE *input;
  9470. debug_printf("sourcing /etc/profile\n");
  9471. input = hfopen("/etc/profile");
  9472. if (input != NULL) {
  9473. install_special_sighandlers();
  9474. parse_and_run_file(input);
  9475. hfclose(input);
  9476. }
  9477. /* bash: after sourcing /etc/profile,
  9478. * tries to source (in the given order):
  9479. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9480. * stopping on first found. --noprofile turns this off.
  9481. * bash also sources ~/.bash_logout on exit.
  9482. * If called as sh, skips .bash_XXX files.
  9483. */
  9484. }
  9485. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9486. if (!(flags & OPT_s) && G.global_argv[1]) {
  9487. HFILE *input;
  9488. /*
  9489. * "bash <script>" (which is never interactive (unless -i?))
  9490. * sources $BASH_ENV here (without scanning $PATH).
  9491. * If called as sh, does the same but with $ENV.
  9492. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9493. */
  9494. G.global_argc--;
  9495. G.global_argv++;
  9496. debug_printf("running script '%s'\n", G.global_argv[0]);
  9497. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9498. input = hfopen(G.global_argv[0]);
  9499. if (!input) {
  9500. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9501. }
  9502. xfunc_error_retval = 1;
  9503. install_special_sighandlers();
  9504. parse_and_run_file(input);
  9505. #if ENABLE_FEATURE_CLEAN_UP
  9506. hfclose(input);
  9507. #endif
  9508. goto final_return;
  9509. }
  9510. /* Up to here, shell was non-interactive. Now it may become one.
  9511. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9512. */
  9513. /* A shell is interactive if the '-i' flag was given,
  9514. * or if all of the following conditions are met:
  9515. * no -c command
  9516. * no arguments remaining or the -s flag given
  9517. * standard input is a terminal
  9518. * standard output is a terminal
  9519. * Refer to Posix.2, the description of the 'sh' utility.
  9520. */
  9521. #if ENABLE_HUSH_JOB
  9522. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9523. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9524. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9525. if (G_saved_tty_pgrp < 0)
  9526. G_saved_tty_pgrp = 0;
  9527. /* try to dup stdin to high fd#, >= 255 */
  9528. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9529. if (G_interactive_fd < 0) {
  9530. /* try to dup to any fd */
  9531. G_interactive_fd = dup(STDIN_FILENO);
  9532. if (G_interactive_fd < 0) {
  9533. /* give up */
  9534. G_interactive_fd = 0;
  9535. G_saved_tty_pgrp = 0;
  9536. }
  9537. }
  9538. // TODO: track & disallow any attempts of user
  9539. // to (inadvertently) close/redirect G_interactive_fd
  9540. }
  9541. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9542. if (G_interactive_fd) {
  9543. close_on_exec_on(G_interactive_fd);
  9544. if (G_saved_tty_pgrp) {
  9545. /* If we were run as 'hush &', sleep until we are
  9546. * in the foreground (tty pgrp == our pgrp).
  9547. * If we get started under a job aware app (like bash),
  9548. * make sure we are now in charge so we don't fight over
  9549. * who gets the foreground */
  9550. while (1) {
  9551. pid_t shell_pgrp = getpgrp();
  9552. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9553. if (G_saved_tty_pgrp == shell_pgrp)
  9554. break;
  9555. /* send TTIN to ourself (should stop us) */
  9556. kill(- shell_pgrp, SIGTTIN);
  9557. }
  9558. }
  9559. /* Install more signal handlers */
  9560. install_special_sighandlers();
  9561. if (G_saved_tty_pgrp) {
  9562. /* Set other signals to restore saved_tty_pgrp */
  9563. install_fatal_sighandlers();
  9564. /* Put ourselves in our own process group
  9565. * (bash, too, does this only if ctty is available) */
  9566. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9567. /* Grab control of the terminal */
  9568. tcsetpgrp(G_interactive_fd, getpid());
  9569. }
  9570. enable_restore_tty_pgrp_on_exit();
  9571. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9572. {
  9573. const char *hp = get_local_var_value("HISTFILE");
  9574. if (!hp) {
  9575. hp = get_local_var_value("HOME");
  9576. if (hp)
  9577. hp = concat_path_file(hp, ".hush_history");
  9578. } else {
  9579. hp = xstrdup(hp);
  9580. }
  9581. if (hp) {
  9582. G.line_input_state->hist_file = hp;
  9583. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9584. }
  9585. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9586. hp = get_local_var_value("HISTFILESIZE");
  9587. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9588. # endif
  9589. }
  9590. # endif
  9591. } else {
  9592. install_special_sighandlers();
  9593. }
  9594. #elif ENABLE_HUSH_INTERACTIVE
  9595. /* No job control compiled in, only prompt/line editing */
  9596. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9597. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9598. if (G_interactive_fd < 0) {
  9599. /* try to dup to any fd */
  9600. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9601. if (G_interactive_fd < 0)
  9602. /* give up */
  9603. G_interactive_fd = 0;
  9604. }
  9605. }
  9606. if (G_interactive_fd) {
  9607. close_on_exec_on(G_interactive_fd);
  9608. }
  9609. install_special_sighandlers();
  9610. #else
  9611. /* We have interactiveness code disabled */
  9612. install_special_sighandlers();
  9613. #endif
  9614. /* bash:
  9615. * if interactive but not a login shell, sources ~/.bashrc
  9616. * (--norc turns this off, --rcfile <file> overrides)
  9617. */
  9618. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  9619. /* note: ash and hush share this string */
  9620. printf("\n\n%s %s\n"
  9621. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9622. "\n",
  9623. bb_banner,
  9624. "hush - the humble shell"
  9625. );
  9626. }
  9627. parse_and_run_file(hfopen(NULL)); /* stdin */
  9628. final_return:
  9629. hush_exit(G.last_exitcode);
  9630. }
  9631. /*
  9632. * Built-ins
  9633. */
  9634. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9635. {
  9636. return 0;
  9637. }
  9638. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9639. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9640. {
  9641. int argc = string_array_len(argv);
  9642. return applet_main_func(argc, argv);
  9643. }
  9644. #endif
  9645. #if ENABLE_HUSH_TEST || BASH_TEST2
  9646. static int FAST_FUNC builtin_test(char **argv)
  9647. {
  9648. return run_applet_main(argv, test_main);
  9649. }
  9650. #endif
  9651. #if ENABLE_HUSH_ECHO
  9652. static int FAST_FUNC builtin_echo(char **argv)
  9653. {
  9654. return run_applet_main(argv, echo_main);
  9655. }
  9656. #endif
  9657. #if ENABLE_HUSH_PRINTF
  9658. static int FAST_FUNC builtin_printf(char **argv)
  9659. {
  9660. return run_applet_main(argv, printf_main);
  9661. }
  9662. #endif
  9663. #if ENABLE_HUSH_HELP
  9664. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9665. {
  9666. const struct built_in_command *x;
  9667. printf(
  9668. "Built-in commands:\n"
  9669. "------------------\n");
  9670. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9671. if (x->b_descr)
  9672. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9673. }
  9674. return EXIT_SUCCESS;
  9675. }
  9676. #endif
  9677. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9678. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9679. {
  9680. show_history(G.line_input_state);
  9681. return EXIT_SUCCESS;
  9682. }
  9683. #endif
  9684. static char **skip_dash_dash(char **argv)
  9685. {
  9686. argv++;
  9687. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9688. argv++;
  9689. return argv;
  9690. }
  9691. static int FAST_FUNC builtin_cd(char **argv)
  9692. {
  9693. const char *newdir;
  9694. argv = skip_dash_dash(argv);
  9695. newdir = argv[0];
  9696. if (newdir == NULL) {
  9697. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9698. * bash says "bash: cd: HOME not set" and does nothing
  9699. * (exitcode 1)
  9700. */
  9701. const char *home = get_local_var_value("HOME");
  9702. newdir = home ? home : "/";
  9703. }
  9704. if (chdir(newdir)) {
  9705. /* Mimic bash message exactly */
  9706. bb_perror_msg("cd: %s", newdir);
  9707. return EXIT_FAILURE;
  9708. }
  9709. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9710. * Note: do not enforce exporting. If PWD was unset or unexported,
  9711. * set it again, but do not export. bash does the same.
  9712. */
  9713. set_pwd_var(/*flag:*/ 0);
  9714. return EXIT_SUCCESS;
  9715. }
  9716. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9717. {
  9718. puts(get_cwd(0));
  9719. return EXIT_SUCCESS;
  9720. }
  9721. static int FAST_FUNC builtin_eval(char **argv)
  9722. {
  9723. argv = skip_dash_dash(argv);
  9724. if (!argv[0])
  9725. return EXIT_SUCCESS;
  9726. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9727. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9728. if (!argv[1]) {
  9729. /* bash:
  9730. * eval "echo Hi; done" ("done" is syntax error):
  9731. * "echo Hi" will not execute too.
  9732. */
  9733. parse_and_run_string(argv[0]);
  9734. } else {
  9735. /* "The eval utility shall construct a command by
  9736. * concatenating arguments together, separating
  9737. * each with a <space> character."
  9738. */
  9739. char *str, *p;
  9740. unsigned len = 0;
  9741. char **pp = argv;
  9742. do
  9743. len += strlen(*pp) + 1;
  9744. while (*++pp);
  9745. str = p = xmalloc(len);
  9746. pp = argv;
  9747. for (;;) {
  9748. p = stpcpy(p, *pp);
  9749. pp++;
  9750. if (!*pp)
  9751. break;
  9752. *p++ = ' ';
  9753. }
  9754. parse_and_run_string(str);
  9755. free(str);
  9756. }
  9757. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9758. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9759. return G.last_exitcode;
  9760. }
  9761. static int FAST_FUNC builtin_exec(char **argv)
  9762. {
  9763. argv = skip_dash_dash(argv);
  9764. if (argv[0] == NULL)
  9765. return EXIT_SUCCESS; /* bash does this */
  9766. /* Careful: we can end up here after [v]fork. Do not restore
  9767. * tty pgrp then, only top-level shell process does that */
  9768. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9769. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9770. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9771. * open here. However, they are all CLOEXEC, and execv below
  9772. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9773. * it should show no extra open fds in the "ls" process.
  9774. * If we'd try to run builtins/NOEXECs, this would need improving.
  9775. */
  9776. //close_saved_fds_and_FILE_fds();
  9777. /* TODO: if exec fails, bash does NOT exit! We do.
  9778. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9779. * and tcsetpgrp, and this is inherently racy.
  9780. */
  9781. execvp_or_die(argv);
  9782. }
  9783. static int FAST_FUNC builtin_exit(char **argv)
  9784. {
  9785. debug_printf_exec("%s()\n", __func__);
  9786. /* interactive bash:
  9787. * # trap "echo EEE" EXIT
  9788. * # exit
  9789. * exit
  9790. * There are stopped jobs.
  9791. * (if there are _stopped_ jobs, running ones don't count)
  9792. * # exit
  9793. * exit
  9794. * EEE (then bash exits)
  9795. *
  9796. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9797. */
  9798. /* note: EXIT trap is run by hush_exit */
  9799. argv = skip_dash_dash(argv);
  9800. if (argv[0] == NULL)
  9801. hush_exit(G.last_exitcode);
  9802. /* mimic bash: exit 123abc == exit 255 + error msg */
  9803. xfunc_error_retval = 255;
  9804. /* bash: exit -2 == exit 254, no error msg */
  9805. hush_exit(xatoi(argv[0]) & 0xff);
  9806. }
  9807. #if ENABLE_HUSH_TYPE
  9808. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9809. static int FAST_FUNC builtin_type(char **argv)
  9810. {
  9811. int ret = EXIT_SUCCESS;
  9812. while (*++argv) {
  9813. const char *type;
  9814. char *path = NULL;
  9815. if (0) {} /* make conditional compile easier below */
  9816. /*else if (find_alias(*argv))
  9817. type = "an alias";*/
  9818. #if ENABLE_HUSH_FUNCTIONS
  9819. else if (find_function(*argv))
  9820. type = "a function";
  9821. #endif
  9822. else if (find_builtin(*argv))
  9823. type = "a shell builtin";
  9824. else if ((path = find_in_path(*argv)) != NULL)
  9825. type = path;
  9826. else {
  9827. bb_error_msg("type: %s: not found", *argv);
  9828. ret = EXIT_FAILURE;
  9829. continue;
  9830. }
  9831. printf("%s is %s\n", *argv, type);
  9832. free(path);
  9833. }
  9834. return ret;
  9835. }
  9836. #endif
  9837. #if ENABLE_HUSH_READ
  9838. /* Interruptibility of read builtin in bash
  9839. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9840. *
  9841. * Empty trap makes read ignore corresponding signal, for any signal.
  9842. *
  9843. * SIGINT:
  9844. * - terminates non-interactive shell;
  9845. * - interrupts read in interactive shell;
  9846. * if it has non-empty trap:
  9847. * - executes trap and returns to command prompt in interactive shell;
  9848. * - executes trap and returns to read in non-interactive shell;
  9849. * SIGTERM:
  9850. * - is ignored (does not interrupt) read in interactive shell;
  9851. * - terminates non-interactive shell;
  9852. * if it has non-empty trap:
  9853. * - executes trap and returns to read;
  9854. * SIGHUP:
  9855. * - terminates shell (regardless of interactivity);
  9856. * if it has non-empty trap:
  9857. * - executes trap and returns to read;
  9858. * SIGCHLD from children:
  9859. * - does not interrupt read regardless of interactivity:
  9860. * try: sleep 1 & read x; echo $x
  9861. */
  9862. static int FAST_FUNC builtin_read(char **argv)
  9863. {
  9864. const char *r;
  9865. struct builtin_read_params params;
  9866. memset(&params, 0, sizeof(params));
  9867. /* "!": do not abort on errors.
  9868. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9869. */
  9870. params.read_flags = getopt32(argv,
  9871. #if BASH_READ_D
  9872. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9873. #else
  9874. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9875. #endif
  9876. );
  9877. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9878. return EXIT_FAILURE;
  9879. argv += optind;
  9880. params.argv = argv;
  9881. params.setvar = set_local_var_from_halves;
  9882. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9883. again:
  9884. r = shell_builtin_read(&params);
  9885. if ((uintptr_t)r == 1 && errno == EINTR) {
  9886. unsigned sig = check_and_run_traps();
  9887. if (sig != SIGINT)
  9888. goto again;
  9889. }
  9890. if ((uintptr_t)r > 1) {
  9891. bb_error_msg("%s", r);
  9892. r = (char*)(uintptr_t)1;
  9893. }
  9894. return (uintptr_t)r;
  9895. }
  9896. #endif
  9897. #if ENABLE_HUSH_UMASK
  9898. static int FAST_FUNC builtin_umask(char **argv)
  9899. {
  9900. int rc;
  9901. mode_t mask;
  9902. rc = 1;
  9903. mask = umask(0);
  9904. argv = skip_dash_dash(argv);
  9905. if (argv[0]) {
  9906. mode_t old_mask = mask;
  9907. /* numeric umasks are taken as-is */
  9908. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9909. if (!isdigit(argv[0][0]))
  9910. mask ^= 0777;
  9911. mask = bb_parse_mode(argv[0], mask);
  9912. if (!isdigit(argv[0][0]))
  9913. mask ^= 0777;
  9914. if ((unsigned)mask > 0777) {
  9915. mask = old_mask;
  9916. /* bash messages:
  9917. * bash: umask: 'q': invalid symbolic mode operator
  9918. * bash: umask: 999: octal number out of range
  9919. */
  9920. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9921. rc = 0;
  9922. }
  9923. } else {
  9924. /* Mimic bash */
  9925. printf("%04o\n", (unsigned) mask);
  9926. /* fall through and restore mask which we set to 0 */
  9927. }
  9928. umask(mask);
  9929. return !rc; /* rc != 0 - success */
  9930. }
  9931. #endif
  9932. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9933. static void print_escaped(const char *s)
  9934. {
  9935. if (*s == '\'')
  9936. goto squote;
  9937. do {
  9938. const char *p = strchrnul(s, '\'');
  9939. /* print 'xxxx', possibly just '' */
  9940. printf("'%.*s'", (int)(p - s), s);
  9941. if (*p == '\0')
  9942. break;
  9943. s = p;
  9944. squote:
  9945. /* s points to '; print "'''...'''" */
  9946. putchar('"');
  9947. do putchar('\''); while (*++s == '\'');
  9948. putchar('"');
  9949. } while (*s);
  9950. }
  9951. #endif
  9952. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9953. static int helper_export_local(char **argv, unsigned flags)
  9954. {
  9955. do {
  9956. char *name = *argv;
  9957. char *name_end = strchrnul(name, '=');
  9958. /* So far we do not check that name is valid (TODO?) */
  9959. if (*name_end == '\0') {
  9960. struct variable *var, **vpp;
  9961. vpp = get_ptr_to_local_var(name, name_end - name);
  9962. var = vpp ? *vpp : NULL;
  9963. if (flags & SETFLAG_UNEXPORT) {
  9964. /* export -n NAME (without =VALUE) */
  9965. if (var) {
  9966. var->flg_export = 0;
  9967. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9968. unsetenv(name);
  9969. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9970. continue;
  9971. }
  9972. if (flags & SETFLAG_EXPORT) {
  9973. /* export NAME (without =VALUE) */
  9974. if (var) {
  9975. var->flg_export = 1;
  9976. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  9977. putenv(var->varstr);
  9978. continue;
  9979. }
  9980. }
  9981. if (flags & SETFLAG_MAKE_RO) {
  9982. /* readonly NAME (without =VALUE) */
  9983. if (var) {
  9984. var->flg_read_only = 1;
  9985. continue;
  9986. }
  9987. }
  9988. # if ENABLE_HUSH_LOCAL
  9989. /* Is this "local" bltin? */
  9990. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  9991. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  9992. if (var && var->var_nest_level == lvl) {
  9993. /* "local x=abc; ...; local x" - ignore second local decl */
  9994. continue;
  9995. }
  9996. }
  9997. # endif
  9998. /* Exporting non-existing variable.
  9999. * bash does not put it in environment,
  10000. * but remembers that it is exported,
  10001. * and does put it in env when it is set later.
  10002. * We just set it to "" and export.
  10003. */
  10004. /* Or, it's "local NAME" (without =VALUE).
  10005. * bash sets the value to "".
  10006. */
  10007. /* Or, it's "readonly NAME" (without =VALUE).
  10008. * bash remembers NAME and disallows its creation
  10009. * in the future.
  10010. */
  10011. name = xasprintf("%s=", name);
  10012. } else {
  10013. /* (Un)exporting/making local NAME=VALUE */
  10014. name = xstrdup(name);
  10015. }
  10016. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10017. if (set_local_var(name, flags))
  10018. return EXIT_FAILURE;
  10019. } while (*++argv);
  10020. return EXIT_SUCCESS;
  10021. }
  10022. #endif
  10023. #if ENABLE_HUSH_EXPORT
  10024. static int FAST_FUNC builtin_export(char **argv)
  10025. {
  10026. unsigned opt_unexport;
  10027. #if ENABLE_HUSH_EXPORT_N
  10028. /* "!": do not abort on errors */
  10029. opt_unexport = getopt32(argv, "!n");
  10030. if (opt_unexport == (uint32_t)-1)
  10031. return EXIT_FAILURE;
  10032. argv += optind;
  10033. #else
  10034. opt_unexport = 0;
  10035. argv++;
  10036. #endif
  10037. if (argv[0] == NULL) {
  10038. char **e = environ;
  10039. if (e) {
  10040. while (*e) {
  10041. #if 0
  10042. puts(*e++);
  10043. #else
  10044. /* ash emits: export VAR='VAL'
  10045. * bash: declare -x VAR="VAL"
  10046. * we follow ash example */
  10047. const char *s = *e++;
  10048. const char *p = strchr(s, '=');
  10049. if (!p) /* wtf? take next variable */
  10050. continue;
  10051. /* export var= */
  10052. printf("export %.*s", (int)(p - s) + 1, s);
  10053. print_escaped(p + 1);
  10054. putchar('\n');
  10055. #endif
  10056. }
  10057. /*fflush_all(); - done after each builtin anyway */
  10058. }
  10059. return EXIT_SUCCESS;
  10060. }
  10061. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10062. }
  10063. #endif
  10064. #if ENABLE_HUSH_LOCAL
  10065. static int FAST_FUNC builtin_local(char **argv)
  10066. {
  10067. if (G.func_nest_level == 0) {
  10068. bb_error_msg("%s: not in a function", argv[0]);
  10069. return EXIT_FAILURE; /* bash compat */
  10070. }
  10071. argv++;
  10072. /* Since all builtins run in a nested variable level,
  10073. * need to use level - 1 here. Or else the variable will be removed at once
  10074. * after builtin returns.
  10075. */
  10076. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10077. }
  10078. #endif
  10079. #if ENABLE_HUSH_READONLY
  10080. static int FAST_FUNC builtin_readonly(char **argv)
  10081. {
  10082. argv++;
  10083. if (*argv == NULL) {
  10084. /* bash: readonly [-p]: list all readonly VARs
  10085. * (-p has no effect in bash)
  10086. */
  10087. struct variable *e;
  10088. for (e = G.top_var; e; e = e->next) {
  10089. if (e->flg_read_only) {
  10090. //TODO: quote value: readonly VAR='VAL'
  10091. printf("readonly %s\n", e->varstr);
  10092. }
  10093. }
  10094. return EXIT_SUCCESS;
  10095. }
  10096. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10097. }
  10098. #endif
  10099. #if ENABLE_HUSH_UNSET
  10100. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10101. static int FAST_FUNC builtin_unset(char **argv)
  10102. {
  10103. int ret;
  10104. unsigned opts;
  10105. /* "!": do not abort on errors */
  10106. /* "+": stop at 1st non-option */
  10107. opts = getopt32(argv, "!+vf");
  10108. if (opts == (unsigned)-1)
  10109. return EXIT_FAILURE;
  10110. if (opts == 3) {
  10111. bb_error_msg("unset: -v and -f are exclusive");
  10112. return EXIT_FAILURE;
  10113. }
  10114. argv += optind;
  10115. ret = EXIT_SUCCESS;
  10116. while (*argv) {
  10117. if (!(opts & 2)) { /* not -f */
  10118. if (unset_local_var(*argv)) {
  10119. /* unset <nonexistent_var> doesn't fail.
  10120. * Error is when one tries to unset RO var.
  10121. * Message was printed by unset_local_var. */
  10122. ret = EXIT_FAILURE;
  10123. }
  10124. }
  10125. # if ENABLE_HUSH_FUNCTIONS
  10126. else {
  10127. unset_func(*argv);
  10128. }
  10129. # endif
  10130. argv++;
  10131. }
  10132. return ret;
  10133. }
  10134. #endif
  10135. #if ENABLE_HUSH_SET
  10136. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10137. * built-in 'set' handler
  10138. * SUSv3 says:
  10139. * set [-abCefhmnuvx] [-o option] [argument...]
  10140. * set [+abCefhmnuvx] [+o option] [argument...]
  10141. * set -- [argument...]
  10142. * set -o
  10143. * set +o
  10144. * Implementations shall support the options in both their hyphen and
  10145. * plus-sign forms. These options can also be specified as options to sh.
  10146. * Examples:
  10147. * Write out all variables and their values: set
  10148. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10149. * Turn on the -x and -v options: set -xv
  10150. * Unset all positional parameters: set --
  10151. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10152. * Set the positional parameters to the expansion of x, even if x expands
  10153. * with a leading '-' or '+': set -- $x
  10154. *
  10155. * So far, we only support "set -- [argument...]" and some of the short names.
  10156. */
  10157. static int FAST_FUNC builtin_set(char **argv)
  10158. {
  10159. int n;
  10160. char **pp, **g_argv;
  10161. char *arg = *++argv;
  10162. if (arg == NULL) {
  10163. struct variable *e;
  10164. for (e = G.top_var; e; e = e->next)
  10165. puts(e->varstr);
  10166. return EXIT_SUCCESS;
  10167. }
  10168. do {
  10169. if (strcmp(arg, "--") == 0) {
  10170. ++argv;
  10171. goto set_argv;
  10172. }
  10173. if (arg[0] != '+' && arg[0] != '-')
  10174. break;
  10175. for (n = 1; arg[n]; ++n) {
  10176. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  10177. goto error;
  10178. if (arg[n] == 'o' && argv[1])
  10179. argv++;
  10180. }
  10181. } while ((arg = *++argv) != NULL);
  10182. /* Now argv[0] is 1st argument */
  10183. if (arg == NULL)
  10184. return EXIT_SUCCESS;
  10185. set_argv:
  10186. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10187. g_argv = G.global_argv;
  10188. if (G.global_args_malloced) {
  10189. pp = g_argv;
  10190. while (*++pp)
  10191. free(*pp);
  10192. g_argv[1] = NULL;
  10193. } else {
  10194. G.global_args_malloced = 1;
  10195. pp = xzalloc(sizeof(pp[0]) * 2);
  10196. pp[0] = g_argv[0]; /* retain $0 */
  10197. g_argv = pp;
  10198. }
  10199. /* This realloc's G.global_argv */
  10200. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10201. G.global_argc = 1 + string_array_len(pp + 1);
  10202. return EXIT_SUCCESS;
  10203. /* Nothing known, so abort */
  10204. error:
  10205. bb_error_msg("%s: %s: invalid option", "set", arg);
  10206. return EXIT_FAILURE;
  10207. }
  10208. #endif
  10209. static int FAST_FUNC builtin_shift(char **argv)
  10210. {
  10211. int n = 1;
  10212. argv = skip_dash_dash(argv);
  10213. if (argv[0]) {
  10214. n = bb_strtou(argv[0], NULL, 10);
  10215. if (errno || n < 0) {
  10216. /* shared string with ash.c */
  10217. bb_error_msg("Illegal number: %s", argv[0]);
  10218. /*
  10219. * ash aborts in this case.
  10220. * bash prints error message and set $? to 1.
  10221. * Interestingly, for "shift 99999" bash does not
  10222. * print error message, but does set $? to 1
  10223. * (and does no shifting at all).
  10224. */
  10225. }
  10226. }
  10227. if (n >= 0 && n < G.global_argc) {
  10228. if (G_global_args_malloced) {
  10229. int m = 1;
  10230. while (m <= n)
  10231. free(G.global_argv[m++]);
  10232. }
  10233. G.global_argc -= n;
  10234. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10235. G.global_argc * sizeof(G.global_argv[0]));
  10236. return EXIT_SUCCESS;
  10237. }
  10238. return EXIT_FAILURE;
  10239. }
  10240. #if ENABLE_HUSH_GETOPTS
  10241. static int FAST_FUNC builtin_getopts(char **argv)
  10242. {
  10243. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10244. TODO:
  10245. If a required argument is not found, and getopts is not silent,
  10246. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10247. diagnostic message is printed. If getopts is silent, then a
  10248. colon (:) is placed in VAR and OPTARG is set to the option
  10249. character found.
  10250. Test that VAR is a valid variable name?
  10251. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10252. */
  10253. char cbuf[2];
  10254. const char *cp, *optstring, *var;
  10255. int c, n, exitcode, my_opterr;
  10256. unsigned count;
  10257. optstring = *++argv;
  10258. if (!optstring || !(var = *++argv)) {
  10259. bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10260. return EXIT_FAILURE;
  10261. }
  10262. if (argv[1])
  10263. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10264. else
  10265. argv = G.global_argv;
  10266. cbuf[1] = '\0';
  10267. my_opterr = 0;
  10268. if (optstring[0] != ':') {
  10269. cp = get_local_var_value("OPTERR");
  10270. /* 0 if "OPTERR=0", 1 otherwise */
  10271. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10272. }
  10273. /* getopts stops on first non-option. Add "+" to force that */
  10274. /*if (optstring[0] != '+')*/ {
  10275. char *s = alloca(strlen(optstring) + 2);
  10276. sprintf(s, "+%s", optstring);
  10277. optstring = s;
  10278. }
  10279. /* Naively, now we should just
  10280. * cp = get_local_var_value("OPTIND");
  10281. * optind = cp ? atoi(cp) : 0;
  10282. * optarg = NULL;
  10283. * opterr = my_opterr;
  10284. * c = getopt(string_array_len(argv), argv, optstring);
  10285. * and be done? Not so fast...
  10286. * Unlike normal getopt() usage in C programs, here
  10287. * each successive call will (usually) have the same argv[] CONTENTS,
  10288. * but not the ADDRESSES. Worse yet, it's possible that between
  10289. * invocations of "getopts", there will be calls to shell builtins
  10290. * which use getopt() internally. Example:
  10291. * while getopts "abc" RES -a -bc -abc de; do
  10292. * unset -ff func
  10293. * done
  10294. * This would not work correctly: getopt() call inside "unset"
  10295. * modifies internal libc state which is tracking position in
  10296. * multi-option strings ("-abc"). At best, it can skip options
  10297. * or return the same option infinitely. With glibc implementation
  10298. * of getopt(), it would use outright invalid pointers and return
  10299. * garbage even _without_ "unset" mangling internal state.
  10300. *
  10301. * We resort to resetting getopt() state and calling it N times,
  10302. * until we get Nth result (or failure).
  10303. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10304. */
  10305. GETOPT_RESET();
  10306. count = 0;
  10307. n = string_array_len(argv);
  10308. do {
  10309. optarg = NULL;
  10310. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10311. c = getopt(n, argv, optstring);
  10312. if (c < 0)
  10313. break;
  10314. count++;
  10315. } while (count <= G.getopt_count);
  10316. /* Set OPTIND. Prevent resetting of the magic counter! */
  10317. set_local_var_from_halves("OPTIND", utoa(optind));
  10318. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10319. GETOPT_RESET(); /* just in case */
  10320. /* Set OPTARG */
  10321. /* Always set or unset, never left as-is, even on exit/error:
  10322. * "If no option was found, or if the option that was found
  10323. * does not have an option-argument, OPTARG shall be unset."
  10324. */
  10325. cp = optarg;
  10326. if (c == '?') {
  10327. /* If ":optstring" and unknown option is seen,
  10328. * it is stored to OPTARG.
  10329. */
  10330. if (optstring[1] == ':') {
  10331. cbuf[0] = optopt;
  10332. cp = cbuf;
  10333. }
  10334. }
  10335. if (cp)
  10336. set_local_var_from_halves("OPTARG", cp);
  10337. else
  10338. unset_local_var("OPTARG");
  10339. /* Convert -1 to "?" */
  10340. exitcode = EXIT_SUCCESS;
  10341. if (c < 0) { /* -1: end of options */
  10342. exitcode = EXIT_FAILURE;
  10343. c = '?';
  10344. }
  10345. /* Set VAR */
  10346. cbuf[0] = c;
  10347. set_local_var_from_halves(var, cbuf);
  10348. return exitcode;
  10349. }
  10350. #endif
  10351. static int FAST_FUNC builtin_source(char **argv)
  10352. {
  10353. char *arg_path, *filename;
  10354. HFILE *input;
  10355. save_arg_t sv;
  10356. char *args_need_save;
  10357. #if ENABLE_HUSH_FUNCTIONS
  10358. smallint sv_flg;
  10359. #endif
  10360. argv = skip_dash_dash(argv);
  10361. filename = argv[0];
  10362. if (!filename) {
  10363. /* bash says: "bash: .: filename argument required" */
  10364. return 2; /* bash compat */
  10365. }
  10366. arg_path = NULL;
  10367. if (!strchr(filename, '/')) {
  10368. arg_path = find_in_path(filename);
  10369. if (arg_path)
  10370. filename = arg_path;
  10371. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10372. errno = ENOENT;
  10373. bb_simple_perror_msg(filename);
  10374. return EXIT_FAILURE;
  10375. }
  10376. }
  10377. input = hfopen(filename);
  10378. free(arg_path);
  10379. if (!input) {
  10380. bb_perror_msg("%s", filename);
  10381. /* POSIX: non-interactive shell should abort here,
  10382. * not merely fail. So far no one complained :)
  10383. */
  10384. return EXIT_FAILURE;
  10385. }
  10386. #if ENABLE_HUSH_FUNCTIONS
  10387. sv_flg = G_flag_return_in_progress;
  10388. /* "we are inside sourced file, ok to use return" */
  10389. G_flag_return_in_progress = -1;
  10390. #endif
  10391. args_need_save = argv[1]; /* used as a boolean variable */
  10392. if (args_need_save)
  10393. save_and_replace_G_args(&sv, argv);
  10394. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10395. G.last_exitcode = 0;
  10396. parse_and_run_file(input);
  10397. hfclose(input);
  10398. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10399. restore_G_args(&sv, argv);
  10400. #if ENABLE_HUSH_FUNCTIONS
  10401. G_flag_return_in_progress = sv_flg;
  10402. #endif
  10403. return G.last_exitcode;
  10404. }
  10405. #if ENABLE_HUSH_TRAP
  10406. static int FAST_FUNC builtin_trap(char **argv)
  10407. {
  10408. int sig;
  10409. char *new_cmd;
  10410. if (!G_traps)
  10411. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10412. argv++;
  10413. if (!*argv) {
  10414. int i;
  10415. /* No args: print all trapped */
  10416. for (i = 0; i < NSIG; ++i) {
  10417. if (G_traps[i]) {
  10418. printf("trap -- ");
  10419. print_escaped(G_traps[i]);
  10420. /* note: bash adds "SIG", but only if invoked
  10421. * as "bash". If called as "sh", or if set -o posix,
  10422. * then it prints short signal names.
  10423. * We are printing short names: */
  10424. printf(" %s\n", get_signame(i));
  10425. }
  10426. }
  10427. /*fflush_all(); - done after each builtin anyway */
  10428. return EXIT_SUCCESS;
  10429. }
  10430. new_cmd = NULL;
  10431. /* If first arg is a number: reset all specified signals */
  10432. sig = bb_strtou(*argv, NULL, 10);
  10433. if (errno == 0) {
  10434. int ret;
  10435. process_sig_list:
  10436. ret = EXIT_SUCCESS;
  10437. while (*argv) {
  10438. sighandler_t handler;
  10439. sig = get_signum(*argv++);
  10440. if (sig < 0) {
  10441. ret = EXIT_FAILURE;
  10442. /* Mimic bash message exactly */
  10443. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10444. continue;
  10445. }
  10446. free(G_traps[sig]);
  10447. G_traps[sig] = xstrdup(new_cmd);
  10448. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10449. get_signame(sig), sig, G_traps[sig]);
  10450. /* There is no signal for 0 (EXIT) */
  10451. if (sig == 0)
  10452. continue;
  10453. if (new_cmd)
  10454. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10455. else
  10456. /* We are removing trap handler */
  10457. handler = pick_sighandler(sig);
  10458. install_sighandler(sig, handler);
  10459. }
  10460. return ret;
  10461. }
  10462. if (!argv[1]) { /* no second arg */
  10463. bb_error_msg("trap: invalid arguments");
  10464. return EXIT_FAILURE;
  10465. }
  10466. /* First arg is "-": reset all specified to default */
  10467. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10468. /* Everything else: set arg as signal handler
  10469. * (includes "" case, which ignores signal) */
  10470. if (argv[0][0] == '-') {
  10471. if (argv[0][1] == '\0') { /* "-" */
  10472. /* new_cmd remains NULL: "reset these sigs" */
  10473. goto reset_traps;
  10474. }
  10475. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10476. argv++;
  10477. }
  10478. /* else: "-something", no special meaning */
  10479. }
  10480. new_cmd = *argv;
  10481. reset_traps:
  10482. argv++;
  10483. goto process_sig_list;
  10484. }
  10485. #endif
  10486. #if ENABLE_HUSH_JOB
  10487. static struct pipe *parse_jobspec(const char *str)
  10488. {
  10489. struct pipe *pi;
  10490. unsigned jobnum;
  10491. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10492. if (str[0] != '%'
  10493. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10494. ) {
  10495. bb_error_msg("bad argument '%s'", str);
  10496. return NULL;
  10497. }
  10498. /* It is "%%", "%+" or "%" - current job */
  10499. jobnum = G.last_jobid;
  10500. if (jobnum == 0) {
  10501. bb_error_msg("no current job");
  10502. return NULL;
  10503. }
  10504. }
  10505. for (pi = G.job_list; pi; pi = pi->next) {
  10506. if (pi->jobid == jobnum) {
  10507. return pi;
  10508. }
  10509. }
  10510. bb_error_msg("%u: no such job", jobnum);
  10511. return NULL;
  10512. }
  10513. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10514. {
  10515. struct pipe *job;
  10516. const char *status_string;
  10517. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10518. for (job = G.job_list; job; job = job->next) {
  10519. if (job->alive_cmds == job->stopped_cmds)
  10520. status_string = "Stopped";
  10521. else
  10522. status_string = "Running";
  10523. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10524. }
  10525. clean_up_last_dead_job();
  10526. return EXIT_SUCCESS;
  10527. }
  10528. /* built-in 'fg' and 'bg' handler */
  10529. static int FAST_FUNC builtin_fg_bg(char **argv)
  10530. {
  10531. int i;
  10532. struct pipe *pi;
  10533. if (!G_interactive_fd)
  10534. return EXIT_FAILURE;
  10535. /* If they gave us no args, assume they want the last backgrounded task */
  10536. if (!argv[1]) {
  10537. for (pi = G.job_list; pi; pi = pi->next) {
  10538. if (pi->jobid == G.last_jobid) {
  10539. goto found;
  10540. }
  10541. }
  10542. bb_error_msg("%s: no current job", argv[0]);
  10543. return EXIT_FAILURE;
  10544. }
  10545. pi = parse_jobspec(argv[1]);
  10546. if (!pi)
  10547. return EXIT_FAILURE;
  10548. found:
  10549. /* TODO: bash prints a string representation
  10550. * of job being foregrounded (like "sleep 1 | cat") */
  10551. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10552. /* Put the job into the foreground. */
  10553. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10554. }
  10555. /* Restart the processes in the job */
  10556. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10557. for (i = 0; i < pi->num_cmds; i++) {
  10558. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10559. }
  10560. pi->stopped_cmds = 0;
  10561. i = kill(- pi->pgrp, SIGCONT);
  10562. if (i < 0) {
  10563. if (errno == ESRCH) {
  10564. delete_finished_job(pi);
  10565. return EXIT_SUCCESS;
  10566. }
  10567. bb_perror_msg("kill (SIGCONT)");
  10568. }
  10569. if (argv[0][0] == 'f') {
  10570. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10571. return checkjobs_and_fg_shell(pi);
  10572. }
  10573. return EXIT_SUCCESS;
  10574. }
  10575. #endif
  10576. #if ENABLE_HUSH_KILL
  10577. static int FAST_FUNC builtin_kill(char **argv)
  10578. {
  10579. int ret = 0;
  10580. # if ENABLE_HUSH_JOB
  10581. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10582. int i = 1;
  10583. do {
  10584. struct pipe *pi;
  10585. char *dst;
  10586. int j, n;
  10587. if (argv[i][0] != '%')
  10588. continue;
  10589. /*
  10590. * "kill %N" - job kill
  10591. * Converting to pgrp / pid kill
  10592. */
  10593. pi = parse_jobspec(argv[i]);
  10594. if (!pi) {
  10595. /* Eat bad jobspec */
  10596. j = i;
  10597. do {
  10598. j++;
  10599. argv[j - 1] = argv[j];
  10600. } while (argv[j]);
  10601. ret = 1;
  10602. i--;
  10603. continue;
  10604. }
  10605. /*
  10606. * In jobs started under job control, we signal
  10607. * entire process group by kill -PGRP_ID.
  10608. * This happens, f.e., in interactive shell.
  10609. *
  10610. * Otherwise, we signal each child via
  10611. * kill PID1 PID2 PID3.
  10612. * Testcases:
  10613. * sh -c 'sleep 1|sleep 1 & kill %1'
  10614. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10615. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10616. */
  10617. n = G_interactive_fd ? 1 : pi->num_cmds;
  10618. dst = alloca(n * sizeof(int)*4);
  10619. argv[i] = dst;
  10620. if (G_interactive_fd)
  10621. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10622. else for (j = 0; j < n; j++) {
  10623. struct command *cmd = &pi->cmds[j];
  10624. /* Skip exited members of the job */
  10625. if (cmd->pid == 0)
  10626. continue;
  10627. /*
  10628. * kill_main has matching code to expect
  10629. * leading space. Needed to not confuse
  10630. * negative pids with "kill -SIGNAL_NO" syntax
  10631. */
  10632. dst += sprintf(dst, " %u", (int)cmd->pid);
  10633. }
  10634. *dst = '\0';
  10635. } while (argv[++i]);
  10636. }
  10637. # endif
  10638. if (argv[1] || ret == 0) {
  10639. ret = run_applet_main(argv, kill_main);
  10640. }
  10641. /* else: ret = 1, "kill %bad_jobspec" case */
  10642. return ret;
  10643. }
  10644. #endif
  10645. #if ENABLE_HUSH_WAIT
  10646. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10647. #if !ENABLE_HUSH_JOB
  10648. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10649. #endif
  10650. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10651. {
  10652. int ret = 0;
  10653. for (;;) {
  10654. int sig;
  10655. sigset_t oldset;
  10656. if (!sigisemptyset(&G.pending_set))
  10657. goto check_sig;
  10658. /* waitpid is not interruptible by SA_RESTARTed
  10659. * signals which we use. Thus, this ugly dance:
  10660. */
  10661. /* Make sure possible SIGCHLD is stored in kernel's
  10662. * pending signal mask before we call waitpid.
  10663. * Or else we may race with SIGCHLD, lose it,
  10664. * and get stuck in sigsuspend...
  10665. */
  10666. sigfillset(&oldset); /* block all signals, remember old set */
  10667. sigprocmask2(SIG_SETMASK, &oldset);
  10668. if (!sigisemptyset(&G.pending_set)) {
  10669. /* Crap! we raced with some signal! */
  10670. goto restore;
  10671. }
  10672. /*errno = 0; - checkjobs does this */
  10673. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10674. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10675. debug_printf_exec("checkjobs:%d\n", ret);
  10676. #if ENABLE_HUSH_JOB
  10677. if (waitfor_pipe) {
  10678. int rcode = job_exited_or_stopped(waitfor_pipe);
  10679. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10680. if (rcode >= 0) {
  10681. ret = rcode;
  10682. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10683. break;
  10684. }
  10685. }
  10686. #endif
  10687. /* if ECHILD, there are no children (ret is -1 or 0) */
  10688. /* if ret == 0, no children changed state */
  10689. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10690. if (errno == ECHILD || ret) {
  10691. ret--;
  10692. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10693. ret = 0;
  10694. #if ENABLE_HUSH_BASH_COMPAT
  10695. if (waitfor_pid == -1 && errno == ECHILD) {
  10696. /* exitcode of "wait -n" with no children is 127, not 0 */
  10697. ret = 127;
  10698. }
  10699. #endif
  10700. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10701. break;
  10702. }
  10703. /* Wait for SIGCHLD or any other signal */
  10704. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10705. /* Note: sigsuspend invokes signal handler */
  10706. sigsuspend(&oldset);
  10707. restore:
  10708. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10709. check_sig:
  10710. /* So, did we get a signal? */
  10711. sig = check_and_run_traps();
  10712. if (sig /*&& sig != SIGCHLD - always true */) {
  10713. /* Do this for any (non-ignored) signal, not only for ^C */
  10714. ret = 128 + sig;
  10715. break;
  10716. }
  10717. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10718. }
  10719. return ret;
  10720. }
  10721. static int FAST_FUNC builtin_wait(char **argv)
  10722. {
  10723. int ret;
  10724. int status;
  10725. argv = skip_dash_dash(argv);
  10726. #if ENABLE_HUSH_BASH_COMPAT
  10727. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10728. /* wait -n */
  10729. /* (bash accepts "wait -n PID" too and ignores PID) */
  10730. G.dead_job_exitcode = -1;
  10731. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10732. }
  10733. #endif
  10734. if (argv[0] == NULL) {
  10735. /* Don't care about wait results */
  10736. /* Note 1: must wait until there are no more children */
  10737. /* Note 2: must be interruptible */
  10738. /* Examples:
  10739. * $ sleep 3 & sleep 6 & wait
  10740. * [1] 30934 sleep 3
  10741. * [2] 30935 sleep 6
  10742. * [1] Done sleep 3
  10743. * [2] Done sleep 6
  10744. * $ sleep 3 & sleep 6 & wait
  10745. * [1] 30936 sleep 3
  10746. * [2] 30937 sleep 6
  10747. * [1] Done sleep 3
  10748. * ^C <-- after ~4 sec from keyboard
  10749. * $
  10750. */
  10751. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10752. }
  10753. do {
  10754. pid_t pid = bb_strtou(*argv, NULL, 10);
  10755. if (errno || pid <= 0) {
  10756. #if ENABLE_HUSH_JOB
  10757. if (argv[0][0] == '%') {
  10758. struct pipe *wait_pipe;
  10759. ret = 127; /* bash compat for bad jobspecs */
  10760. wait_pipe = parse_jobspec(*argv);
  10761. if (wait_pipe) {
  10762. ret = job_exited_or_stopped(wait_pipe);
  10763. if (ret < 0) {
  10764. ret = wait_for_child_or_signal(wait_pipe, 0);
  10765. } else {
  10766. /* waiting on "last dead job" removes it */
  10767. clean_up_last_dead_job();
  10768. }
  10769. }
  10770. /* else: parse_jobspec() already emitted error msg */
  10771. continue;
  10772. }
  10773. #endif
  10774. /* mimic bash message */
  10775. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10776. ret = EXIT_FAILURE;
  10777. continue; /* bash checks all argv[] */
  10778. }
  10779. /* Do we have such child? */
  10780. ret = waitpid(pid, &status, WNOHANG);
  10781. if (ret < 0) {
  10782. /* No */
  10783. ret = 127;
  10784. if (errno == ECHILD) {
  10785. if (pid == G.last_bg_pid) {
  10786. /* "wait $!" but last bg task has already exited. Try:
  10787. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10788. * In bash it prints exitcode 0, then 3.
  10789. * In dash, it is 127.
  10790. */
  10791. ret = G.last_bg_pid_exitcode;
  10792. } else {
  10793. /* Example: "wait 1". mimic bash message */
  10794. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10795. }
  10796. } else {
  10797. /* ??? */
  10798. bb_perror_msg("wait %s", *argv);
  10799. }
  10800. continue; /* bash checks all argv[] */
  10801. }
  10802. if (ret == 0) {
  10803. /* Yes, and it still runs */
  10804. ret = wait_for_child_or_signal(NULL, pid);
  10805. } else {
  10806. /* Yes, and it just exited */
  10807. process_wait_result(NULL, pid, status);
  10808. ret = WEXITSTATUS(status);
  10809. if (WIFSIGNALED(status))
  10810. ret = 128 + WTERMSIG(status);
  10811. }
  10812. } while (*++argv);
  10813. return ret;
  10814. }
  10815. #endif
  10816. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10817. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10818. {
  10819. if (argv[1]) {
  10820. def = bb_strtou(argv[1], NULL, 10);
  10821. if (errno || def < def_min || argv[2]) {
  10822. bb_error_msg("%s: bad arguments", argv[0]);
  10823. def = UINT_MAX;
  10824. }
  10825. }
  10826. return def;
  10827. }
  10828. #endif
  10829. #if ENABLE_HUSH_LOOPS
  10830. static int FAST_FUNC builtin_break(char **argv)
  10831. {
  10832. unsigned depth;
  10833. if (G.depth_of_loop == 0) {
  10834. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10835. /* if we came from builtin_continue(), need to undo "= 1" */
  10836. G.flag_break_continue = 0;
  10837. return EXIT_SUCCESS; /* bash compat */
  10838. }
  10839. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10840. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10841. if (depth == UINT_MAX)
  10842. G.flag_break_continue = BC_BREAK;
  10843. if (G.depth_of_loop < depth)
  10844. G.depth_break_continue = G.depth_of_loop;
  10845. return EXIT_SUCCESS;
  10846. }
  10847. static int FAST_FUNC builtin_continue(char **argv)
  10848. {
  10849. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10850. return builtin_break(argv);
  10851. }
  10852. #endif
  10853. #if ENABLE_HUSH_FUNCTIONS
  10854. static int FAST_FUNC builtin_return(char **argv)
  10855. {
  10856. int rc;
  10857. if (G_flag_return_in_progress != -1) {
  10858. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10859. return EXIT_FAILURE; /* bash compat */
  10860. }
  10861. G_flag_return_in_progress = 1;
  10862. /* bash:
  10863. * out of range: wraps around at 256, does not error out
  10864. * non-numeric param:
  10865. * f() { false; return qwe; }; f; echo $?
  10866. * bash: return: qwe: numeric argument required <== we do this
  10867. * 255 <== we also do this
  10868. */
  10869. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10870. return rc;
  10871. }
  10872. #endif
  10873. #if ENABLE_HUSH_TIMES
  10874. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10875. {
  10876. static const uint8_t times_tbl[] ALIGN1 = {
  10877. ' ', offsetof(struct tms, tms_utime),
  10878. '\n', offsetof(struct tms, tms_stime),
  10879. ' ', offsetof(struct tms, tms_cutime),
  10880. '\n', offsetof(struct tms, tms_cstime),
  10881. 0
  10882. };
  10883. const uint8_t *p;
  10884. unsigned clk_tck;
  10885. struct tms buf;
  10886. clk_tck = bb_clk_tck();
  10887. times(&buf);
  10888. p = times_tbl;
  10889. do {
  10890. unsigned sec, frac;
  10891. unsigned long t;
  10892. t = *(clock_t *)(((char *) &buf) + p[1]);
  10893. sec = t / clk_tck;
  10894. frac = t % clk_tck;
  10895. printf("%um%u.%03us%c",
  10896. sec / 60, sec % 60,
  10897. (frac * 1000) / clk_tck,
  10898. p[0]);
  10899. p += 2;
  10900. } while (*p);
  10901. return EXIT_SUCCESS;
  10902. }
  10903. #endif
  10904. #if ENABLE_HUSH_MEMLEAK
  10905. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10906. {
  10907. void *p;
  10908. unsigned long l;
  10909. # ifdef M_TRIM_THRESHOLD
  10910. /* Optional. Reduces probability of false positives */
  10911. malloc_trim(0);
  10912. # endif
  10913. /* Crude attempt to find where "free memory" starts,
  10914. * sans fragmentation. */
  10915. p = malloc(240);
  10916. l = (unsigned long)p;
  10917. free(p);
  10918. p = malloc(3400);
  10919. if (l < (unsigned long)p) l = (unsigned long)p;
  10920. free(p);
  10921. # if 0 /* debug */
  10922. {
  10923. struct mallinfo mi = mallinfo();
  10924. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10925. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10926. }
  10927. # endif
  10928. if (!G.memleak_value)
  10929. G.memleak_value = l;
  10930. l -= G.memleak_value;
  10931. if ((long)l < 0)
  10932. l = 0;
  10933. l /= 1024;
  10934. if (l > 127)
  10935. l = 127;
  10936. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10937. return l;
  10938. }
  10939. #endif