hush.c 326 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899
  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: select SHELL_HUSH
  99. //config: help
  100. //config: hush is a small shell. It handles the normal flow control
  101. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  102. //config: case/esac. Redirections, here documents, $((arithmetic))
  103. //config: and functions are supported.
  104. //config:
  105. //config: It will compile and work on no-mmu systems.
  106. //config:
  107. //config: It does not handle select, aliases, tilde expansion,
  108. //config: &>file and >&file redirection of stdout+stderr.
  109. //config:
  110. // This option is visible (has a description) to make it possible to select
  111. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  112. //config:config SHELL_HUSH
  113. //config: bool "Internal shell for embedded script support"
  114. //config: default n
  115. //config:
  116. //config:# hush options
  117. //config:# It's only needed to get "nice" menuconfig indenting.
  118. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  119. //config:
  120. //config:config HUSH_BASH_COMPAT
  121. //config: bool "bash-compatible extensions"
  122. //config: default y
  123. //config: depends on SHELL_HUSH
  124. //config:
  125. //config:config HUSH_BRACE_EXPANSION
  126. //config: bool "Brace expansion"
  127. //config: default y
  128. //config: depends on HUSH_BASH_COMPAT
  129. //config: help
  130. //config: Enable {abc,def} extension.
  131. //config:
  132. //config:config HUSH_LINENO_VAR
  133. //config: bool "$LINENO variable"
  134. //config: default y
  135. //config: depends on HUSH_BASH_COMPAT
  136. //config:
  137. //config:config HUSH_BASH_SOURCE_CURDIR
  138. //config: bool "'source' and '.' builtins search current directory after $PATH"
  139. //config: default n # do not encourage non-standard behavior
  140. //config: depends on HUSH_BASH_COMPAT
  141. //config: help
  142. //config: This is not compliant with standards. Avoid if possible.
  143. //config:
  144. //config:config HUSH_INTERACTIVE
  145. //config: bool "Interactive mode"
  146. //config: default y
  147. //config: depends on SHELL_HUSH
  148. //config: help
  149. //config: Enable interactive mode (prompt and command editing).
  150. //config: Without this, hush simply reads and executes commands
  151. //config: from stdin just like a shell script from a file.
  152. //config: No prompt, no PS1/PS2 magic shell variables.
  153. //config:
  154. //config:config HUSH_SAVEHISTORY
  155. //config: bool "Save command history to .hush_history"
  156. //config: default y
  157. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  158. //config:
  159. //config:config HUSH_JOB
  160. //config: bool "Job control"
  161. //config: default y
  162. //config: depends on HUSH_INTERACTIVE
  163. //config: help
  164. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  165. //config: command (not entire shell), fg/bg builtins work. Without this option,
  166. //config: "cmd &" still works by simply spawning a process and immediately
  167. //config: prompting for next command (or executing next command in a script),
  168. //config: but no separate process group is formed.
  169. //config:
  170. //config:config HUSH_TICK
  171. //config: bool "Support command substitution"
  172. //config: default y
  173. //config: depends on SHELL_HUSH
  174. //config: help
  175. //config: Enable `command` and $(command).
  176. //config:
  177. //config:config HUSH_IF
  178. //config: bool "Support if/then/elif/else/fi"
  179. //config: default y
  180. //config: depends on SHELL_HUSH
  181. //config:
  182. //config:config HUSH_LOOPS
  183. //config: bool "Support for, while and until loops"
  184. //config: default y
  185. //config: depends on SHELL_HUSH
  186. //config:
  187. //config:config HUSH_CASE
  188. //config: bool "Support case ... esac statement"
  189. //config: default y
  190. //config: depends on SHELL_HUSH
  191. //config: help
  192. //config: Enable case ... esac statement. +400 bytes.
  193. //config:
  194. //config:config HUSH_FUNCTIONS
  195. //config: bool "Support funcname() { commands; } syntax"
  196. //config: default y
  197. //config: depends on SHELL_HUSH
  198. //config: help
  199. //config: Enable support for shell functions. +800 bytes.
  200. //config:
  201. //config:config HUSH_LOCAL
  202. //config: bool "local builtin"
  203. //config: default y
  204. //config: depends on HUSH_FUNCTIONS
  205. //config: help
  206. //config: Enable support for local variables in functions.
  207. //config:
  208. //config:config HUSH_RANDOM_SUPPORT
  209. //config: bool "Pseudorandom generator and $RANDOM variable"
  210. //config: default y
  211. //config: depends on SHELL_HUSH
  212. //config: help
  213. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  214. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  215. //config:
  216. //config:config HUSH_MODE_X
  217. //config: bool "Support 'hush -x' option and 'set -x' command"
  218. //config: default y
  219. //config: depends on SHELL_HUSH
  220. //config: help
  221. //config: This instructs hush to print commands before execution.
  222. //config: Adds ~300 bytes.
  223. //config:
  224. //config:config HUSH_ECHO
  225. //config: bool "echo builtin"
  226. //config: default y
  227. //config: depends on SHELL_HUSH
  228. //config:
  229. //config:config HUSH_PRINTF
  230. //config: bool "printf builtin"
  231. //config: default y
  232. //config: depends on SHELL_HUSH
  233. //config:
  234. //config:config HUSH_TEST
  235. //config: bool "test builtin"
  236. //config: default y
  237. //config: depends on SHELL_HUSH
  238. //config:
  239. //config:config HUSH_HELP
  240. //config: bool "help builtin"
  241. //config: default y
  242. //config: depends on SHELL_HUSH
  243. //config:
  244. //config:config HUSH_EXPORT
  245. //config: bool "export builtin"
  246. //config: default y
  247. //config: depends on SHELL_HUSH
  248. //config:
  249. //config:config HUSH_EXPORT_N
  250. //config: bool "Support 'export -n' option"
  251. //config: default y
  252. //config: depends on HUSH_EXPORT
  253. //config: help
  254. //config: export -n unexports variables. It is a bash extension.
  255. //config:
  256. //config:config HUSH_READONLY
  257. //config: bool "readonly builtin"
  258. //config: default y
  259. //config: depends on SHELL_HUSH
  260. //config: help
  261. //config: Enable support for read-only variables.
  262. //config:
  263. //config:config HUSH_KILL
  264. //config: bool "kill builtin (supports kill %jobspec)"
  265. //config: default y
  266. //config: depends on SHELL_HUSH
  267. //config:
  268. //config:config HUSH_WAIT
  269. //config: bool "wait builtin"
  270. //config: default y
  271. //config: depends on SHELL_HUSH
  272. //config:
  273. //config:config HUSH_COMMAND
  274. //config: bool "command builtin"
  275. //config: default y
  276. //config: depends on SHELL_HUSH
  277. //config:
  278. //config:config HUSH_TRAP
  279. //config: bool "trap builtin"
  280. //config: default y
  281. //config: depends on SHELL_HUSH
  282. //config:
  283. //config:config HUSH_TYPE
  284. //config: bool "type builtin"
  285. //config: default y
  286. //config: depends on SHELL_HUSH
  287. //config:
  288. //config:config HUSH_TIMES
  289. //config: bool "times builtin"
  290. //config: default y
  291. //config: depends on SHELL_HUSH
  292. //config:
  293. //config:config HUSH_READ
  294. //config: bool "read builtin"
  295. //config: default y
  296. //config: depends on SHELL_HUSH
  297. //config:
  298. //config:config HUSH_SET
  299. //config: bool "set builtin"
  300. //config: default y
  301. //config: depends on SHELL_HUSH
  302. //config:
  303. //config:config HUSH_UNSET
  304. //config: bool "unset builtin"
  305. //config: default y
  306. //config: depends on SHELL_HUSH
  307. //config:
  308. //config:config HUSH_ULIMIT
  309. //config: bool "ulimit builtin"
  310. //config: default y
  311. //config: depends on SHELL_HUSH
  312. //config:
  313. //config:config HUSH_UMASK
  314. //config: bool "umask builtin"
  315. //config: default y
  316. //config: depends on SHELL_HUSH
  317. //config:
  318. //config:config HUSH_GETOPTS
  319. //config: bool "getopts builtin"
  320. //config: default y
  321. //config: depends on SHELL_HUSH
  322. //config:
  323. //config:config HUSH_MEMLEAK
  324. //config: bool "memleak builtin (debugging)"
  325. //config: default n
  326. //config: depends on SHELL_HUSH
  327. //config:
  328. //config:endif # hush options
  329. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  330. // APPLET_ODDNAME:name main location suid_type help
  331. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  332. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  333. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  334. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  335. /* -i (interactive) is also accepted,
  336. * but does nothing, therefore not shown in help.
  337. * NOMMU-specific options are not meant to be used by users,
  338. * therefore we don't show them either.
  339. */
  340. //usage:#define hush_trivial_usage
  341. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  342. //usage:#define hush_full_usage "\n\n"
  343. //usage: "Unix shell interpreter"
  344. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  345. || defined(__APPLE__) \
  346. )
  347. # include <malloc.h> /* for malloc_trim */
  348. #endif
  349. #include <glob.h>
  350. /* #include <dmalloc.h> */
  351. #if ENABLE_HUSH_CASE
  352. # include <fnmatch.h>
  353. #endif
  354. #include <sys/times.h>
  355. #include <sys/utsname.h> /* for setting $HOSTNAME */
  356. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  357. #include "unicode.h"
  358. #include "shell_common.h"
  359. #include "math.h"
  360. #include "match.h"
  361. #if ENABLE_HUSH_RANDOM_SUPPORT
  362. # include "random.h"
  363. #else
  364. # define CLEAR_RANDOM_T(rnd) ((void)0)
  365. #endif
  366. #ifndef O_CLOEXEC
  367. # define O_CLOEXEC 0
  368. #endif
  369. #ifndef F_DUPFD_CLOEXEC
  370. # define F_DUPFD_CLOEXEC F_DUPFD
  371. #endif
  372. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  373. # include "embedded_scripts.h"
  374. #else
  375. # define NUM_SCRIPTS 0
  376. #endif
  377. /* So far, all bash compat is controlled by one config option */
  378. /* Separate defines document which part of code implements what */
  379. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  383. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  384. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  385. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  386. /* Build knobs */
  387. #define LEAK_HUNTING 0
  388. #define BUILD_AS_NOMMU 0
  389. /* Enable/disable sanity checks. Ok to enable in production,
  390. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  391. * Keeping 1 for now even in released versions.
  392. */
  393. #define HUSH_DEBUG 1
  394. /* Slightly bigger (+200 bytes), but faster hush.
  395. * So far it only enables a trick with counting SIGCHLDs and forks,
  396. * which allows us to do fewer waitpid's.
  397. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  398. * and therefore waitpid will return the same result as last time)
  399. */
  400. #define ENABLE_HUSH_FAST 0
  401. /* TODO: implement simplified code for users which do not need ${var%...} ops
  402. * So far ${var%...} ops are always enabled:
  403. */
  404. #define ENABLE_HUSH_DOLLAR_OPS 1
  405. #if BUILD_AS_NOMMU
  406. # undef BB_MMU
  407. # undef USE_FOR_NOMMU
  408. # undef USE_FOR_MMU
  409. # define BB_MMU 0
  410. # define USE_FOR_NOMMU(...) __VA_ARGS__
  411. # define USE_FOR_MMU(...)
  412. #endif
  413. #include "NUM_APPLETS.h"
  414. #if NUM_APPLETS == 1
  415. /* STANDALONE does not make sense, and won't compile */
  416. # undef CONFIG_FEATURE_SH_STANDALONE
  417. # undef ENABLE_FEATURE_SH_STANDALONE
  418. # undef IF_FEATURE_SH_STANDALONE
  419. # undef IF_NOT_FEATURE_SH_STANDALONE
  420. # define ENABLE_FEATURE_SH_STANDALONE 0
  421. # define IF_FEATURE_SH_STANDALONE(...)
  422. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  423. #endif
  424. #if !ENABLE_HUSH_INTERACTIVE
  425. # undef ENABLE_FEATURE_EDITING
  426. # define ENABLE_FEATURE_EDITING 0
  427. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  428. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  429. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  430. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  431. #endif
  432. /* Do we support ANY keywords? */
  433. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  434. # define HAS_KEYWORDS 1
  435. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  436. # define IF_HAS_NO_KEYWORDS(...)
  437. #else
  438. # define HAS_KEYWORDS 0
  439. # define IF_HAS_KEYWORDS(...)
  440. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  441. #endif
  442. /* If you comment out one of these below, it will be #defined later
  443. * to perform debug printfs to stderr: */
  444. #define debug_printf(...) do {} while (0)
  445. /* Finer-grained debug switches */
  446. #define debug_printf_parse(...) do {} while (0)
  447. #define debug_printf_heredoc(...) do {} while (0)
  448. #define debug_print_tree(a, b) do {} while (0)
  449. #define debug_printf_exec(...) do {} while (0)
  450. #define debug_printf_env(...) do {} while (0)
  451. #define debug_printf_jobs(...) do {} while (0)
  452. #define debug_printf_expand(...) do {} while (0)
  453. #define debug_printf_varexp(...) do {} while (0)
  454. #define debug_printf_glob(...) do {} while (0)
  455. #define debug_printf_redir(...) do {} while (0)
  456. #define debug_printf_list(...) do {} while (0)
  457. #define debug_printf_subst(...) do {} while (0)
  458. #define debug_printf_prompt(...) do {} while (0)
  459. #define debug_printf_clean(...) do {} while (0)
  460. #define ERR_PTR ((void*)(long)1)
  461. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  462. #define _SPECIAL_VARS_STR "_*@$!?#-"
  463. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  464. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  465. #if BASH_PATTERN_SUBST
  466. /* Support / and // replace ops */
  467. /* Note that // is stored as \ in "encoded" string representation */
  468. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  469. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  470. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  471. #else
  472. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  473. # define VAR_SUBST_OPS "%#:-=+?"
  474. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  475. #endif
  476. #define SPECIAL_VAR_SYMBOL_STR "\3"
  477. #define SPECIAL_VAR_SYMBOL 3
  478. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  479. #define SPECIAL_VAR_QUOTED_SVS 1
  480. struct variable;
  481. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  482. /* This supports saving pointers malloced in vfork child,
  483. * to be freed in the parent.
  484. */
  485. #if !BB_MMU
  486. typedef struct nommu_save_t {
  487. struct variable *old_vars;
  488. char **argv;
  489. char **argv_from_re_execing;
  490. } nommu_save_t;
  491. #endif
  492. enum {
  493. RES_NONE = 0,
  494. #if ENABLE_HUSH_IF
  495. RES_IF ,
  496. RES_THEN ,
  497. RES_ELIF ,
  498. RES_ELSE ,
  499. RES_FI ,
  500. #endif
  501. #if ENABLE_HUSH_LOOPS
  502. RES_FOR ,
  503. RES_WHILE ,
  504. RES_UNTIL ,
  505. RES_DO ,
  506. RES_DONE ,
  507. #endif
  508. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  509. RES_IN ,
  510. #endif
  511. #if ENABLE_HUSH_CASE
  512. RES_CASE ,
  513. /* three pseudo-keywords support contrived "case" syntax: */
  514. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  515. RES_MATCH , /* "word)" */
  516. RES_CASE_BODY, /* "this command is inside CASE" */
  517. RES_ESAC ,
  518. #endif
  519. RES_XXXX ,
  520. RES_SNTX
  521. };
  522. typedef struct o_string {
  523. char *data;
  524. int length; /* position where data is appended */
  525. int maxlen;
  526. int o_expflags;
  527. /* At least some part of the string was inside '' or "",
  528. * possibly empty one: word"", wo''rd etc. */
  529. smallint has_quoted_part;
  530. smallint has_empty_slot;
  531. smallint ended_in_ifs;
  532. } o_string;
  533. enum {
  534. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  535. EXP_FLAG_GLOB = 0x2,
  536. /* Protect newly added chars against globbing
  537. * by prepending \ to *, ?, [, \ */
  538. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  539. };
  540. /* Used for initialization: o_string foo = NULL_O_STRING; */
  541. #define NULL_O_STRING { NULL }
  542. #ifndef debug_printf_parse
  543. static const char *const assignment_flag[] = {
  544. "MAYBE_ASSIGNMENT",
  545. "DEFINITELY_ASSIGNMENT",
  546. "NOT_ASSIGNMENT",
  547. "WORD_IS_KEYWORD",
  548. };
  549. #endif
  550. /* We almost can use standard FILE api, but we need an ability to move
  551. * its fd when redirects coincide with it. No api exists for that
  552. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  553. * HFILE is our internal alternative. Only supports reading.
  554. * Since we now can, we incorporate linked list of all opened HFILEs
  555. * into the struct (used to be a separate mini-list).
  556. */
  557. typedef struct HFILE {
  558. char *cur;
  559. char *end;
  560. struct HFILE *next_hfile;
  561. int fd;
  562. char buf[1024];
  563. } HFILE;
  564. typedef struct in_str {
  565. const char *p;
  566. int peek_buf[2];
  567. int last_char;
  568. HFILE *file;
  569. } in_str;
  570. /* The descrip member of this structure is only used to make
  571. * debugging output pretty */
  572. static const struct {
  573. int mode;
  574. signed char default_fd;
  575. char descrip[3];
  576. } redir_table[] = {
  577. { O_RDONLY, 0, "<" },
  578. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  579. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  580. { O_CREAT|O_RDWR, 1, "<>" },
  581. { O_RDONLY, 0, "<<" },
  582. /* Should not be needed. Bogus default_fd helps in debugging */
  583. /* { O_RDONLY, 77, "<<" }, */
  584. };
  585. struct redir_struct {
  586. struct redir_struct *next;
  587. char *rd_filename; /* filename */
  588. int rd_fd; /* fd to redirect */
  589. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  590. int rd_dup;
  591. smallint rd_type; /* (enum redir_type) */
  592. /* note: for heredocs, rd_filename contains heredoc delimiter,
  593. * and subsequently heredoc itself; and rd_dup is a bitmask:
  594. * bit 0: do we need to trim leading tabs?
  595. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  596. */
  597. };
  598. typedef enum redir_type {
  599. REDIRECT_INPUT = 0,
  600. REDIRECT_OVERWRITE = 1,
  601. REDIRECT_APPEND = 2,
  602. REDIRECT_IO = 3,
  603. REDIRECT_HEREDOC = 4,
  604. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  605. REDIRFD_CLOSE = -3,
  606. REDIRFD_SYNTAX_ERR = -2,
  607. REDIRFD_TO_FILE = -1,
  608. /* otherwise, rd_fd is redirected to rd_dup */
  609. HEREDOC_SKIPTABS = 1,
  610. HEREDOC_QUOTED = 2,
  611. } redir_type;
  612. struct command {
  613. pid_t pid; /* 0 if exited */
  614. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  615. #if ENABLE_HUSH_LINENO_VAR
  616. unsigned lineno;
  617. #endif
  618. smallint cmd_type; /* CMD_xxx */
  619. #define CMD_NORMAL 0
  620. #define CMD_SUBSHELL 1
  621. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  622. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  623. * "export v=t*"
  624. */
  625. # define CMD_SINGLEWORD_NOGLOB 2
  626. #endif
  627. #if ENABLE_HUSH_FUNCTIONS
  628. # define CMD_FUNCDEF 3
  629. #endif
  630. smalluint cmd_exitcode;
  631. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  632. struct pipe *group;
  633. #if !BB_MMU
  634. char *group_as_string;
  635. #endif
  636. #if ENABLE_HUSH_FUNCTIONS
  637. struct function *child_func;
  638. /* This field is used to prevent a bug here:
  639. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  640. * When we execute "f1() {a;}" cmd, we create new function and clear
  641. * cmd->group, cmd->group_as_string, cmd->argv[0].
  642. * When we execute "f1() {b;}", we notice that f1 exists,
  643. * and that its "parent cmd" struct is still "alive",
  644. * we put those fields back into cmd->xxx
  645. * (struct function has ->parent_cmd ptr to facilitate that).
  646. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  647. * Without this trick, loop would execute a;b;b;b;...
  648. * instead of correct sequence a;b;a;b;...
  649. * When command is freed, it severs the link
  650. * (sets ->child_func->parent_cmd to NULL).
  651. */
  652. #endif
  653. char **argv; /* command name and arguments */
  654. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  655. * and on execution these are substituted with their values.
  656. * Substitution can make _several_ words out of one argv[n]!
  657. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  658. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  659. */
  660. struct redir_struct *redirects; /* I/O redirections */
  661. };
  662. /* Is there anything in this command at all? */
  663. #define IS_NULL_CMD(cmd) \
  664. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  665. struct pipe {
  666. struct pipe *next;
  667. int num_cmds; /* total number of commands in pipe */
  668. int alive_cmds; /* number of commands running (not exited) */
  669. int stopped_cmds; /* number of commands alive, but stopped */
  670. #if ENABLE_HUSH_JOB
  671. unsigned jobid; /* job number */
  672. pid_t pgrp; /* process group ID for the job */
  673. char *cmdtext; /* name of job */
  674. #endif
  675. struct command *cmds; /* array of commands in pipe */
  676. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  677. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  678. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  679. };
  680. typedef enum pipe_style {
  681. PIPE_SEQ = 0,
  682. PIPE_AND = 1,
  683. PIPE_OR = 2,
  684. PIPE_BG = 3,
  685. } pipe_style;
  686. /* Is there anything in this pipe at all? */
  687. #define IS_NULL_PIPE(pi) \
  688. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  689. /* This holds pointers to the various results of parsing */
  690. struct parse_context {
  691. /* linked list of pipes */
  692. struct pipe *list_head;
  693. /* last pipe (being constructed right now) */
  694. struct pipe *pipe;
  695. /* last command in pipe (being constructed right now) */
  696. struct command *command;
  697. /* last redirect in command->redirects list */
  698. struct redir_struct *pending_redirect;
  699. o_string word;
  700. #if !BB_MMU
  701. o_string as_string;
  702. #endif
  703. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  704. #if HAS_KEYWORDS
  705. smallint ctx_res_w;
  706. smallint ctx_inverted; /* "! cmd | cmd" */
  707. #if ENABLE_HUSH_CASE
  708. smallint ctx_dsemicolon; /* ";;" seen */
  709. #endif
  710. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  711. int old_flag;
  712. /* group we are enclosed in:
  713. * example: "if pipe1; pipe2; then pipe3; fi"
  714. * when we see "if" or "then", we malloc and copy current context,
  715. * and make ->stack point to it. then we parse pipeN.
  716. * when closing "then" / fi" / whatever is found,
  717. * we move list_head into ->stack->command->group,
  718. * copy ->stack into current context, and delete ->stack.
  719. * (parsing of { list } and ( list ) doesn't use this method)
  720. */
  721. struct parse_context *stack;
  722. #endif
  723. };
  724. enum {
  725. MAYBE_ASSIGNMENT = 0,
  726. DEFINITELY_ASSIGNMENT = 1,
  727. NOT_ASSIGNMENT = 2,
  728. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  729. WORD_IS_KEYWORD = 3,
  730. };
  731. /* On program start, environ points to initial environment.
  732. * putenv adds new pointers into it, unsetenv removes them.
  733. * Neither of these (de)allocates the strings.
  734. * setenv allocates new strings in malloc space and does putenv,
  735. * and thus setenv is unusable (leaky) for shell's purposes */
  736. #define setenv(...) setenv_is_leaky_dont_use()
  737. struct variable {
  738. struct variable *next;
  739. char *varstr; /* points to "name=" portion */
  740. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  741. uint16_t var_nest_level;
  742. smallint flg_export; /* putenv should be done on this var */
  743. smallint flg_read_only;
  744. };
  745. enum {
  746. BC_BREAK = 1,
  747. BC_CONTINUE = 2,
  748. };
  749. #if ENABLE_HUSH_FUNCTIONS
  750. struct function {
  751. struct function *next;
  752. char *name;
  753. struct command *parent_cmd;
  754. struct pipe *body;
  755. # if !BB_MMU
  756. char *body_as_string;
  757. # endif
  758. };
  759. #endif
  760. /* set -/+o OPT support. (TODO: make it optional)
  761. * bash supports the following opts:
  762. * allexport off
  763. * braceexpand on
  764. * emacs on
  765. * errexit off
  766. * errtrace off
  767. * functrace off
  768. * hashall on
  769. * histexpand off
  770. * history on
  771. * ignoreeof off
  772. * interactive-comments on
  773. * keyword off
  774. * monitor on
  775. * noclobber off
  776. * noexec off
  777. * noglob off
  778. * nolog off
  779. * notify off
  780. * nounset off
  781. * onecmd off
  782. * physical off
  783. * pipefail off
  784. * posix off
  785. * privileged off
  786. * verbose off
  787. * vi off
  788. * xtrace off
  789. */
  790. static const char o_opt_strings[] ALIGN1 =
  791. "pipefail\0"
  792. "noexec\0"
  793. "errexit\0"
  794. #if ENABLE_HUSH_MODE_X
  795. "xtrace\0"
  796. #endif
  797. ;
  798. enum {
  799. OPT_O_PIPEFAIL,
  800. OPT_O_NOEXEC,
  801. OPT_O_ERREXIT,
  802. #if ENABLE_HUSH_MODE_X
  803. OPT_O_XTRACE,
  804. #endif
  805. NUM_OPT_O
  806. };
  807. /* "Globals" within this file */
  808. /* Sorted roughly by size (smaller offsets == smaller code) */
  809. struct globals {
  810. /* interactive_fd != 0 means we are an interactive shell.
  811. * If we are, then saved_tty_pgrp can also be != 0, meaning
  812. * that controlling tty is available. With saved_tty_pgrp == 0,
  813. * job control still works, but terminal signals
  814. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  815. * process groups can only be created with "cmd &".
  816. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  817. * to give tty to the foreground process group,
  818. * and will take it back when the group is stopped (^Z)
  819. * or killed (^C).
  820. */
  821. #if ENABLE_HUSH_INTERACTIVE
  822. /* 'interactive_fd' is a fd# open to ctty, if we have one
  823. * _AND_ if we decided to act interactively */
  824. int interactive_fd;
  825. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  826. # define G_interactive_fd (G.interactive_fd)
  827. #else
  828. # define G_interactive_fd 0
  829. #endif
  830. #if ENABLE_FEATURE_EDITING
  831. line_input_t *line_input_state;
  832. #endif
  833. pid_t root_pid;
  834. pid_t root_ppid;
  835. pid_t last_bg_pid;
  836. #if ENABLE_HUSH_RANDOM_SUPPORT
  837. random_t random_gen;
  838. #endif
  839. #if ENABLE_HUSH_JOB
  840. int run_list_level;
  841. unsigned last_jobid;
  842. pid_t saved_tty_pgrp;
  843. struct pipe *job_list;
  844. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  845. #else
  846. # define G_saved_tty_pgrp 0
  847. #endif
  848. /* How deeply are we in context where "set -e" is ignored */
  849. int errexit_depth;
  850. /* "set -e" rules (do we follow them correctly?):
  851. * Exit if pipe, list, or compound command exits with a non-zero status.
  852. * Shell does not exit if failed command is part of condition in
  853. * if/while, part of && or || list except the last command, any command
  854. * in a pipe but the last, or if the command's return value is being
  855. * inverted with !. If a compound command other than a subshell returns a
  856. * non-zero status because a command failed while -e was being ignored, the
  857. * shell does not exit. A trap on ERR, if set, is executed before the shell
  858. * exits [ERR is a bashism].
  859. *
  860. * If a compound command or function executes in a context where -e is
  861. * ignored, none of the commands executed within are affected by the -e
  862. * setting. If a compound command or function sets -e while executing in a
  863. * context where -e is ignored, that setting does not have any effect until
  864. * the compound command or the command containing the function call completes.
  865. */
  866. char o_opt[NUM_OPT_O];
  867. #if ENABLE_HUSH_MODE_X
  868. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  869. #else
  870. # define G_x_mode 0
  871. #endif
  872. char opt_s;
  873. char opt_c;
  874. #if ENABLE_HUSH_INTERACTIVE
  875. smallint promptmode; /* 0: PS1, 1: PS2 */
  876. #endif
  877. smallint flag_SIGINT;
  878. #if ENABLE_HUSH_LOOPS
  879. smallint flag_break_continue;
  880. #endif
  881. #if ENABLE_HUSH_FUNCTIONS
  882. /* 0: outside of a function (or sourced file)
  883. * -1: inside of a function, ok to use return builtin
  884. * 1: return is invoked, skip all till end of func
  885. */
  886. smallint flag_return_in_progress;
  887. # define G_flag_return_in_progress (G.flag_return_in_progress)
  888. #else
  889. # define G_flag_return_in_progress 0
  890. #endif
  891. smallint exiting; /* used to prevent EXIT trap recursion */
  892. /* These support $? */
  893. smalluint last_exitcode;
  894. smalluint expand_exitcode;
  895. smalluint last_bg_pid_exitcode;
  896. #if ENABLE_HUSH_SET
  897. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  898. smalluint global_args_malloced;
  899. # define G_global_args_malloced (G.global_args_malloced)
  900. #else
  901. # define G_global_args_malloced 0
  902. #endif
  903. #if ENABLE_HUSH_BASH_COMPAT
  904. int dead_job_exitcode; /* for "wait -n" */
  905. #endif
  906. /* how many non-NULL argv's we have. NB: $# + 1 */
  907. int global_argc;
  908. char **global_argv;
  909. #if !BB_MMU
  910. char *argv0_for_re_execing;
  911. #endif
  912. #if ENABLE_HUSH_LOOPS
  913. unsigned depth_break_continue;
  914. unsigned depth_of_loop;
  915. #endif
  916. #if ENABLE_HUSH_GETOPTS
  917. unsigned getopt_count;
  918. #endif
  919. const char *ifs;
  920. char *ifs_whitespace; /* = G.ifs or malloced */
  921. const char *cwd;
  922. struct variable *top_var;
  923. char **expanded_assignments;
  924. struct variable **shadowed_vars_pp;
  925. unsigned var_nest_level;
  926. #if ENABLE_HUSH_FUNCTIONS
  927. # if ENABLE_HUSH_LOCAL
  928. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  929. # endif
  930. struct function *top_func;
  931. #endif
  932. /* Signal and trap handling */
  933. #if ENABLE_HUSH_FAST
  934. unsigned count_SIGCHLD;
  935. unsigned handled_SIGCHLD;
  936. smallint we_have_children;
  937. #endif
  938. #if ENABLE_HUSH_LINENO_VAR
  939. unsigned parse_lineno;
  940. unsigned execute_lineno;
  941. #endif
  942. HFILE *HFILE_list;
  943. HFILE *HFILE_stdin;
  944. /* Which signals have non-DFL handler (even with no traps set)?
  945. * Set at the start to:
  946. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  947. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  948. * The rest is cleared right before execv syscalls.
  949. * Other than these two times, never modified.
  950. */
  951. unsigned special_sig_mask;
  952. #if ENABLE_HUSH_JOB
  953. unsigned fatal_sig_mask;
  954. # define G_fatal_sig_mask (G.fatal_sig_mask)
  955. #else
  956. # define G_fatal_sig_mask 0
  957. #endif
  958. #if ENABLE_HUSH_TRAP
  959. int pre_trap_exitcode;
  960. # if ENABLE_HUSH_FUNCTIONS
  961. int return_exitcode;
  962. # endif
  963. char **traps; /* char *traps[NSIG] */
  964. # define G_traps G.traps
  965. #else
  966. # define G_traps ((char**)NULL)
  967. #endif
  968. sigset_t pending_set;
  969. #if ENABLE_HUSH_MEMLEAK
  970. unsigned long memleak_value;
  971. #endif
  972. #if ENABLE_HUSH_MODE_X
  973. unsigned x_mode_depth;
  974. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  975. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  976. * for all subsequent output.
  977. */
  978. int x_mode_fd;
  979. o_string x_mode_buf;
  980. #endif
  981. #if HUSH_DEBUG >= 2
  982. int debug_indent;
  983. #endif
  984. struct sigaction sa;
  985. char optstring_buf[sizeof("eixcs")];
  986. #if BASH_EPOCH_VARS
  987. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  988. #endif
  989. #if ENABLE_FEATURE_EDITING
  990. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  991. #endif
  992. };
  993. #define G (*ptr_to_globals)
  994. /* Not #defining name to G.name - this quickly gets unwieldy
  995. * (too many defines). Also, I actually prefer to see when a variable
  996. * is global, thus "G." prefix is a useful hint */
  997. #define INIT_G() do { \
  998. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  999. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1000. sigfillset(&G.sa.sa_mask); \
  1001. G.sa.sa_flags = SA_RESTART; \
  1002. } while (0)
  1003. /* Function prototypes for builtins */
  1004. static int builtin_cd(char **argv) FAST_FUNC;
  1005. #if ENABLE_HUSH_ECHO
  1006. static int builtin_echo(char **argv) FAST_FUNC;
  1007. #endif
  1008. static int builtin_eval(char **argv) FAST_FUNC;
  1009. static int builtin_exec(char **argv) FAST_FUNC;
  1010. static int builtin_exit(char **argv) FAST_FUNC;
  1011. #if ENABLE_HUSH_EXPORT
  1012. static int builtin_export(char **argv) FAST_FUNC;
  1013. #endif
  1014. #if ENABLE_HUSH_READONLY
  1015. static int builtin_readonly(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_JOB
  1018. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1019. static int builtin_jobs(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_GETOPTS
  1022. static int builtin_getopts(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_HELP
  1025. static int builtin_help(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1028. static int builtin_history(char **argv) FAST_FUNC;
  1029. #endif
  1030. #if ENABLE_HUSH_LOCAL
  1031. static int builtin_local(char **argv) FAST_FUNC;
  1032. #endif
  1033. #if ENABLE_HUSH_MEMLEAK
  1034. static int builtin_memleak(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_PRINTF
  1037. static int builtin_printf(char **argv) FAST_FUNC;
  1038. #endif
  1039. static int builtin_pwd(char **argv) FAST_FUNC;
  1040. #if ENABLE_HUSH_READ
  1041. static int builtin_read(char **argv) FAST_FUNC;
  1042. #endif
  1043. #if ENABLE_HUSH_SET
  1044. static int builtin_set(char **argv) FAST_FUNC;
  1045. #endif
  1046. static int builtin_shift(char **argv) FAST_FUNC;
  1047. static int builtin_source(char **argv) FAST_FUNC;
  1048. #if ENABLE_HUSH_TEST || BASH_TEST2
  1049. static int builtin_test(char **argv) FAST_FUNC;
  1050. #endif
  1051. #if ENABLE_HUSH_TRAP
  1052. static int builtin_trap(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_TYPE
  1055. static int builtin_type(char **argv) FAST_FUNC;
  1056. #endif
  1057. #if ENABLE_HUSH_TIMES
  1058. static int builtin_times(char **argv) FAST_FUNC;
  1059. #endif
  1060. static int builtin_true(char **argv) FAST_FUNC;
  1061. #if ENABLE_HUSH_UMASK
  1062. static int builtin_umask(char **argv) FAST_FUNC;
  1063. #endif
  1064. #if ENABLE_HUSH_UNSET
  1065. static int builtin_unset(char **argv) FAST_FUNC;
  1066. #endif
  1067. #if ENABLE_HUSH_KILL
  1068. static int builtin_kill(char **argv) FAST_FUNC;
  1069. #endif
  1070. #if ENABLE_HUSH_WAIT
  1071. static int builtin_wait(char **argv) FAST_FUNC;
  1072. #endif
  1073. #if ENABLE_HUSH_LOOPS
  1074. static int builtin_break(char **argv) FAST_FUNC;
  1075. static int builtin_continue(char **argv) FAST_FUNC;
  1076. #endif
  1077. #if ENABLE_HUSH_FUNCTIONS
  1078. static int builtin_return(char **argv) FAST_FUNC;
  1079. #endif
  1080. /* Table of built-in functions. They can be forked or not, depending on
  1081. * context: within pipes, they fork. As simple commands, they do not.
  1082. * When used in non-forking context, they can change global variables
  1083. * in the parent shell process. If forked, of course they cannot.
  1084. * For example, 'unset foo | whatever' will parse and run, but foo will
  1085. * still be set at the end. */
  1086. struct built_in_command {
  1087. const char *b_cmd;
  1088. int (*b_function)(char **argv) FAST_FUNC;
  1089. #if ENABLE_HUSH_HELP
  1090. const char *b_descr;
  1091. # define BLTIN(cmd, func, help) { cmd, func, help }
  1092. #else
  1093. # define BLTIN(cmd, func, help) { cmd, func }
  1094. #endif
  1095. };
  1096. static const struct built_in_command bltins1[] = {
  1097. BLTIN("." , builtin_source , "Run commands in file"),
  1098. BLTIN(":" , builtin_true , NULL),
  1099. #if ENABLE_HUSH_JOB
  1100. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1101. #endif
  1102. #if ENABLE_HUSH_LOOPS
  1103. BLTIN("break" , builtin_break , "Exit loop"),
  1104. #endif
  1105. BLTIN("cd" , builtin_cd , "Change directory"),
  1106. #if ENABLE_HUSH_LOOPS
  1107. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1108. #endif
  1109. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1110. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1111. BLTIN("exit" , builtin_exit , NULL),
  1112. #if ENABLE_HUSH_EXPORT
  1113. BLTIN("export" , builtin_export , "Set environment variables"),
  1114. #endif
  1115. #if ENABLE_HUSH_JOB
  1116. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1117. #endif
  1118. #if ENABLE_HUSH_GETOPTS
  1119. BLTIN("getopts" , builtin_getopts , NULL),
  1120. #endif
  1121. #if ENABLE_HUSH_HELP
  1122. BLTIN("help" , builtin_help , NULL),
  1123. #endif
  1124. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1125. BLTIN("history" , builtin_history , "Show history"),
  1126. #endif
  1127. #if ENABLE_HUSH_JOB
  1128. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1129. #endif
  1130. #if ENABLE_HUSH_KILL
  1131. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1132. #endif
  1133. #if ENABLE_HUSH_LOCAL
  1134. BLTIN("local" , builtin_local , "Set local variables"),
  1135. #endif
  1136. #if ENABLE_HUSH_MEMLEAK
  1137. BLTIN("memleak" , builtin_memleak , NULL),
  1138. #endif
  1139. #if ENABLE_HUSH_READ
  1140. BLTIN("read" , builtin_read , "Input into variable"),
  1141. #endif
  1142. #if ENABLE_HUSH_READONLY
  1143. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1144. #endif
  1145. #if ENABLE_HUSH_FUNCTIONS
  1146. BLTIN("return" , builtin_return , "Return from function"),
  1147. #endif
  1148. #if ENABLE_HUSH_SET
  1149. BLTIN("set" , builtin_set , "Set positional parameters"),
  1150. #endif
  1151. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1152. #if BASH_SOURCE
  1153. BLTIN("source" , builtin_source , NULL),
  1154. #endif
  1155. #if ENABLE_HUSH_TIMES
  1156. BLTIN("times" , builtin_times , NULL),
  1157. #endif
  1158. #if ENABLE_HUSH_TRAP
  1159. BLTIN("trap" , builtin_trap , "Trap signals"),
  1160. #endif
  1161. BLTIN("true" , builtin_true , NULL),
  1162. #if ENABLE_HUSH_TYPE
  1163. BLTIN("type" , builtin_type , "Show command type"),
  1164. #endif
  1165. #if ENABLE_HUSH_ULIMIT
  1166. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1167. #endif
  1168. #if ENABLE_HUSH_UMASK
  1169. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1170. #endif
  1171. #if ENABLE_HUSH_UNSET
  1172. BLTIN("unset" , builtin_unset , "Unset variables"),
  1173. #endif
  1174. #if ENABLE_HUSH_WAIT
  1175. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1176. #endif
  1177. };
  1178. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1179. * (it's cheaper to run an external program in this case):
  1180. */
  1181. static const struct built_in_command bltins2[] = {
  1182. #if ENABLE_HUSH_TEST
  1183. BLTIN("[" , builtin_test , NULL),
  1184. #endif
  1185. #if BASH_TEST2
  1186. BLTIN("[[" , builtin_test , NULL),
  1187. #endif
  1188. #if ENABLE_HUSH_ECHO
  1189. BLTIN("echo" , builtin_echo , NULL),
  1190. #endif
  1191. #if ENABLE_HUSH_PRINTF
  1192. BLTIN("printf" , builtin_printf , NULL),
  1193. #endif
  1194. BLTIN("pwd" , builtin_pwd , NULL),
  1195. #if ENABLE_HUSH_TEST
  1196. BLTIN("test" , builtin_test , NULL),
  1197. #endif
  1198. };
  1199. /* Debug printouts.
  1200. */
  1201. #if HUSH_DEBUG >= 2
  1202. /* prevent disasters with G.debug_indent < 0 */
  1203. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1204. # define debug_enter() (G.debug_indent++)
  1205. # define debug_leave() (G.debug_indent--)
  1206. #else
  1207. # define indent() ((void)0)
  1208. # define debug_enter() ((void)0)
  1209. # define debug_leave() ((void)0)
  1210. #endif
  1211. #ifndef debug_printf
  1212. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. #endif
  1214. #ifndef debug_printf_parse
  1215. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1216. #endif
  1217. #ifndef debug_printf_heredoc
  1218. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. #endif
  1220. #ifndef debug_printf_exec
  1221. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1222. #endif
  1223. #ifndef debug_printf_env
  1224. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_jobs
  1227. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_JOBS 1
  1229. #else
  1230. # define DEBUG_JOBS 0
  1231. #endif
  1232. #ifndef debug_printf_expand
  1233. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. # define DEBUG_EXPAND 1
  1235. #else
  1236. # define DEBUG_EXPAND 0
  1237. #endif
  1238. #ifndef debug_printf_varexp
  1239. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_glob
  1242. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. # define DEBUG_GLOB 1
  1244. #else
  1245. # define DEBUG_GLOB 0
  1246. #endif
  1247. #ifndef debug_printf_redir
  1248. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1249. #endif
  1250. #ifndef debug_printf_list
  1251. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1252. #endif
  1253. #ifndef debug_printf_subst
  1254. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1255. #endif
  1256. #ifndef debug_printf_prompt
  1257. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1258. #endif
  1259. #ifndef debug_printf_clean
  1260. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1261. # define DEBUG_CLEAN 1
  1262. #else
  1263. # define DEBUG_CLEAN 0
  1264. #endif
  1265. #if DEBUG_EXPAND
  1266. static void debug_print_strings(const char *prefix, char **vv)
  1267. {
  1268. indent();
  1269. fdprintf(2, "%s:\n", prefix);
  1270. while (*vv)
  1271. fdprintf(2, " '%s'\n", *vv++);
  1272. }
  1273. #else
  1274. # define debug_print_strings(prefix, vv) ((void)0)
  1275. #endif
  1276. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1277. */
  1278. #if LEAK_HUNTING
  1279. static void *xxmalloc(int lineno, size_t size)
  1280. {
  1281. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1282. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1283. return ptr;
  1284. }
  1285. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1286. {
  1287. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1288. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1289. return ptr;
  1290. }
  1291. static char *xxstrdup(int lineno, const char *str)
  1292. {
  1293. char *ptr = xstrdup(str);
  1294. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1295. return ptr;
  1296. }
  1297. static void xxfree(void *ptr)
  1298. {
  1299. fdprintf(2, "free %p\n", ptr);
  1300. free(ptr);
  1301. }
  1302. # define xmalloc(s) xxmalloc(__LINE__, s)
  1303. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1304. # define xstrdup(s) xxstrdup(__LINE__, s)
  1305. # define free(p) xxfree(p)
  1306. #endif
  1307. /* Syntax and runtime errors. They always abort scripts.
  1308. * In interactive use they usually discard unparsed and/or unexecuted commands
  1309. * and return to the prompt.
  1310. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1311. */
  1312. #if HUSH_DEBUG < 2
  1313. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1314. # define syntax_error(lineno, msg) syntax_error(msg)
  1315. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1316. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1317. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1318. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1319. #endif
  1320. static void die_if_script(void)
  1321. {
  1322. if (!G_interactive_fd) {
  1323. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1324. xfunc_error_retval = G.last_exitcode;
  1325. xfunc_die();
  1326. }
  1327. }
  1328. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1329. {
  1330. va_list p;
  1331. #if HUSH_DEBUG >= 2
  1332. bb_error_msg("hush.c:%u", lineno);
  1333. #endif
  1334. va_start(p, fmt);
  1335. bb_verror_msg(fmt, p, NULL);
  1336. va_end(p);
  1337. die_if_script();
  1338. }
  1339. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1340. {
  1341. if (msg)
  1342. bb_error_msg("syntax error: %s", msg);
  1343. else
  1344. bb_simple_error_msg("syntax error");
  1345. die_if_script();
  1346. }
  1347. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1348. {
  1349. bb_error_msg("syntax error at '%s'", msg);
  1350. die_if_script();
  1351. }
  1352. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1353. {
  1354. bb_error_msg("syntax error: unterminated %s", s);
  1355. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1356. // die_if_script();
  1357. }
  1358. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1359. {
  1360. char msg[2] = { ch, '\0' };
  1361. syntax_error_unterm_str(lineno, msg);
  1362. }
  1363. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1364. {
  1365. char msg[2];
  1366. msg[0] = ch;
  1367. msg[1] = '\0';
  1368. #if HUSH_DEBUG >= 2
  1369. bb_error_msg("hush.c:%u", lineno);
  1370. #endif
  1371. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1372. die_if_script();
  1373. }
  1374. #if HUSH_DEBUG < 2
  1375. # undef msg_and_die_if_script
  1376. # undef syntax_error
  1377. # undef syntax_error_at
  1378. # undef syntax_error_unterm_ch
  1379. # undef syntax_error_unterm_str
  1380. # undef syntax_error_unexpected_ch
  1381. #else
  1382. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1383. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1384. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1385. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1386. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1387. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1388. #endif
  1389. /* Utility functions
  1390. */
  1391. /* Replace each \x with x in place, return ptr past NUL. */
  1392. static char *unbackslash(char *src)
  1393. {
  1394. char *dst = src = strchrnul(src, '\\');
  1395. while (1) {
  1396. if (*src == '\\') {
  1397. src++;
  1398. if (*src != '\0') {
  1399. /* \x -> x */
  1400. *dst++ = *src++;
  1401. continue;
  1402. }
  1403. /* else: "\<nul>". Do not delete this backslash.
  1404. * Testcase: eval 'echo ok\'
  1405. */
  1406. *dst++ = '\\';
  1407. /* fallthrough */
  1408. }
  1409. if ((*dst++ = *src++) == '\0')
  1410. break;
  1411. }
  1412. return dst;
  1413. }
  1414. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1415. {
  1416. int i;
  1417. unsigned count1;
  1418. unsigned count2;
  1419. char **v;
  1420. v = strings;
  1421. count1 = 0;
  1422. if (v) {
  1423. while (*v) {
  1424. count1++;
  1425. v++;
  1426. }
  1427. }
  1428. count2 = 0;
  1429. v = add;
  1430. while (*v) {
  1431. count2++;
  1432. v++;
  1433. }
  1434. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1435. v[count1 + count2] = NULL;
  1436. i = count2;
  1437. while (--i >= 0)
  1438. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1439. return v;
  1440. }
  1441. #if LEAK_HUNTING
  1442. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1443. {
  1444. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1445. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1446. return ptr;
  1447. }
  1448. #define add_strings_to_strings(strings, add, need_to_dup) \
  1449. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1450. #endif
  1451. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1452. static char **add_string_to_strings(char **strings, char *add)
  1453. {
  1454. char *v[2];
  1455. v[0] = add;
  1456. v[1] = NULL;
  1457. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1458. }
  1459. #if LEAK_HUNTING
  1460. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1461. {
  1462. char **ptr = add_string_to_strings(strings, add);
  1463. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1464. return ptr;
  1465. }
  1466. #define add_string_to_strings(strings, add) \
  1467. xx_add_string_to_strings(__LINE__, strings, add)
  1468. #endif
  1469. static void free_strings(char **strings)
  1470. {
  1471. char **v;
  1472. if (!strings)
  1473. return;
  1474. v = strings;
  1475. while (*v) {
  1476. free(*v);
  1477. v++;
  1478. }
  1479. free(strings);
  1480. }
  1481. static int dup_CLOEXEC(int fd, int avoid_fd)
  1482. {
  1483. int newfd;
  1484. repeat:
  1485. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1486. if (newfd >= 0) {
  1487. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1488. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1489. } else { /* newfd < 0 */
  1490. if (errno == EBUSY)
  1491. goto repeat;
  1492. if (errno == EINTR)
  1493. goto repeat;
  1494. }
  1495. return newfd;
  1496. }
  1497. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1498. {
  1499. int newfd;
  1500. repeat:
  1501. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1502. if (newfd < 0) {
  1503. if (errno == EBUSY)
  1504. goto repeat;
  1505. if (errno == EINTR)
  1506. goto repeat;
  1507. /* fd was not open? */
  1508. if (errno == EBADF)
  1509. return fd;
  1510. xfunc_die();
  1511. }
  1512. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1513. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1514. close(fd);
  1515. return newfd;
  1516. }
  1517. /* Manipulating HFILEs */
  1518. static HFILE *hfopen(const char *name)
  1519. {
  1520. HFILE *fp;
  1521. int fd;
  1522. fd = STDIN_FILENO;
  1523. if (name) {
  1524. fd = open(name, O_RDONLY | O_CLOEXEC);
  1525. if (fd < 0)
  1526. return NULL;
  1527. if (O_CLOEXEC == 0) /* ancient libc */
  1528. close_on_exec_on(fd);
  1529. }
  1530. fp = xmalloc(sizeof(*fp));
  1531. if (name == NULL)
  1532. G.HFILE_stdin = fp;
  1533. fp->fd = fd;
  1534. fp->cur = fp->end = fp->buf;
  1535. fp->next_hfile = G.HFILE_list;
  1536. G.HFILE_list = fp;
  1537. return fp;
  1538. }
  1539. static void hfclose(HFILE *fp)
  1540. {
  1541. HFILE **pp = &G.HFILE_list;
  1542. while (*pp) {
  1543. HFILE *cur = *pp;
  1544. if (cur == fp) {
  1545. *pp = cur->next_hfile;
  1546. break;
  1547. }
  1548. pp = &cur->next_hfile;
  1549. }
  1550. if (fp->fd >= 0)
  1551. close(fp->fd);
  1552. free(fp);
  1553. }
  1554. static int refill_HFILE_and_getc(HFILE *fp)
  1555. {
  1556. int n;
  1557. if (fp->fd < 0) {
  1558. /* Already saw EOF */
  1559. return EOF;
  1560. }
  1561. /* Try to buffer more input */
  1562. fp->cur = fp->buf;
  1563. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1564. if (n < 0) {
  1565. bb_simple_perror_msg("read error");
  1566. n = 0;
  1567. }
  1568. fp->end = fp->buf + n;
  1569. if (n == 0) {
  1570. /* EOF/error */
  1571. close(fp->fd);
  1572. fp->fd = -1;
  1573. return EOF;
  1574. }
  1575. return (unsigned char)(*fp->cur++);
  1576. }
  1577. /* Inlined for common case of non-empty buffer.
  1578. */
  1579. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1580. {
  1581. if (fp->cur < fp->end)
  1582. return (unsigned char)(*fp->cur++);
  1583. /* Buffer empty */
  1584. return refill_HFILE_and_getc(fp);
  1585. }
  1586. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1587. {
  1588. HFILE *fl = G.HFILE_list;
  1589. while (fl) {
  1590. if (fd == fl->fd) {
  1591. /* We use it only on script files, they are all CLOEXEC */
  1592. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1593. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1594. return 1; /* "found and moved" */
  1595. }
  1596. fl = fl->next_hfile;
  1597. }
  1598. #if ENABLE_HUSH_MODE_X
  1599. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1600. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1601. return 1; /* "found and moved" */
  1602. }
  1603. #endif
  1604. return 0; /* "not in the list" */
  1605. }
  1606. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1607. static void close_all_HFILE_list(void)
  1608. {
  1609. HFILE *fl = G.HFILE_list;
  1610. while (fl) {
  1611. /* hfclose would also free HFILE object.
  1612. * It is disastrous if we share memory with a vforked parent.
  1613. * I'm not sure we never come here after vfork.
  1614. * Therefore just close fd, nothing more.
  1615. *
  1616. * ">" instead of ">=": we don't close fd#0,
  1617. * interactive shell uses hfopen(NULL) as stdin input
  1618. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1619. * If we'd close it here, then e.g. interactive "set | sort"
  1620. * with NOFORKed sort, would have sort's input fd closed.
  1621. */
  1622. if (fl->fd > 0)
  1623. /*hfclose(fl); - unsafe */
  1624. close(fl->fd);
  1625. fl = fl->next_hfile;
  1626. }
  1627. }
  1628. #endif
  1629. static int fd_in_HFILEs(int fd)
  1630. {
  1631. HFILE *fl = G.HFILE_list;
  1632. while (fl) {
  1633. if (fl->fd == fd)
  1634. return 1;
  1635. fl = fl->next_hfile;
  1636. }
  1637. return 0;
  1638. }
  1639. /* Helpers for setting new $n and restoring them back
  1640. */
  1641. typedef struct save_arg_t {
  1642. char *sv_argv0;
  1643. char **sv_g_argv;
  1644. int sv_g_argc;
  1645. IF_HUSH_SET(smallint sv_g_malloced;)
  1646. } save_arg_t;
  1647. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1648. {
  1649. sv->sv_argv0 = argv[0];
  1650. sv->sv_g_argv = G.global_argv;
  1651. sv->sv_g_argc = G.global_argc;
  1652. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1653. argv[0] = G.global_argv[0]; /* retain $0 */
  1654. G.global_argv = argv;
  1655. IF_HUSH_SET(G.global_args_malloced = 0;)
  1656. G.global_argc = 1 + string_array_len(argv + 1);
  1657. }
  1658. static void restore_G_args(save_arg_t *sv, char **argv)
  1659. {
  1660. #if ENABLE_HUSH_SET
  1661. if (G.global_args_malloced) {
  1662. /* someone ran "set -- arg1 arg2 ...", undo */
  1663. char **pp = G.global_argv;
  1664. while (*++pp) /* note: does not free $0 */
  1665. free(*pp);
  1666. free(G.global_argv);
  1667. }
  1668. #endif
  1669. argv[0] = sv->sv_argv0;
  1670. G.global_argv = sv->sv_g_argv;
  1671. G.global_argc = sv->sv_g_argc;
  1672. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1673. }
  1674. /* Basic theory of signal handling in shell
  1675. * ========================================
  1676. * This does not describe what hush does, rather, it is current understanding
  1677. * what it _should_ do. If it doesn't, it's a bug.
  1678. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1679. *
  1680. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1681. * is finished or backgrounded. It is the same in interactive and
  1682. * non-interactive shells, and is the same regardless of whether
  1683. * a user trap handler is installed or a shell special one is in effect.
  1684. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1685. * backgrounds (i.e. stops) or kills all members of currently running
  1686. * pipe.
  1687. *
  1688. * Wait builtin is interruptible by signals for which user trap is set
  1689. * or by SIGINT in interactive shell.
  1690. *
  1691. * Trap handlers will execute even within trap handlers. (right?)
  1692. *
  1693. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1694. * except for handlers set to '' (empty string).
  1695. *
  1696. * If job control is off, backgrounded commands ("cmd &")
  1697. * have SIGINT, SIGQUIT set to SIG_IGN.
  1698. *
  1699. * Commands which are run in command substitution ("`cmd`")
  1700. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1701. *
  1702. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1703. * by the shell from its parent.
  1704. *
  1705. * Signals which differ from SIG_DFL action
  1706. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1707. *
  1708. * SIGQUIT: ignore
  1709. * SIGTERM (interactive): ignore
  1710. * SIGHUP (interactive):
  1711. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1712. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1713. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1714. * that all pipe members are stopped. Try this in bash:
  1715. * while :; do :; done - ^Z does not background it
  1716. * (while :; do :; done) - ^Z backgrounds it
  1717. * SIGINT (interactive): wait for last pipe, ignore the rest
  1718. * of the command line, show prompt. NB: ^C does not send SIGINT
  1719. * to interactive shell while shell is waiting for a pipe,
  1720. * since shell is bg'ed (is not in foreground process group).
  1721. * Example 1: this waits 5 sec, but does not execute ls:
  1722. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1723. * Example 2: this does not wait and does not execute ls:
  1724. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1725. * Example 3: this does not wait 5 sec, but executes ls:
  1726. * "sleep 5; ls -l" + press ^C
  1727. * Example 4: this does not wait and does not execute ls:
  1728. * "sleep 5 & wait; ls -l" + press ^C
  1729. *
  1730. * (What happens to signals which are IGN on shell start?)
  1731. * (What happens with signal mask on shell start?)
  1732. *
  1733. * Old implementation
  1734. * ==================
  1735. * We use in-kernel pending signal mask to determine which signals were sent.
  1736. * We block all signals which we don't want to take action immediately,
  1737. * i.e. we block all signals which need to have special handling as described
  1738. * above, and all signals which have traps set.
  1739. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1740. * and act on them.
  1741. *
  1742. * unsigned special_sig_mask: a mask of such "special" signals
  1743. * sigset_t blocked_set: current blocked signal set
  1744. *
  1745. * "trap - SIGxxx":
  1746. * clear bit in blocked_set unless it is also in special_sig_mask
  1747. * "trap 'cmd' SIGxxx":
  1748. * set bit in blocked_set (even if 'cmd' is '')
  1749. * after [v]fork, if we plan to be a shell:
  1750. * unblock signals with special interactive handling
  1751. * (child shell is not interactive),
  1752. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1753. * after [v]fork, if we plan to exec:
  1754. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1755. * Restore blocked signal set to one inherited by shell just prior to exec.
  1756. *
  1757. * Note: as a result, we do not use signal handlers much. The only uses
  1758. * are to count SIGCHLDs
  1759. * and to restore tty pgrp on signal-induced exit.
  1760. *
  1761. * Note 2 (compat):
  1762. * Standard says "When a subshell is entered, traps that are not being ignored
  1763. * are set to the default actions". bash interprets it so that traps which
  1764. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1765. *
  1766. * Problem: the above approach makes it unwieldy to catch signals while
  1767. * we are in read builtin, or while we read commands from stdin:
  1768. * masked signals are not visible!
  1769. *
  1770. * New implementation
  1771. * ==================
  1772. * We record each signal we are interested in by installing signal handler
  1773. * for them - a bit like emulating kernel pending signal mask in userspace.
  1774. * We are interested in: signals which need to have special handling
  1775. * as described above, and all signals which have traps set.
  1776. * Signals are recorded in pending_set.
  1777. * After each pipe execution, we extract any pending signals
  1778. * and act on them.
  1779. *
  1780. * unsigned special_sig_mask: a mask of shell-special signals.
  1781. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1782. * char *traps[sig] if trap for sig is set (even if it's '').
  1783. * sigset_t pending_set: set of sigs we received.
  1784. *
  1785. * "trap - SIGxxx":
  1786. * if sig is in special_sig_mask, set handler back to:
  1787. * record_pending_signo, or to IGN if it's a tty stop signal
  1788. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1789. * else: set handler back to SIG_DFL
  1790. * "trap 'cmd' SIGxxx":
  1791. * set handler to record_pending_signo.
  1792. * "trap '' SIGxxx":
  1793. * set handler to SIG_IGN.
  1794. * after [v]fork, if we plan to be a shell:
  1795. * set signals with special interactive handling to SIG_DFL
  1796. * (because child shell is not interactive),
  1797. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1798. * after [v]fork, if we plan to exec:
  1799. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1800. *
  1801. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1802. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1803. *
  1804. * Note (compat):
  1805. * Standard says "When a subshell is entered, traps that are not being ignored
  1806. * are set to the default actions". bash interprets it so that traps which
  1807. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1808. */
  1809. enum {
  1810. SPECIAL_INTERACTIVE_SIGS = 0
  1811. | (1 << SIGTERM)
  1812. | (1 << SIGINT)
  1813. | (1 << SIGHUP)
  1814. ,
  1815. SPECIAL_JOBSTOP_SIGS = 0
  1816. #if ENABLE_HUSH_JOB
  1817. | (1 << SIGTTIN)
  1818. | (1 << SIGTTOU)
  1819. | (1 << SIGTSTP)
  1820. #endif
  1821. ,
  1822. };
  1823. static void record_pending_signo(int sig)
  1824. {
  1825. sigaddset(&G.pending_set, sig);
  1826. #if ENABLE_HUSH_FAST
  1827. if (sig == SIGCHLD) {
  1828. G.count_SIGCHLD++;
  1829. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1830. }
  1831. #endif
  1832. }
  1833. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1834. {
  1835. struct sigaction old_sa;
  1836. /* We could use signal() to install handlers... almost:
  1837. * except that we need to mask ALL signals while handlers run.
  1838. * I saw signal nesting in strace, race window isn't small.
  1839. * SA_RESTART is also needed, but in Linux, signal()
  1840. * sets SA_RESTART too.
  1841. */
  1842. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1843. /* sigfillset(&G.sa.sa_mask); - already done */
  1844. /* G.sa.sa_flags = SA_RESTART; - already done */
  1845. G.sa.sa_handler = handler;
  1846. sigaction(sig, &G.sa, &old_sa);
  1847. return old_sa.sa_handler;
  1848. }
  1849. static void hush_exit(int exitcode) NORETURN;
  1850. static void restore_ttypgrp_and__exit(void) NORETURN;
  1851. static void restore_ttypgrp_and__exit(void)
  1852. {
  1853. /* xfunc has failed! die die die */
  1854. /* no EXIT traps, this is an escape hatch! */
  1855. G.exiting = 1;
  1856. hush_exit(xfunc_error_retval);
  1857. }
  1858. #if ENABLE_HUSH_JOB
  1859. /* Needed only on some libc:
  1860. * It was observed that on exit(), fgetc'ed buffered data
  1861. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1862. * With the net effect that even after fork(), not vfork(),
  1863. * exit() in NOEXECed applet in "sh SCRIPT":
  1864. * noexec_applet_here
  1865. * echo END_OF_SCRIPT
  1866. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1867. * This makes "echo END_OF_SCRIPT" executed twice.
  1868. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1869. * and in `cmd` handling.
  1870. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1871. */
  1872. static void fflush_and__exit(void) NORETURN;
  1873. static void fflush_and__exit(void)
  1874. {
  1875. fflush_all();
  1876. _exit(xfunc_error_retval);
  1877. }
  1878. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1879. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1880. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1881. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1882. /* Restores tty foreground process group, and exits.
  1883. * May be called as signal handler for fatal signal
  1884. * (will resend signal to itself, producing correct exit state)
  1885. * or called directly with -EXITCODE.
  1886. * We also call it if xfunc is exiting.
  1887. */
  1888. static void sigexit(int sig) NORETURN;
  1889. static void sigexit(int sig)
  1890. {
  1891. /* Careful: we can end up here after [v]fork. Do not restore
  1892. * tty pgrp then, only top-level shell process does that */
  1893. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1894. /* Disable all signals: job control, SIGPIPE, etc.
  1895. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1896. */
  1897. sigprocmask_allsigs(SIG_BLOCK);
  1898. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1899. }
  1900. /* Not a signal, just exit */
  1901. if (sig <= 0)
  1902. _exit(- sig);
  1903. kill_myself_with_sig(sig); /* does not return */
  1904. }
  1905. #else
  1906. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1907. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1908. #endif
  1909. static sighandler_t pick_sighandler(unsigned sig)
  1910. {
  1911. sighandler_t handler = SIG_DFL;
  1912. if (sig < sizeof(unsigned)*8) {
  1913. unsigned sigmask = (1 << sig);
  1914. #if ENABLE_HUSH_JOB
  1915. /* is sig fatal? */
  1916. if (G_fatal_sig_mask & sigmask)
  1917. handler = sigexit;
  1918. else
  1919. #endif
  1920. /* sig has special handling? */
  1921. if (G.special_sig_mask & sigmask) {
  1922. handler = record_pending_signo;
  1923. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1924. * in order to ignore them: they will be raised
  1925. * in an endless loop when we try to do some
  1926. * terminal ioctls! We do have to _ignore_ these.
  1927. */
  1928. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1929. handler = SIG_IGN;
  1930. }
  1931. }
  1932. return handler;
  1933. }
  1934. /* Restores tty foreground process group, and exits. */
  1935. static void hush_exit(int exitcode)
  1936. {
  1937. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1938. if (G.line_input_state)
  1939. save_history(G.line_input_state);
  1940. #endif
  1941. fflush_all();
  1942. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1943. char *argv[3];
  1944. /* argv[0] is unused */
  1945. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1946. argv[2] = NULL;
  1947. G.exiting = 1; /* prevent EXIT trap recursion */
  1948. /* Note: G_traps[0] is not cleared!
  1949. * "trap" will still show it, if executed
  1950. * in the handler */
  1951. builtin_eval(argv);
  1952. }
  1953. #if ENABLE_FEATURE_CLEAN_UP
  1954. {
  1955. struct variable *cur_var;
  1956. if (G.cwd != bb_msg_unknown)
  1957. free((char*)G.cwd);
  1958. cur_var = G.top_var;
  1959. while (cur_var) {
  1960. struct variable *tmp = cur_var;
  1961. if (!cur_var->max_len)
  1962. free(cur_var->varstr);
  1963. cur_var = cur_var->next;
  1964. free(tmp);
  1965. }
  1966. }
  1967. #endif
  1968. fflush_all();
  1969. #if ENABLE_HUSH_JOB
  1970. sigexit(- (exitcode & 0xff));
  1971. #else
  1972. _exit(exitcode);
  1973. #endif
  1974. }
  1975. //TODO: return a mask of ALL handled sigs?
  1976. static int check_and_run_traps(void)
  1977. {
  1978. int last_sig = 0;
  1979. while (1) {
  1980. int sig;
  1981. if (sigisemptyset(&G.pending_set))
  1982. break;
  1983. sig = 0;
  1984. do {
  1985. sig++;
  1986. if (sigismember(&G.pending_set, sig)) {
  1987. sigdelset(&G.pending_set, sig);
  1988. goto got_sig;
  1989. }
  1990. } while (sig < NSIG);
  1991. break;
  1992. got_sig:
  1993. #if ENABLE_HUSH_TRAP
  1994. if (G_traps && G_traps[sig]) {
  1995. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1996. if (G_traps[sig][0]) {
  1997. /* We have user-defined handler */
  1998. smalluint save_rcode;
  1999. int save_pre;
  2000. char *argv[3];
  2001. /* argv[0] is unused */
  2002. argv[1] = xstrdup(G_traps[sig]);
  2003. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2004. argv[2] = NULL;
  2005. save_pre = G.pre_trap_exitcode;
  2006. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2007. builtin_eval(argv);
  2008. free(argv[1]);
  2009. G.pre_trap_exitcode = save_pre;
  2010. G.last_exitcode = save_rcode;
  2011. # if ENABLE_HUSH_FUNCTIONS
  2012. if (G.return_exitcode >= 0) {
  2013. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2014. G.last_exitcode = G.return_exitcode;
  2015. }
  2016. # endif
  2017. last_sig = sig;
  2018. } /* else: "" trap, ignoring signal */
  2019. continue;
  2020. }
  2021. #endif
  2022. /* not a trap: special action */
  2023. switch (sig) {
  2024. case SIGINT:
  2025. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2026. G.flag_SIGINT = 1;
  2027. last_sig = sig;
  2028. break;
  2029. #if ENABLE_HUSH_JOB
  2030. case SIGHUP: {
  2031. //TODO: why are we doing this? ash and dash don't do this,
  2032. //they have no handler for SIGHUP at all,
  2033. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2034. struct pipe *job;
  2035. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2036. /* bash is observed to signal whole process groups,
  2037. * not individual processes */
  2038. for (job = G.job_list; job; job = job->next) {
  2039. if (job->pgrp <= 0)
  2040. continue;
  2041. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2042. if (kill(- job->pgrp, SIGHUP) == 0)
  2043. kill(- job->pgrp, SIGCONT);
  2044. }
  2045. sigexit(SIGHUP);
  2046. }
  2047. #endif
  2048. #if ENABLE_HUSH_FAST
  2049. case SIGCHLD:
  2050. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2051. G.count_SIGCHLD++;
  2052. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2053. /* Note:
  2054. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2055. * This simplifies wait builtin a bit.
  2056. */
  2057. break;
  2058. #endif
  2059. default: /* ignored: */
  2060. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2061. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2062. /* Note:
  2063. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2064. * Example: wait is not interrupted by TERM
  2065. * in interactive shell, because TERM is ignored.
  2066. */
  2067. break;
  2068. }
  2069. }
  2070. return last_sig;
  2071. }
  2072. static const char *get_cwd(int force)
  2073. {
  2074. if (force || G.cwd == NULL) {
  2075. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2076. * we must not try to free(bb_msg_unknown) */
  2077. if (G.cwd == bb_msg_unknown)
  2078. G.cwd = NULL;
  2079. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2080. if (!G.cwd)
  2081. G.cwd = bb_msg_unknown;
  2082. }
  2083. return G.cwd;
  2084. }
  2085. /*
  2086. * Shell and environment variable support
  2087. */
  2088. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2089. {
  2090. struct variable **pp;
  2091. struct variable *cur;
  2092. pp = &G.top_var;
  2093. while ((cur = *pp) != NULL) {
  2094. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2095. return pp;
  2096. pp = &cur->next;
  2097. }
  2098. return NULL;
  2099. }
  2100. static const char* FAST_FUNC get_local_var_value(const char *name)
  2101. {
  2102. struct variable **vpp;
  2103. unsigned len = strlen(name);
  2104. if (G.expanded_assignments) {
  2105. char **cpp = G.expanded_assignments;
  2106. while (*cpp) {
  2107. char *cp = *cpp;
  2108. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2109. return cp + len + 1;
  2110. cpp++;
  2111. }
  2112. }
  2113. vpp = get_ptr_to_local_var(name, len);
  2114. if (vpp)
  2115. return (*vpp)->varstr + len + 1;
  2116. if (strcmp(name, "PPID") == 0)
  2117. return utoa(G.root_ppid);
  2118. // bash compat: UID? EUID?
  2119. #if ENABLE_HUSH_RANDOM_SUPPORT
  2120. if (strcmp(name, "RANDOM") == 0)
  2121. return utoa(next_random(&G.random_gen));
  2122. #endif
  2123. #if ENABLE_HUSH_LINENO_VAR
  2124. if (strcmp(name, "LINENO") == 0)
  2125. return utoa(G.execute_lineno);
  2126. #endif
  2127. #if BASH_EPOCH_VARS
  2128. {
  2129. const char *fmt = NULL;
  2130. if (strcmp(name, "EPOCHSECONDS") == 0)
  2131. fmt = "%lu";
  2132. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2133. fmt = "%lu.%06u";
  2134. if (fmt) {
  2135. struct timeval tv;
  2136. gettimeofday(&tv, NULL);
  2137. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2138. (unsigned)tv.tv_usec);
  2139. return G.epoch_buf;
  2140. }
  2141. }
  2142. #endif
  2143. return NULL;
  2144. }
  2145. #if ENABLE_HUSH_GETOPTS
  2146. static void handle_changed_special_names(const char *name, unsigned name_len)
  2147. {
  2148. if (name_len == 6) {
  2149. if (strncmp(name, "OPTIND", 6) == 0) {
  2150. G.getopt_count = 0;
  2151. return;
  2152. }
  2153. }
  2154. }
  2155. #else
  2156. /* Do not even bother evaluating arguments */
  2157. # define handle_changed_special_names(...) ((void)0)
  2158. #endif
  2159. /* str holds "NAME=VAL" and is expected to be malloced.
  2160. * We take ownership of it.
  2161. */
  2162. #define SETFLAG_EXPORT (1 << 0)
  2163. #define SETFLAG_UNEXPORT (1 << 1)
  2164. #define SETFLAG_MAKE_RO (1 << 2)
  2165. #define SETFLAG_VARLVL_SHIFT 3
  2166. static int set_local_var(char *str, unsigned flags)
  2167. {
  2168. struct variable **cur_pp;
  2169. struct variable *cur;
  2170. char *free_me = NULL;
  2171. char *eq_sign;
  2172. int name_len;
  2173. int retval;
  2174. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2175. eq_sign = strchr(str, '=');
  2176. if (HUSH_DEBUG && !eq_sign)
  2177. bb_simple_error_msg_and_die("BUG in setvar");
  2178. name_len = eq_sign - str + 1; /* including '=' */
  2179. cur_pp = &G.top_var;
  2180. while ((cur = *cur_pp) != NULL) {
  2181. if (strncmp(cur->varstr, str, name_len) != 0) {
  2182. cur_pp = &cur->next;
  2183. continue;
  2184. }
  2185. /* We found an existing var with this name */
  2186. if (cur->flg_read_only) {
  2187. bb_error_msg("%s: readonly variable", str);
  2188. free(str);
  2189. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2190. //but export per se succeeds (does put the var in env). We don't mimic that.
  2191. return -1;
  2192. }
  2193. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2194. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2195. *eq_sign = '\0';
  2196. unsetenv(str);
  2197. *eq_sign = '=';
  2198. }
  2199. if (cur->var_nest_level < local_lvl) {
  2200. /* bash 3.2.33(1) and exported vars:
  2201. * # export z=z
  2202. * # f() { local z=a; env | grep ^z; }
  2203. * # f
  2204. * z=a
  2205. * # env | grep ^z
  2206. * z=z
  2207. */
  2208. if (cur->flg_export)
  2209. flags |= SETFLAG_EXPORT;
  2210. /* New variable is local ("local VAR=VAL" or
  2211. * "VAR=VAL cmd")
  2212. * and existing one is global, or local
  2213. * on a lower level that new one.
  2214. * Remove it from global variable list:
  2215. */
  2216. *cur_pp = cur->next;
  2217. if (G.shadowed_vars_pp) {
  2218. /* Save in "shadowed" list */
  2219. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2220. cur->flg_export ? "exported " : "",
  2221. cur->varstr, cur->var_nest_level, str, local_lvl
  2222. );
  2223. cur->next = *G.shadowed_vars_pp;
  2224. *G.shadowed_vars_pp = cur;
  2225. } else {
  2226. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2227. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2228. cur->flg_export ? "exported " : "",
  2229. cur->varstr, cur->var_nest_level, str, local_lvl
  2230. );
  2231. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2232. free_me = cur->varstr; /* then free it later */
  2233. free(cur);
  2234. }
  2235. break;
  2236. }
  2237. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2238. debug_printf_env("assignement '%s' does not change anything\n", str);
  2239. free_and_exp:
  2240. free(str);
  2241. goto exp;
  2242. }
  2243. /* Replace the value in the found "struct variable" */
  2244. if (cur->max_len != 0) {
  2245. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2246. /* This one is from startup env, reuse space */
  2247. debug_printf_env("reusing startup env for '%s'\n", str);
  2248. strcpy(cur->varstr, str);
  2249. goto free_and_exp;
  2250. }
  2251. /* Can't reuse */
  2252. cur->max_len = 0;
  2253. goto set_str_and_exp;
  2254. }
  2255. /* max_len == 0 signifies "malloced" var, which we can
  2256. * (and have to) free. But we can't free(cur->varstr) here:
  2257. * if cur->flg_export is 1, it is in the environment.
  2258. * We should either unsetenv+free, or wait until putenv,
  2259. * then putenv(new)+free(old).
  2260. */
  2261. free_me = cur->varstr;
  2262. goto set_str_and_exp;
  2263. }
  2264. /* Not found or shadowed - create new variable struct */
  2265. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2266. cur = xzalloc(sizeof(*cur));
  2267. cur->var_nest_level = local_lvl;
  2268. cur->next = *cur_pp;
  2269. *cur_pp = cur;
  2270. set_str_and_exp:
  2271. cur->varstr = str;
  2272. exp:
  2273. #if !BB_MMU || ENABLE_HUSH_READONLY
  2274. if (flags & SETFLAG_MAKE_RO) {
  2275. cur->flg_read_only = 1;
  2276. }
  2277. #endif
  2278. if (flags & SETFLAG_EXPORT)
  2279. cur->flg_export = 1;
  2280. retval = 0;
  2281. if (cur->flg_export) {
  2282. if (flags & SETFLAG_UNEXPORT) {
  2283. cur->flg_export = 0;
  2284. /* unsetenv was already done */
  2285. } else {
  2286. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2287. retval = putenv(cur->varstr);
  2288. /* fall through to "free(free_me)" -
  2289. * only now we can free old exported malloced string
  2290. */
  2291. }
  2292. }
  2293. free(free_me);
  2294. handle_changed_special_names(cur->varstr, name_len - 1);
  2295. return retval;
  2296. }
  2297. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2298. {
  2299. char *var = xasprintf("%s=%s", name, val);
  2300. set_local_var(var, /*flag:*/ 0);
  2301. }
  2302. /* Used at startup and after each cd */
  2303. static void set_pwd_var(unsigned flag)
  2304. {
  2305. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2306. }
  2307. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2308. static int unset_local_var_len(const char *name, int name_len)
  2309. {
  2310. struct variable *cur;
  2311. struct variable **cur_pp;
  2312. cur_pp = &G.top_var;
  2313. while ((cur = *cur_pp) != NULL) {
  2314. if (strncmp(cur->varstr, name, name_len) == 0
  2315. && cur->varstr[name_len] == '='
  2316. ) {
  2317. if (cur->flg_read_only) {
  2318. bb_error_msg("%s: readonly variable", name);
  2319. return EXIT_FAILURE;
  2320. }
  2321. *cur_pp = cur->next;
  2322. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2323. bb_unsetenv(cur->varstr);
  2324. if (!cur->max_len)
  2325. free(cur->varstr);
  2326. free(cur);
  2327. break;
  2328. }
  2329. cur_pp = &cur->next;
  2330. }
  2331. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2332. handle_changed_special_names(name, name_len);
  2333. return EXIT_SUCCESS;
  2334. }
  2335. static int unset_local_var(const char *name)
  2336. {
  2337. return unset_local_var_len(name, strlen(name));
  2338. }
  2339. #endif
  2340. /*
  2341. * Helpers for "var1=val1 var2=val2 cmd" feature
  2342. */
  2343. static void add_vars(struct variable *var)
  2344. {
  2345. struct variable *next;
  2346. while (var) {
  2347. next = var->next;
  2348. var->next = G.top_var;
  2349. G.top_var = var;
  2350. if (var->flg_export) {
  2351. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2352. putenv(var->varstr);
  2353. } else {
  2354. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2355. }
  2356. var = next;
  2357. }
  2358. }
  2359. /* We put strings[i] into variable table and possibly putenv them.
  2360. * If variable is read only, we can free the strings[i]
  2361. * which attempts to overwrite it.
  2362. * The strings[] vector itself is freed.
  2363. */
  2364. static void set_vars_and_save_old(char **strings)
  2365. {
  2366. char **s;
  2367. if (!strings)
  2368. return;
  2369. s = strings;
  2370. while (*s) {
  2371. struct variable *var_p;
  2372. struct variable **var_pp;
  2373. char *eq;
  2374. eq = strchr(*s, '=');
  2375. if (HUSH_DEBUG && !eq)
  2376. bb_simple_error_msg_and_die("BUG in varexp4");
  2377. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2378. if (var_pp) {
  2379. var_p = *var_pp;
  2380. if (var_p->flg_read_only) {
  2381. char **p;
  2382. bb_error_msg("%s: readonly variable", *s);
  2383. /*
  2384. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2385. * If VAR is readonly, leaving it in the list
  2386. * after asssignment error (msg above)
  2387. * causes doubled error message later, on unset.
  2388. */
  2389. debug_printf_env("removing/freeing '%s' element\n", *s);
  2390. free(*s);
  2391. p = s;
  2392. do { *p = p[1]; p++; } while (*p);
  2393. goto next;
  2394. }
  2395. /* below, set_local_var() with nest level will
  2396. * "shadow" (remove) this variable from
  2397. * global linked list.
  2398. */
  2399. }
  2400. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2401. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2402. s++;
  2403. next: ;
  2404. }
  2405. free(strings);
  2406. }
  2407. /*
  2408. * Unicode helper
  2409. */
  2410. static void reinit_unicode_for_hush(void)
  2411. {
  2412. /* Unicode support should be activated even if LANG is set
  2413. * _during_ shell execution, not only if it was set when
  2414. * shell was started. Therefore, re-check LANG every time:
  2415. */
  2416. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2417. || ENABLE_UNICODE_USING_LOCALE
  2418. ) {
  2419. const char *s = get_local_var_value("LC_ALL");
  2420. if (!s) s = get_local_var_value("LC_CTYPE");
  2421. if (!s) s = get_local_var_value("LANG");
  2422. reinit_unicode(s);
  2423. }
  2424. }
  2425. /*
  2426. * in_str support (strings, and "strings" read from files).
  2427. */
  2428. #if ENABLE_HUSH_INTERACTIVE
  2429. /* To test correct lineedit/interactive behavior, type from command line:
  2430. * echo $P\
  2431. * \
  2432. * AT\
  2433. * H\
  2434. * \
  2435. * It exercises a lot of corner cases.
  2436. */
  2437. static const char *setup_prompt_string(void)
  2438. {
  2439. const char *prompt_str;
  2440. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2441. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2442. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2443. if (!prompt_str)
  2444. prompt_str = "";
  2445. # else
  2446. prompt_str = "> "; /* if PS2, else... */
  2447. if (G.promptmode == 0) { /* PS1 */
  2448. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2449. free(G.PS1);
  2450. /* bash uses $PWD value, even if it is set by user.
  2451. * It uses current dir only if PWD is unset.
  2452. * We always use current dir. */
  2453. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2454. }
  2455. # endif
  2456. debug_printf("prompt_str '%s'\n", prompt_str);
  2457. return prompt_str;
  2458. }
  2459. static int get_user_input(struct in_str *i)
  2460. {
  2461. int r;
  2462. const char *prompt_str;
  2463. prompt_str = setup_prompt_string();
  2464. # if ENABLE_FEATURE_EDITING
  2465. for (;;) {
  2466. reinit_unicode_for_hush();
  2467. if (G.flag_SIGINT) {
  2468. /* There was ^C'ed, make it look prettier: */
  2469. bb_putchar('\n');
  2470. G.flag_SIGINT = 0;
  2471. }
  2472. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2473. * only after <Enter>. (^C works immediately) */
  2474. r = read_line_input(G.line_input_state, prompt_str,
  2475. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2476. );
  2477. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2478. if (r == 0)
  2479. raise(SIGINT);
  2480. check_and_run_traps();
  2481. if (r != 0 && !G.flag_SIGINT)
  2482. break;
  2483. /* ^C or SIGINT: repeat */
  2484. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2485. write(STDOUT_FILENO, "^C", 2);
  2486. G.last_exitcode = 128 + SIGINT;
  2487. }
  2488. if (r < 0) {
  2489. /* EOF/error detected */
  2490. i->p = NULL;
  2491. i->peek_buf[0] = r = EOF;
  2492. return r;
  2493. }
  2494. i->p = G.user_input_buf;
  2495. return (unsigned char)*i->p++;
  2496. # else
  2497. for (;;) {
  2498. G.flag_SIGINT = 0;
  2499. if (i->last_char == '\0' || i->last_char == '\n') {
  2500. /* Why check_and_run_traps here? Try this interactively:
  2501. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2502. * $ <[enter], repeatedly...>
  2503. * Without check_and_run_traps, handler never runs.
  2504. */
  2505. check_and_run_traps();
  2506. fputs(prompt_str, stdout);
  2507. }
  2508. fflush_all();
  2509. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2510. r = hfgetc(i->file);
  2511. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2512. * no ^C masking happens during fgetc, no special code for ^C:
  2513. * it generates SIGINT as usual.
  2514. */
  2515. check_and_run_traps();
  2516. if (G.flag_SIGINT)
  2517. G.last_exitcode = 128 + SIGINT;
  2518. if (r != '\0')
  2519. break;
  2520. }
  2521. return r;
  2522. # endif
  2523. }
  2524. /* This is the magic location that prints prompts
  2525. * and gets data back from the user */
  2526. static int fgetc_interactive(struct in_str *i)
  2527. {
  2528. int ch;
  2529. /* If it's interactive stdin, get new line. */
  2530. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2531. /* Returns first char (or EOF), the rest is in i->p[] */
  2532. ch = get_user_input(i);
  2533. G.promptmode = 1; /* PS2 */
  2534. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2535. } else {
  2536. /* Not stdin: script file, sourced file, etc */
  2537. do ch = hfgetc(i->file); while (ch == '\0');
  2538. }
  2539. return ch;
  2540. }
  2541. #else
  2542. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2543. {
  2544. int ch;
  2545. do ch = hfgetc(i->file); while (ch == '\0');
  2546. return ch;
  2547. }
  2548. #endif /* INTERACTIVE */
  2549. static int i_getch(struct in_str *i)
  2550. {
  2551. int ch;
  2552. if (!i->file) {
  2553. /* string-based in_str */
  2554. ch = (unsigned char)*i->p;
  2555. if (ch != '\0') {
  2556. i->p++;
  2557. i->last_char = ch;
  2558. return ch;
  2559. }
  2560. return EOF;
  2561. }
  2562. /* FILE-based in_str */
  2563. #if ENABLE_FEATURE_EDITING
  2564. /* This can be stdin, check line editing char[] buffer */
  2565. if (i->p && *i->p != '\0') {
  2566. ch = (unsigned char)*i->p++;
  2567. goto out;
  2568. }
  2569. #endif
  2570. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2571. ch = i->peek_buf[0];
  2572. if (ch != 0) {
  2573. int ch2 = i->peek_buf[1];
  2574. i->peek_buf[0] = ch2;
  2575. if (ch2 == 0) /* very likely, avoid redundant write */
  2576. goto out;
  2577. i->peek_buf[1] = 0;
  2578. goto out;
  2579. }
  2580. ch = fgetc_interactive(i);
  2581. out:
  2582. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2583. i->last_char = ch;
  2584. #if ENABLE_HUSH_LINENO_VAR
  2585. if (ch == '\n') {
  2586. G.parse_lineno++;
  2587. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2588. }
  2589. #endif
  2590. return ch;
  2591. }
  2592. static int i_peek(struct in_str *i)
  2593. {
  2594. int ch;
  2595. if (!i->file) {
  2596. /* string-based in_str */
  2597. /* Doesn't report EOF on NUL. None of the callers care. */
  2598. return (unsigned char)*i->p;
  2599. }
  2600. /* FILE-based in_str */
  2601. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2602. /* This can be stdin, check line editing char[] buffer */
  2603. if (i->p && *i->p != '\0')
  2604. return (unsigned char)*i->p;
  2605. #endif
  2606. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2607. ch = i->peek_buf[0];
  2608. if (ch != 0)
  2609. return ch;
  2610. /* Need to get a new char */
  2611. ch = fgetc_interactive(i);
  2612. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2613. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2614. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2615. if (i->p) {
  2616. i->p -= 1;
  2617. return ch;
  2618. }
  2619. #endif
  2620. i->peek_buf[0] = ch;
  2621. /*i->peek_buf[1] = 0; - already is */
  2622. return ch;
  2623. }
  2624. /* Only ever called if i_peek() was called, and did not return EOF.
  2625. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2626. * not end-of-line. Therefore we never need to read a new editing line here.
  2627. */
  2628. static int i_peek2(struct in_str *i)
  2629. {
  2630. int ch;
  2631. /* There are two cases when i->p[] buffer exists.
  2632. * (1) it's a string in_str.
  2633. * (2) It's a file, and we have a saved line editing buffer.
  2634. * In both cases, we know that i->p[0] exists and not NUL, and
  2635. * the peek2 result is in i->p[1].
  2636. */
  2637. if (i->p)
  2638. return (unsigned char)i->p[1];
  2639. /* Now we know it is a file-based in_str. */
  2640. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2641. /* Is there 2nd char? */
  2642. ch = i->peek_buf[1];
  2643. if (ch == 0) {
  2644. /* We did not read it yet, get it now */
  2645. do ch = hfgetc(i->file); while (ch == '\0');
  2646. i->peek_buf[1] = ch;
  2647. }
  2648. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2649. return ch;
  2650. }
  2651. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2652. {
  2653. for (;;) {
  2654. int ch, ch2;
  2655. ch = i_getch(input);
  2656. if (ch != '\\')
  2657. return ch;
  2658. ch2 = i_peek(input);
  2659. if (ch2 != '\n')
  2660. return ch;
  2661. /* backslash+newline, skip it */
  2662. i_getch(input);
  2663. }
  2664. }
  2665. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2666. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2667. */
  2668. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2669. {
  2670. for (;;) {
  2671. int ch, ch2;
  2672. ch = i_peek(input);
  2673. if (ch != '\\')
  2674. return ch;
  2675. ch2 = i_peek2(input);
  2676. if (ch2 != '\n')
  2677. return ch;
  2678. /* backslash+newline, skip it */
  2679. i_getch(input);
  2680. i_getch(input);
  2681. }
  2682. }
  2683. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2684. {
  2685. memset(i, 0, sizeof(*i));
  2686. i->file = fp;
  2687. /* i->p = NULL; */
  2688. }
  2689. static void setup_string_in_str(struct in_str *i, const char *s)
  2690. {
  2691. memset(i, 0, sizeof(*i));
  2692. /*i->file = NULL */;
  2693. i->p = s;
  2694. }
  2695. /*
  2696. * o_string support
  2697. */
  2698. #define B_CHUNK (32 * sizeof(char*))
  2699. static void o_reset_to_empty_unquoted(o_string *o)
  2700. {
  2701. o->length = 0;
  2702. o->has_quoted_part = 0;
  2703. if (o->data)
  2704. o->data[0] = '\0';
  2705. }
  2706. static void o_free_and_set_NULL(o_string *o)
  2707. {
  2708. free(o->data);
  2709. memset(o, 0, sizeof(*o));
  2710. }
  2711. static ALWAYS_INLINE void o_free(o_string *o)
  2712. {
  2713. free(o->data);
  2714. }
  2715. static void o_grow_by(o_string *o, int len)
  2716. {
  2717. if (o->length + len > o->maxlen) {
  2718. o->maxlen += (2 * len) | (B_CHUNK-1);
  2719. o->data = xrealloc(o->data, 1 + o->maxlen);
  2720. }
  2721. }
  2722. static void o_addchr(o_string *o, int ch)
  2723. {
  2724. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2725. if (o->length < o->maxlen) {
  2726. /* likely. avoid o_grow_by() call */
  2727. add:
  2728. o->data[o->length] = ch;
  2729. o->length++;
  2730. o->data[o->length] = '\0';
  2731. return;
  2732. }
  2733. o_grow_by(o, 1);
  2734. goto add;
  2735. }
  2736. #if 0
  2737. /* Valid only if we know o_string is not empty */
  2738. static void o_delchr(o_string *o)
  2739. {
  2740. o->length--;
  2741. o->data[o->length] = '\0';
  2742. }
  2743. #endif
  2744. static void o_addblock(o_string *o, const char *str, int len)
  2745. {
  2746. o_grow_by(o, len);
  2747. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2748. o->length += len;
  2749. }
  2750. static void o_addstr(o_string *o, const char *str)
  2751. {
  2752. o_addblock(o, str, strlen(str));
  2753. }
  2754. static void o_addstr_with_NUL(o_string *o, const char *str)
  2755. {
  2756. o_addblock(o, str, strlen(str) + 1);
  2757. }
  2758. #if !BB_MMU
  2759. static void nommu_addchr(o_string *o, int ch)
  2760. {
  2761. if (o)
  2762. o_addchr(o, ch);
  2763. }
  2764. #else
  2765. # define nommu_addchr(o, str) ((void)0)
  2766. #endif
  2767. #if ENABLE_HUSH_MODE_X
  2768. static void x_mode_addchr(int ch)
  2769. {
  2770. o_addchr(&G.x_mode_buf, ch);
  2771. }
  2772. static void x_mode_addstr(const char *str)
  2773. {
  2774. o_addstr(&G.x_mode_buf, str);
  2775. }
  2776. static void x_mode_addblock(const char *str, int len)
  2777. {
  2778. o_addblock(&G.x_mode_buf, str, len);
  2779. }
  2780. static void x_mode_prefix(void)
  2781. {
  2782. int n = G.x_mode_depth;
  2783. do x_mode_addchr('+'); while (--n >= 0);
  2784. }
  2785. static void x_mode_flush(void)
  2786. {
  2787. int len = G.x_mode_buf.length;
  2788. if (len <= 0)
  2789. return;
  2790. if (G.x_mode_fd > 0) {
  2791. G.x_mode_buf.data[len] = '\n';
  2792. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2793. }
  2794. G.x_mode_buf.length = 0;
  2795. }
  2796. #endif
  2797. /*
  2798. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2799. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2800. * Apparently, on unquoted $v bash still does globbing
  2801. * ("v='*.txt'; echo $v" prints all .txt files),
  2802. * but NOT brace expansion! Thus, there should be TWO independent
  2803. * quoting mechanisms on $v expansion side: one protects
  2804. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2805. * We have only second one.
  2806. */
  2807. #if ENABLE_HUSH_BRACE_EXPANSION
  2808. # define MAYBE_BRACES "{}"
  2809. #else
  2810. # define MAYBE_BRACES ""
  2811. #endif
  2812. /* My analysis of quoting semantics tells me that state information
  2813. * is associated with a destination, not a source.
  2814. */
  2815. static void o_addqchr(o_string *o, int ch)
  2816. {
  2817. int sz = 1;
  2818. /* '-' is included because of this case:
  2819. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2820. */
  2821. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2822. if (found)
  2823. sz++;
  2824. o_grow_by(o, sz);
  2825. if (found) {
  2826. o->data[o->length] = '\\';
  2827. o->length++;
  2828. }
  2829. o->data[o->length] = ch;
  2830. o->length++;
  2831. o->data[o->length] = '\0';
  2832. }
  2833. static void o_addQchr(o_string *o, int ch)
  2834. {
  2835. int sz = 1;
  2836. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2837. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2838. ) {
  2839. sz++;
  2840. o->data[o->length] = '\\';
  2841. o->length++;
  2842. }
  2843. o_grow_by(o, sz);
  2844. o->data[o->length] = ch;
  2845. o->length++;
  2846. o->data[o->length] = '\0';
  2847. }
  2848. static void o_addqblock(o_string *o, const char *str, int len)
  2849. {
  2850. while (len) {
  2851. char ch;
  2852. int sz;
  2853. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2854. if (ordinary_cnt > len) /* paranoia */
  2855. ordinary_cnt = len;
  2856. o_addblock(o, str, ordinary_cnt);
  2857. if (ordinary_cnt == len)
  2858. return; /* NUL is already added by o_addblock */
  2859. str += ordinary_cnt;
  2860. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2861. ch = *str++;
  2862. sz = 1;
  2863. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2864. sz++;
  2865. o->data[o->length] = '\\';
  2866. o->length++;
  2867. }
  2868. o_grow_by(o, sz);
  2869. o->data[o->length] = ch;
  2870. o->length++;
  2871. }
  2872. o->data[o->length] = '\0';
  2873. }
  2874. static void o_addQblock(o_string *o, const char *str, int len)
  2875. {
  2876. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2877. o_addblock(o, str, len);
  2878. return;
  2879. }
  2880. o_addqblock(o, str, len);
  2881. }
  2882. static void o_addQstr(o_string *o, const char *str)
  2883. {
  2884. o_addQblock(o, str, strlen(str));
  2885. }
  2886. /* A special kind of o_string for $VAR and `cmd` expansion.
  2887. * It contains char* list[] at the beginning, which is grown in 16 element
  2888. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2889. * list[i] contains an INDEX (int!) into this string data.
  2890. * It means that if list[] needs to grow, data needs to be moved higher up
  2891. * but list[i]'s need not be modified.
  2892. * NB: remembering how many list[i]'s you have there is crucial.
  2893. * o_finalize_list() operation post-processes this structure - calculates
  2894. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2895. */
  2896. #if DEBUG_EXPAND || DEBUG_GLOB
  2897. static void debug_print_list(const char *prefix, o_string *o, int n)
  2898. {
  2899. char **list = (char**)o->data;
  2900. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2901. int i = 0;
  2902. indent();
  2903. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2904. prefix, list, n, string_start, o->length, o->maxlen,
  2905. !!(o->o_expflags & EXP_FLAG_GLOB),
  2906. o->has_quoted_part,
  2907. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2908. while (i < n) {
  2909. indent();
  2910. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2911. o->data + (int)(uintptr_t)list[i] + string_start,
  2912. o->data + (int)(uintptr_t)list[i] + string_start);
  2913. i++;
  2914. }
  2915. if (n) {
  2916. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2917. indent();
  2918. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2919. }
  2920. }
  2921. #else
  2922. # define debug_print_list(prefix, o, n) ((void)0)
  2923. #endif
  2924. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2925. * in list[n] so that it points past last stored byte so far.
  2926. * It returns n+1. */
  2927. static int o_save_ptr_helper(o_string *o, int n)
  2928. {
  2929. char **list = (char**)o->data;
  2930. int string_start;
  2931. int string_len;
  2932. if (!o->has_empty_slot) {
  2933. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2934. string_len = o->length - string_start;
  2935. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2936. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2937. /* list[n] points to string_start, make space for 16 more pointers */
  2938. o->maxlen += 0x10 * sizeof(list[0]);
  2939. o->data = xrealloc(o->data, o->maxlen + 1);
  2940. list = (char**)o->data;
  2941. memmove(list + n + 0x10, list + n, string_len);
  2942. /*
  2943. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2944. * check. (grep for -prev-ifs-check-).
  2945. * Ensure that argv[-1][last] is not garbage
  2946. * but zero bytes, to save index check there.
  2947. */
  2948. list[n + 0x10 - 1] = 0;
  2949. o->length += 0x10 * sizeof(list[0]);
  2950. } else {
  2951. debug_printf_list("list[%d]=%d string_start=%d\n",
  2952. n, string_len, string_start);
  2953. }
  2954. } else {
  2955. /* We have empty slot at list[n], reuse without growth */
  2956. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2957. string_len = o->length - string_start;
  2958. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2959. n, string_len, string_start);
  2960. o->has_empty_slot = 0;
  2961. }
  2962. o->has_quoted_part = 0;
  2963. list[n] = (char*)(uintptr_t)string_len;
  2964. return n + 1;
  2965. }
  2966. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2967. static int o_get_last_ptr(o_string *o, int n)
  2968. {
  2969. char **list = (char**)o->data;
  2970. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2971. return ((int)(uintptr_t)list[n-1]) + string_start;
  2972. }
  2973. /*
  2974. * Globbing routines.
  2975. *
  2976. * Most words in commands need to be globbed, even ones which are
  2977. * (single or double) quoted. This stems from the possiblity of
  2978. * constructs like "abc"* and 'abc'* - these should be globbed.
  2979. * Having a different code path for fully-quoted strings ("abc",
  2980. * 'abc') would only help performance-wise, but we still need
  2981. * code for partially-quoted strings.
  2982. *
  2983. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2984. * the logic can't be "shell-syntax argument is first transformed
  2985. * to a string, then globbed, and if globbing does not match anything,
  2986. * it is used verbatim". Here are two examples where it fails:
  2987. *
  2988. * echo 'b\*'?
  2989. *
  2990. * The globbing can't be avoided (because of '?' at the end).
  2991. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2992. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2993. * - IOW: they "unbackslash" the glob pattern.
  2994. * Now, look at this:
  2995. *
  2996. * v='\\\*'; echo b$v?
  2997. *
  2998. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2999. * should be used as glob pattern with no changes. However, if glob
  3000. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3001. *
  3002. * ash implements this by having an encoded representation of the word
  3003. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3004. * Glob pattern is derived from it. If glob fails, the decision what result
  3005. * should be is made using that encoded representation. Not glob pattern.
  3006. */
  3007. #if ENABLE_HUSH_BRACE_EXPANSION
  3008. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3009. * first, it processes even {a} (no commas), second,
  3010. * I didn't manage to make it return strings when they don't match
  3011. * existing files. Need to re-implement it.
  3012. */
  3013. /* Helper */
  3014. static int glob_needed(const char *s)
  3015. {
  3016. while (*s) {
  3017. if (*s == '\\') {
  3018. if (!s[1])
  3019. return 0;
  3020. s += 2;
  3021. continue;
  3022. }
  3023. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3024. return 1;
  3025. s++;
  3026. }
  3027. return 0;
  3028. }
  3029. /* Return pointer to next closing brace or to comma */
  3030. static const char *next_brace_sub(const char *cp)
  3031. {
  3032. unsigned depth = 0;
  3033. cp++;
  3034. while (*cp != '\0') {
  3035. if (*cp == '\\') {
  3036. if (*++cp == '\0')
  3037. break;
  3038. cp++;
  3039. continue;
  3040. }
  3041. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3042. break;
  3043. if (*cp++ == '{')
  3044. depth++;
  3045. }
  3046. return *cp != '\0' ? cp : NULL;
  3047. }
  3048. /* Recursive brace globber. Note: may garble pattern[]. */
  3049. static int glob_brace(char *pattern, o_string *o, int n)
  3050. {
  3051. char *new_pattern_buf;
  3052. const char *begin;
  3053. const char *next;
  3054. const char *rest;
  3055. const char *p;
  3056. size_t rest_len;
  3057. debug_printf_glob("glob_brace('%s')\n", pattern);
  3058. begin = pattern;
  3059. while (1) {
  3060. if (*begin == '\0')
  3061. goto simple_glob;
  3062. if (*begin == '{') {
  3063. /* Find the first sub-pattern and at the same time
  3064. * find the rest after the closing brace */
  3065. next = next_brace_sub(begin);
  3066. if (next == NULL) {
  3067. /* An illegal expression */
  3068. goto simple_glob;
  3069. }
  3070. if (*next == '}') {
  3071. /* "{abc}" with no commas - illegal
  3072. * brace expr, disregard and skip it */
  3073. begin = next + 1;
  3074. continue;
  3075. }
  3076. break;
  3077. }
  3078. if (*begin == '\\' && begin[1] != '\0')
  3079. begin++;
  3080. begin++;
  3081. }
  3082. debug_printf_glob("begin:%s\n", begin);
  3083. debug_printf_glob("next:%s\n", next);
  3084. /* Now find the end of the whole brace expression */
  3085. rest = next;
  3086. while (*rest != '}') {
  3087. rest = next_brace_sub(rest);
  3088. if (rest == NULL) {
  3089. /* An illegal expression */
  3090. goto simple_glob;
  3091. }
  3092. debug_printf_glob("rest:%s\n", rest);
  3093. }
  3094. rest_len = strlen(++rest) + 1;
  3095. /* We are sure the brace expression is well-formed */
  3096. /* Allocate working buffer large enough for our work */
  3097. new_pattern_buf = xmalloc(strlen(pattern));
  3098. /* We have a brace expression. BEGIN points to the opening {,
  3099. * NEXT points past the terminator of the first element, and REST
  3100. * points past the final }. We will accumulate result names from
  3101. * recursive runs for each brace alternative in the buffer using
  3102. * GLOB_APPEND. */
  3103. p = begin + 1;
  3104. while (1) {
  3105. /* Construct the new glob expression */
  3106. memcpy(
  3107. mempcpy(
  3108. mempcpy(new_pattern_buf,
  3109. /* We know the prefix for all sub-patterns */
  3110. pattern, begin - pattern),
  3111. p, next - p),
  3112. rest, rest_len);
  3113. /* Note: glob_brace() may garble new_pattern_buf[].
  3114. * That's why we re-copy prefix every time (1st memcpy above).
  3115. */
  3116. n = glob_brace(new_pattern_buf, o, n);
  3117. if (*next == '}') {
  3118. /* We saw the last entry */
  3119. break;
  3120. }
  3121. p = next + 1;
  3122. next = next_brace_sub(next);
  3123. }
  3124. free(new_pattern_buf);
  3125. return n;
  3126. simple_glob:
  3127. {
  3128. int gr;
  3129. glob_t globdata;
  3130. memset(&globdata, 0, sizeof(globdata));
  3131. gr = glob(pattern, 0, NULL, &globdata);
  3132. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3133. if (gr != 0) {
  3134. if (gr == GLOB_NOMATCH) {
  3135. globfree(&globdata);
  3136. /* NB: garbles parameter */
  3137. unbackslash(pattern);
  3138. o_addstr_with_NUL(o, pattern);
  3139. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3140. return o_save_ptr_helper(o, n);
  3141. }
  3142. if (gr == GLOB_NOSPACE)
  3143. bb_die_memory_exhausted();
  3144. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3145. * but we didn't specify it. Paranoia again. */
  3146. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3147. }
  3148. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3149. char **argv = globdata.gl_pathv;
  3150. while (1) {
  3151. o_addstr_with_NUL(o, *argv);
  3152. n = o_save_ptr_helper(o, n);
  3153. argv++;
  3154. if (!*argv)
  3155. break;
  3156. }
  3157. }
  3158. globfree(&globdata);
  3159. }
  3160. return n;
  3161. }
  3162. /* Performs globbing on last list[],
  3163. * saving each result as a new list[].
  3164. */
  3165. static int perform_glob(o_string *o, int n)
  3166. {
  3167. char *pattern, *copy;
  3168. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3169. if (!o->data)
  3170. return o_save_ptr_helper(o, n);
  3171. pattern = o->data + o_get_last_ptr(o, n);
  3172. debug_printf_glob("glob pattern '%s'\n", pattern);
  3173. if (!glob_needed(pattern)) {
  3174. /* unbackslash last string in o in place, fix length */
  3175. o->length = unbackslash(pattern) - o->data;
  3176. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3177. return o_save_ptr_helper(o, n);
  3178. }
  3179. copy = xstrdup(pattern);
  3180. /* "forget" pattern in o */
  3181. o->length = pattern - o->data;
  3182. n = glob_brace(copy, o, n);
  3183. free(copy);
  3184. if (DEBUG_GLOB)
  3185. debug_print_list("perform_glob returning", o, n);
  3186. return n;
  3187. }
  3188. #else /* !HUSH_BRACE_EXPANSION */
  3189. /* Helper */
  3190. static int glob_needed(const char *s)
  3191. {
  3192. while (*s) {
  3193. if (*s == '\\') {
  3194. if (!s[1])
  3195. return 0;
  3196. s += 2;
  3197. continue;
  3198. }
  3199. if (*s == '*' || *s == '[' || *s == '?')
  3200. return 1;
  3201. s++;
  3202. }
  3203. return 0;
  3204. }
  3205. /* Performs globbing on last list[],
  3206. * saving each result as a new list[].
  3207. */
  3208. static int perform_glob(o_string *o, int n)
  3209. {
  3210. glob_t globdata;
  3211. int gr;
  3212. char *pattern;
  3213. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3214. if (!o->data)
  3215. return o_save_ptr_helper(o, n);
  3216. pattern = o->data + o_get_last_ptr(o, n);
  3217. debug_printf_glob("glob pattern '%s'\n", pattern);
  3218. if (!glob_needed(pattern)) {
  3219. literal:
  3220. /* unbackslash last string in o in place, fix length */
  3221. o->length = unbackslash(pattern) - o->data;
  3222. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3223. return o_save_ptr_helper(o, n);
  3224. }
  3225. memset(&globdata, 0, sizeof(globdata));
  3226. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3227. * If we glob "*.\*" and don't find anything, we need
  3228. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3229. * will return "*.\*"!
  3230. */
  3231. gr = glob(pattern, 0, NULL, &globdata);
  3232. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3233. if (gr != 0) {
  3234. if (gr == GLOB_NOMATCH) {
  3235. globfree(&globdata);
  3236. goto literal;
  3237. }
  3238. if (gr == GLOB_NOSPACE)
  3239. bb_die_memory_exhausted();
  3240. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3241. * but we didn't specify it. Paranoia again. */
  3242. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3243. }
  3244. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3245. char **argv = globdata.gl_pathv;
  3246. /* "forget" pattern in o */
  3247. o->length = pattern - o->data;
  3248. while (1) {
  3249. o_addstr_with_NUL(o, *argv);
  3250. n = o_save_ptr_helper(o, n);
  3251. argv++;
  3252. if (!*argv)
  3253. break;
  3254. }
  3255. }
  3256. globfree(&globdata);
  3257. if (DEBUG_GLOB)
  3258. debug_print_list("perform_glob returning", o, n);
  3259. return n;
  3260. }
  3261. #endif /* !HUSH_BRACE_EXPANSION */
  3262. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3263. * Otherwise, just finish current list[] and start new */
  3264. static int o_save_ptr(o_string *o, int n)
  3265. {
  3266. if (o->o_expflags & EXP_FLAG_GLOB) {
  3267. /* If o->has_empty_slot, list[n] was already globbed
  3268. * (if it was requested back then when it was filled)
  3269. * so don't do that again! */
  3270. if (!o->has_empty_slot)
  3271. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3272. }
  3273. return o_save_ptr_helper(o, n);
  3274. }
  3275. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3276. static char **o_finalize_list(o_string *o, int n)
  3277. {
  3278. char **list;
  3279. int string_start;
  3280. if (DEBUG_EXPAND)
  3281. debug_print_list("finalized", o, n);
  3282. debug_printf_expand("finalized n:%d\n", n);
  3283. list = (char**)o->data;
  3284. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3285. list[--n] = NULL;
  3286. while (n) {
  3287. n--;
  3288. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3289. }
  3290. return list;
  3291. }
  3292. static void free_pipe_list(struct pipe *pi);
  3293. /* Returns pi->next - next pipe in the list */
  3294. static struct pipe *free_pipe(struct pipe *pi)
  3295. {
  3296. struct pipe *next;
  3297. int i;
  3298. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3299. for (i = 0; i < pi->num_cmds; i++) {
  3300. struct command *command;
  3301. struct redir_struct *r, *rnext;
  3302. command = &pi->cmds[i];
  3303. debug_printf_clean(" command %d:\n", i);
  3304. if (command->argv) {
  3305. if (DEBUG_CLEAN) {
  3306. int a;
  3307. char **p;
  3308. for (a = 0, p = command->argv; *p; a++, p++) {
  3309. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3310. }
  3311. }
  3312. free_strings(command->argv);
  3313. //command->argv = NULL;
  3314. }
  3315. /* not "else if": on syntax error, we may have both! */
  3316. if (command->group) {
  3317. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3318. command->cmd_type);
  3319. free_pipe_list(command->group);
  3320. debug_printf_clean(" end group\n");
  3321. //command->group = NULL;
  3322. }
  3323. /* else is crucial here.
  3324. * If group != NULL, child_func is meaningless */
  3325. #if ENABLE_HUSH_FUNCTIONS
  3326. else if (command->child_func) {
  3327. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3328. command->child_func->parent_cmd = NULL;
  3329. }
  3330. #endif
  3331. #if !BB_MMU
  3332. free(command->group_as_string);
  3333. //command->group_as_string = NULL;
  3334. #endif
  3335. for (r = command->redirects; r; r = rnext) {
  3336. debug_printf_clean(" redirect %d%s",
  3337. r->rd_fd, redir_table[r->rd_type].descrip);
  3338. /* guard against the case >$FOO, where foo is unset or blank */
  3339. if (r->rd_filename) {
  3340. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3341. free(r->rd_filename);
  3342. //r->rd_filename = NULL;
  3343. }
  3344. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3345. rnext = r->next;
  3346. free(r);
  3347. }
  3348. //command->redirects = NULL;
  3349. }
  3350. free(pi->cmds); /* children are an array, they get freed all at once */
  3351. //pi->cmds = NULL;
  3352. #if ENABLE_HUSH_JOB
  3353. free(pi->cmdtext);
  3354. //pi->cmdtext = NULL;
  3355. #endif
  3356. next = pi->next;
  3357. free(pi);
  3358. return next;
  3359. }
  3360. static void free_pipe_list(struct pipe *pi)
  3361. {
  3362. while (pi) {
  3363. #if HAS_KEYWORDS
  3364. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3365. #endif
  3366. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3367. pi = free_pipe(pi);
  3368. }
  3369. }
  3370. /*** Parsing routines ***/
  3371. #ifndef debug_print_tree
  3372. static void debug_print_tree(struct pipe *pi, int lvl)
  3373. {
  3374. static const char *const PIPE[] = {
  3375. [PIPE_SEQ] = "SEQ",
  3376. [PIPE_AND] = "AND",
  3377. [PIPE_OR ] = "OR" ,
  3378. [PIPE_BG ] = "BG" ,
  3379. };
  3380. static const char *RES[] = {
  3381. [RES_NONE ] = "NONE" ,
  3382. # if ENABLE_HUSH_IF
  3383. [RES_IF ] = "IF" ,
  3384. [RES_THEN ] = "THEN" ,
  3385. [RES_ELIF ] = "ELIF" ,
  3386. [RES_ELSE ] = "ELSE" ,
  3387. [RES_FI ] = "FI" ,
  3388. # endif
  3389. # if ENABLE_HUSH_LOOPS
  3390. [RES_FOR ] = "FOR" ,
  3391. [RES_WHILE] = "WHILE",
  3392. [RES_UNTIL] = "UNTIL",
  3393. [RES_DO ] = "DO" ,
  3394. [RES_DONE ] = "DONE" ,
  3395. # endif
  3396. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3397. [RES_IN ] = "IN" ,
  3398. # endif
  3399. # if ENABLE_HUSH_CASE
  3400. [RES_CASE ] = "CASE" ,
  3401. [RES_CASE_IN ] = "CASE_IN" ,
  3402. [RES_MATCH] = "MATCH",
  3403. [RES_CASE_BODY] = "CASE_BODY",
  3404. [RES_ESAC ] = "ESAC" ,
  3405. # endif
  3406. [RES_XXXX ] = "XXXX" ,
  3407. [RES_SNTX ] = "SNTX" ,
  3408. };
  3409. static const char *const CMDTYPE[] = {
  3410. "{}",
  3411. "()",
  3412. "[noglob]",
  3413. # if ENABLE_HUSH_FUNCTIONS
  3414. "func()",
  3415. # endif
  3416. };
  3417. int pin, prn;
  3418. pin = 0;
  3419. while (pi) {
  3420. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3421. lvl*2, "",
  3422. pin,
  3423. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3424. RES[pi->res_word],
  3425. pi->followup, PIPE[pi->followup]
  3426. );
  3427. prn = 0;
  3428. while (prn < pi->num_cmds) {
  3429. struct command *command = &pi->cmds[prn];
  3430. char **argv = command->argv;
  3431. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3432. lvl*2, "", prn,
  3433. command->assignment_cnt);
  3434. # if ENABLE_HUSH_LINENO_VAR
  3435. fdprintf(2, " LINENO:%u", command->lineno);
  3436. # endif
  3437. if (command->group) {
  3438. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3439. CMDTYPE[command->cmd_type],
  3440. argv
  3441. # if !BB_MMU
  3442. , " group_as_string:", command->group_as_string
  3443. # else
  3444. , "", ""
  3445. # endif
  3446. );
  3447. debug_print_tree(command->group, lvl+1);
  3448. prn++;
  3449. continue;
  3450. }
  3451. if (argv) while (*argv) {
  3452. fdprintf(2, " '%s'", *argv);
  3453. argv++;
  3454. }
  3455. if (command->redirects)
  3456. fdprintf(2, " {redir}");
  3457. fdprintf(2, "\n");
  3458. prn++;
  3459. }
  3460. pi = pi->next;
  3461. pin++;
  3462. }
  3463. }
  3464. #endif /* debug_print_tree */
  3465. static struct pipe *new_pipe(void)
  3466. {
  3467. struct pipe *pi;
  3468. pi = xzalloc(sizeof(struct pipe));
  3469. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3470. return pi;
  3471. }
  3472. /* Command (member of a pipe) is complete, or we start a new pipe
  3473. * if ctx->command is NULL.
  3474. * No errors possible here.
  3475. */
  3476. static int done_command(struct parse_context *ctx)
  3477. {
  3478. /* The command is really already in the pipe structure, so
  3479. * advance the pipe counter and make a new, null command. */
  3480. struct pipe *pi = ctx->pipe;
  3481. struct command *command = ctx->command;
  3482. #if 0 /* Instead we emit error message at run time */
  3483. if (ctx->pending_redirect) {
  3484. /* For example, "cmd >" (no filename to redirect to) */
  3485. syntax_error("invalid redirect");
  3486. ctx->pending_redirect = NULL;
  3487. }
  3488. #endif
  3489. if (command) {
  3490. if (IS_NULL_CMD(command)) {
  3491. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3492. goto clear_and_ret;
  3493. }
  3494. pi->num_cmds++;
  3495. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3496. //debug_print_tree(ctx->list_head, 20);
  3497. } else {
  3498. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3499. }
  3500. /* Only real trickiness here is that the uncommitted
  3501. * command structure is not counted in pi->num_cmds. */
  3502. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3503. ctx->command = command = &pi->cmds[pi->num_cmds];
  3504. clear_and_ret:
  3505. memset(command, 0, sizeof(*command));
  3506. #if ENABLE_HUSH_LINENO_VAR
  3507. command->lineno = G.parse_lineno;
  3508. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3509. #endif
  3510. return pi->num_cmds; /* used only for 0/nonzero check */
  3511. }
  3512. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3513. {
  3514. int not_null;
  3515. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3516. /* Close previous command */
  3517. not_null = done_command(ctx);
  3518. #if HAS_KEYWORDS
  3519. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3520. ctx->ctx_inverted = 0;
  3521. ctx->pipe->res_word = ctx->ctx_res_w;
  3522. #endif
  3523. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3524. /* Necessary since && and || have precedence over &:
  3525. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3526. * in a backgrounded subshell.
  3527. */
  3528. struct pipe *pi;
  3529. struct command *command;
  3530. /* Is this actually this construct, all pipes end with && or ||? */
  3531. pi = ctx->list_head;
  3532. while (pi != ctx->pipe) {
  3533. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3534. goto no_conv;
  3535. pi = pi->next;
  3536. }
  3537. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3538. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3539. pi = xzalloc(sizeof(*pi));
  3540. pi->followup = PIPE_BG;
  3541. pi->num_cmds = 1;
  3542. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3543. command = &pi->cmds[0];
  3544. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3545. command->cmd_type = CMD_NORMAL;
  3546. command->group = ctx->list_head;
  3547. #if !BB_MMU
  3548. command->group_as_string = xstrndup(
  3549. ctx->as_string.data,
  3550. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3551. );
  3552. #endif
  3553. /* Replace all pipes in ctx with one newly created */
  3554. ctx->list_head = ctx->pipe = pi;
  3555. } else {
  3556. no_conv:
  3557. ctx->pipe->followup = type;
  3558. }
  3559. /* Without this check, even just <enter> on command line generates
  3560. * tree of three NOPs (!). Which is harmless but annoying.
  3561. * IOW: it is safe to do it unconditionally. */
  3562. if (not_null
  3563. #if ENABLE_HUSH_IF
  3564. || ctx->ctx_res_w == RES_FI
  3565. #endif
  3566. #if ENABLE_HUSH_LOOPS
  3567. || ctx->ctx_res_w == RES_DONE
  3568. || ctx->ctx_res_w == RES_FOR
  3569. || ctx->ctx_res_w == RES_IN
  3570. #endif
  3571. #if ENABLE_HUSH_CASE
  3572. || ctx->ctx_res_w == RES_ESAC
  3573. #endif
  3574. ) {
  3575. struct pipe *new_p;
  3576. debug_printf_parse("done_pipe: adding new pipe: "
  3577. "not_null:%d ctx->ctx_res_w:%d\n",
  3578. not_null, ctx->ctx_res_w);
  3579. new_p = new_pipe();
  3580. ctx->pipe->next = new_p;
  3581. ctx->pipe = new_p;
  3582. /* RES_THEN, RES_DO etc are "sticky" -
  3583. * they remain set for pipes inside if/while.
  3584. * This is used to control execution.
  3585. * RES_FOR and RES_IN are NOT sticky (needed to support
  3586. * cases where variable or value happens to match a keyword):
  3587. */
  3588. #if ENABLE_HUSH_LOOPS
  3589. if (ctx->ctx_res_w == RES_FOR
  3590. || ctx->ctx_res_w == RES_IN)
  3591. ctx->ctx_res_w = RES_NONE;
  3592. #endif
  3593. #if ENABLE_HUSH_CASE
  3594. if (ctx->ctx_res_w == RES_MATCH)
  3595. ctx->ctx_res_w = RES_CASE_BODY;
  3596. if (ctx->ctx_res_w == RES_CASE)
  3597. ctx->ctx_res_w = RES_CASE_IN;
  3598. #endif
  3599. ctx->command = NULL; /* trick done_command below */
  3600. /* Create the memory for command, roughly:
  3601. * ctx->pipe->cmds = new struct command;
  3602. * ctx->command = &ctx->pipe->cmds[0];
  3603. */
  3604. done_command(ctx);
  3605. //debug_print_tree(ctx->list_head, 10);
  3606. }
  3607. debug_printf_parse("done_pipe return\n");
  3608. }
  3609. static void initialize_context(struct parse_context *ctx)
  3610. {
  3611. memset(ctx, 0, sizeof(*ctx));
  3612. if (MAYBE_ASSIGNMENT != 0)
  3613. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3614. ctx->pipe = ctx->list_head = new_pipe();
  3615. /* Create the memory for command, roughly:
  3616. * ctx->pipe->cmds = new struct command;
  3617. * ctx->command = &ctx->pipe->cmds[0];
  3618. */
  3619. done_command(ctx);
  3620. }
  3621. /* If a reserved word is found and processed, parse context is modified
  3622. * and 1 is returned.
  3623. */
  3624. #if HAS_KEYWORDS
  3625. struct reserved_combo {
  3626. char literal[6];
  3627. unsigned char res;
  3628. unsigned char assignment_flag;
  3629. int flag;
  3630. };
  3631. enum {
  3632. FLAG_END = (1 << RES_NONE ),
  3633. # if ENABLE_HUSH_IF
  3634. FLAG_IF = (1 << RES_IF ),
  3635. FLAG_THEN = (1 << RES_THEN ),
  3636. FLAG_ELIF = (1 << RES_ELIF ),
  3637. FLAG_ELSE = (1 << RES_ELSE ),
  3638. FLAG_FI = (1 << RES_FI ),
  3639. # endif
  3640. # if ENABLE_HUSH_LOOPS
  3641. FLAG_FOR = (1 << RES_FOR ),
  3642. FLAG_WHILE = (1 << RES_WHILE),
  3643. FLAG_UNTIL = (1 << RES_UNTIL),
  3644. FLAG_DO = (1 << RES_DO ),
  3645. FLAG_DONE = (1 << RES_DONE ),
  3646. FLAG_IN = (1 << RES_IN ),
  3647. # endif
  3648. # if ENABLE_HUSH_CASE
  3649. FLAG_MATCH = (1 << RES_MATCH),
  3650. FLAG_ESAC = (1 << RES_ESAC ),
  3651. # endif
  3652. FLAG_START = (1 << RES_XXXX ),
  3653. };
  3654. static const struct reserved_combo* match_reserved_word(o_string *word)
  3655. {
  3656. /* Mostly a list of accepted follow-up reserved words.
  3657. * FLAG_END means we are done with the sequence, and are ready
  3658. * to turn the compound list into a command.
  3659. * FLAG_START means the word must start a new compound list.
  3660. */
  3661. static const struct reserved_combo reserved_list[] = {
  3662. # if ENABLE_HUSH_IF
  3663. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3664. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3665. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3666. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3667. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3668. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3669. # endif
  3670. # if ENABLE_HUSH_LOOPS
  3671. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3672. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3673. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3674. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3675. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3676. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3677. # endif
  3678. # if ENABLE_HUSH_CASE
  3679. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3680. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3681. # endif
  3682. };
  3683. const struct reserved_combo *r;
  3684. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3685. if (strcmp(word->data, r->literal) == 0)
  3686. return r;
  3687. }
  3688. return NULL;
  3689. }
  3690. /* Return NULL: not a keyword, else: keyword
  3691. */
  3692. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3693. {
  3694. # if ENABLE_HUSH_CASE
  3695. static const struct reserved_combo reserved_match = {
  3696. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3697. };
  3698. # endif
  3699. const struct reserved_combo *r;
  3700. if (ctx->word.has_quoted_part)
  3701. return 0;
  3702. r = match_reserved_word(&ctx->word);
  3703. if (!r)
  3704. return r; /* NULL */
  3705. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3706. # if ENABLE_HUSH_CASE
  3707. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3708. /* "case word IN ..." - IN part starts first MATCH part */
  3709. r = &reserved_match;
  3710. } else
  3711. # endif
  3712. if (r->flag == 0) { /* '!' */
  3713. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3714. syntax_error("! ! command");
  3715. ctx->ctx_res_w = RES_SNTX;
  3716. }
  3717. ctx->ctx_inverted = 1;
  3718. return r;
  3719. }
  3720. if (r->flag & FLAG_START) {
  3721. struct parse_context *old;
  3722. old = xmemdup(ctx, sizeof(*ctx));
  3723. debug_printf_parse("push stack %p\n", old);
  3724. initialize_context(ctx);
  3725. ctx->stack = old;
  3726. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3727. syntax_error_at(ctx->word.data);
  3728. ctx->ctx_res_w = RES_SNTX;
  3729. return r;
  3730. } else {
  3731. /* "{...} fi" is ok. "{...} if" is not
  3732. * Example:
  3733. * if { echo foo; } then { echo bar; } fi */
  3734. if (ctx->command->group)
  3735. done_pipe(ctx, PIPE_SEQ);
  3736. }
  3737. ctx->ctx_res_w = r->res;
  3738. ctx->old_flag = r->flag;
  3739. ctx->is_assignment = r->assignment_flag;
  3740. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3741. if (ctx->old_flag & FLAG_END) {
  3742. struct parse_context *old;
  3743. done_pipe(ctx, PIPE_SEQ);
  3744. debug_printf_parse("pop stack %p\n", ctx->stack);
  3745. old = ctx->stack;
  3746. old->command->group = ctx->list_head;
  3747. old->command->cmd_type = CMD_NORMAL;
  3748. # if !BB_MMU
  3749. /* At this point, the compound command's string is in
  3750. * ctx->as_string... except for the leading keyword!
  3751. * Consider this example: "echo a | if true; then echo a; fi"
  3752. * ctx->as_string will contain "true; then echo a; fi",
  3753. * with "if " remaining in old->as_string!
  3754. */
  3755. {
  3756. char *str;
  3757. int len = old->as_string.length;
  3758. /* Concatenate halves */
  3759. o_addstr(&old->as_string, ctx->as_string.data);
  3760. o_free(&ctx->as_string);
  3761. /* Find where leading keyword starts in first half */
  3762. str = old->as_string.data + len;
  3763. if (str > old->as_string.data)
  3764. str--; /* skip whitespace after keyword */
  3765. while (str > old->as_string.data && isalpha(str[-1]))
  3766. str--;
  3767. /* Ugh, we're done with this horrid hack */
  3768. old->command->group_as_string = xstrdup(str);
  3769. debug_printf_parse("pop, remembering as:'%s'\n",
  3770. old->command->group_as_string);
  3771. }
  3772. # endif
  3773. *ctx = *old; /* physical copy */
  3774. free(old);
  3775. }
  3776. return r;
  3777. }
  3778. #endif /* HAS_KEYWORDS */
  3779. /* Word is complete, look at it and update parsing context.
  3780. * Normal return is 0. Syntax errors return 1.
  3781. * Note: on return, word is reset, but not o_free'd!
  3782. */
  3783. static int done_word(struct parse_context *ctx)
  3784. {
  3785. struct command *command = ctx->command;
  3786. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3787. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3788. debug_printf_parse("done_word return 0: true null, ignored\n");
  3789. return 0;
  3790. }
  3791. if (ctx->pending_redirect) {
  3792. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3793. * only if run as "bash", not "sh" */
  3794. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3795. * "2.7 Redirection
  3796. * If the redirection operator is "<<" or "<<-", the word
  3797. * that follows the redirection operator shall be
  3798. * subjected to quote removal; it is unspecified whether
  3799. * any of the other expansions occur. For the other
  3800. * redirection operators, the word that follows the
  3801. * redirection operator shall be subjected to tilde
  3802. * expansion, parameter expansion, command substitution,
  3803. * arithmetic expansion, and quote removal.
  3804. * Pathname expansion shall not be performed
  3805. * on the word by a non-interactive shell; an interactive
  3806. * shell may perform it, but shall do so only when
  3807. * the expansion would result in one word."
  3808. */
  3809. //bash does not do parameter/command substitution or arithmetic expansion
  3810. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3811. // as written:
  3812. // <<EOF$t
  3813. // <<EOF$((1))
  3814. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3815. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3816. /* Cater for >\file case:
  3817. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3818. * Same with heredocs:
  3819. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3820. */
  3821. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3822. unbackslash(ctx->pending_redirect->rd_filename);
  3823. /* Is it <<"HEREDOC"? */
  3824. if (ctx->word.has_quoted_part) {
  3825. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3826. }
  3827. }
  3828. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3829. ctx->pending_redirect = NULL;
  3830. } else {
  3831. #if HAS_KEYWORDS
  3832. # if ENABLE_HUSH_CASE
  3833. if (ctx->ctx_dsemicolon
  3834. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3835. ) {
  3836. /* already done when ctx_dsemicolon was set to 1: */
  3837. /* ctx->ctx_res_w = RES_MATCH; */
  3838. ctx->ctx_dsemicolon = 0;
  3839. } else
  3840. # endif
  3841. if (!command->argv /* if it's the first word... */
  3842. # if ENABLE_HUSH_LOOPS
  3843. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3844. && ctx->ctx_res_w != RES_IN
  3845. # endif
  3846. # if ENABLE_HUSH_CASE
  3847. && ctx->ctx_res_w != RES_CASE
  3848. # endif
  3849. ) {
  3850. const struct reserved_combo *reserved;
  3851. reserved = reserved_word(ctx);
  3852. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3853. if (reserved) {
  3854. # if ENABLE_HUSH_LINENO_VAR
  3855. /* Case:
  3856. * "while ...; do
  3857. * cmd ..."
  3858. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3859. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3860. */
  3861. if (0
  3862. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3863. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3864. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3865. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3866. ) {
  3867. done_pipe(ctx, PIPE_SEQ);
  3868. }
  3869. # endif
  3870. o_reset_to_empty_unquoted(&ctx->word);
  3871. debug_printf_parse("done_word return %d\n",
  3872. (ctx->ctx_res_w == RES_SNTX));
  3873. return (ctx->ctx_res_w == RES_SNTX);
  3874. }
  3875. # if defined(CMD_SINGLEWORD_NOGLOB)
  3876. if (0
  3877. # if BASH_TEST2
  3878. || strcmp(ctx->word.data, "[[") == 0
  3879. # endif
  3880. /* In bash, local/export/readonly are special, args
  3881. * are assignments and therefore expansion of them
  3882. * should be "one-word" expansion:
  3883. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3884. * compare with:
  3885. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3886. * ls: cannot access i=a: No such file or directory
  3887. * ls: cannot access b: No such file or directory
  3888. * Note: bash 3.2.33(1) does this only if export word
  3889. * itself is not quoted:
  3890. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3891. * aaa bbb
  3892. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3893. * aaa
  3894. */
  3895. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3896. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3897. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3898. ) {
  3899. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3900. }
  3901. /* fall through */
  3902. # endif
  3903. }
  3904. #endif /* HAS_KEYWORDS */
  3905. if (command->group) {
  3906. /* "{ echo foo; } echo bar" - bad */
  3907. syntax_error_at(ctx->word.data);
  3908. debug_printf_parse("done_word return 1: syntax error, "
  3909. "groups and arglists don't mix\n");
  3910. return 1;
  3911. }
  3912. /* If this word wasn't an assignment, next ones definitely
  3913. * can't be assignments. Even if they look like ones. */
  3914. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3915. && ctx->is_assignment != WORD_IS_KEYWORD
  3916. ) {
  3917. ctx->is_assignment = NOT_ASSIGNMENT;
  3918. } else {
  3919. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3920. command->assignment_cnt++;
  3921. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3922. }
  3923. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3924. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3925. }
  3926. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3927. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3928. debug_print_strings("word appended to argv", command->argv);
  3929. }
  3930. #if ENABLE_HUSH_LOOPS
  3931. if (ctx->ctx_res_w == RES_FOR) {
  3932. if (ctx->word.has_quoted_part
  3933. || endofname(command->argv[0])[0] != '\0'
  3934. ) {
  3935. /* bash says just "not a valid identifier" */
  3936. syntax_error("not a valid identifier in for");
  3937. return 1;
  3938. }
  3939. /* Force FOR to have just one word (variable name) */
  3940. /* NB: basically, this makes hush see "for v in ..."
  3941. * syntax as if it is "for v; in ...". FOR and IN become
  3942. * two pipe structs in parse tree. */
  3943. done_pipe(ctx, PIPE_SEQ);
  3944. }
  3945. #endif
  3946. #if ENABLE_HUSH_CASE
  3947. /* Force CASE to have just one word */
  3948. if (ctx->ctx_res_w == RES_CASE) {
  3949. done_pipe(ctx, PIPE_SEQ);
  3950. }
  3951. #endif
  3952. o_reset_to_empty_unquoted(&ctx->word);
  3953. debug_printf_parse("done_word return 0\n");
  3954. return 0;
  3955. }
  3956. /* Peek ahead in the input to find out if we have a "&n" construct,
  3957. * as in "2>&1", that represents duplicating a file descriptor.
  3958. * Return:
  3959. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3960. * REDIRFD_SYNTAX_ERR if syntax error,
  3961. * REDIRFD_TO_FILE if no & was seen,
  3962. * or the number found.
  3963. */
  3964. #if BB_MMU
  3965. #define parse_redir_right_fd(as_string, input) \
  3966. parse_redir_right_fd(input)
  3967. #endif
  3968. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3969. {
  3970. int ch, d, ok;
  3971. ch = i_peek(input);
  3972. if (ch != '&')
  3973. return REDIRFD_TO_FILE;
  3974. ch = i_getch(input); /* get the & */
  3975. nommu_addchr(as_string, ch);
  3976. ch = i_peek(input);
  3977. if (ch == '-') {
  3978. ch = i_getch(input);
  3979. nommu_addchr(as_string, ch);
  3980. return REDIRFD_CLOSE;
  3981. }
  3982. d = 0;
  3983. ok = 0;
  3984. while (ch != EOF && isdigit(ch)) {
  3985. d = d*10 + (ch-'0');
  3986. ok = 1;
  3987. ch = i_getch(input);
  3988. nommu_addchr(as_string, ch);
  3989. ch = i_peek(input);
  3990. }
  3991. if (ok) return d;
  3992. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3993. bb_simple_error_msg("ambiguous redirect");
  3994. return REDIRFD_SYNTAX_ERR;
  3995. }
  3996. /* Return code is 0 normal, 1 if a syntax error is detected
  3997. */
  3998. static int parse_redirect(struct parse_context *ctx,
  3999. int fd,
  4000. redir_type style,
  4001. struct in_str *input)
  4002. {
  4003. struct command *command = ctx->command;
  4004. struct redir_struct *redir;
  4005. struct redir_struct **redirp;
  4006. int dup_num;
  4007. dup_num = REDIRFD_TO_FILE;
  4008. if (style != REDIRECT_HEREDOC) {
  4009. /* Check for a '>&1' type redirect */
  4010. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4011. if (dup_num == REDIRFD_SYNTAX_ERR)
  4012. return 1;
  4013. } else {
  4014. int ch = i_peek_and_eat_bkslash_nl(input);
  4015. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4016. if (dup_num) { /* <<-... */
  4017. ch = i_getch(input);
  4018. nommu_addchr(&ctx->as_string, ch);
  4019. ch = i_peek(input);
  4020. }
  4021. }
  4022. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4023. int ch = i_peek_and_eat_bkslash_nl(input);
  4024. if (ch == '|') {
  4025. /* >|FILE redirect ("clobbering" >).
  4026. * Since we do not support "set -o noclobber" yet,
  4027. * >| and > are the same for now. Just eat |.
  4028. */
  4029. ch = i_getch(input);
  4030. nommu_addchr(&ctx->as_string, ch);
  4031. }
  4032. }
  4033. /* Create a new redir_struct and append it to the linked list */
  4034. redirp = &command->redirects;
  4035. while ((redir = *redirp) != NULL) {
  4036. redirp = &(redir->next);
  4037. }
  4038. *redirp = redir = xzalloc(sizeof(*redir));
  4039. /* redir->next = NULL; */
  4040. /* redir->rd_filename = NULL; */
  4041. redir->rd_type = style;
  4042. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4043. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4044. redir_table[style].descrip);
  4045. redir->rd_dup = dup_num;
  4046. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4047. /* Erik had a check here that the file descriptor in question
  4048. * is legit; I postpone that to "run time"
  4049. * A "-" representation of "close me" shows up as a -3 here */
  4050. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4051. redir->rd_fd, redir->rd_dup);
  4052. } else {
  4053. #if 0 /* Instead we emit error message at run time */
  4054. if (ctx->pending_redirect) {
  4055. /* For example, "cmd > <file" */
  4056. syntax_error("invalid redirect");
  4057. }
  4058. #endif
  4059. /* Set ctx->pending_redirect, so we know what to do at the
  4060. * end of the next parsed word. */
  4061. ctx->pending_redirect = redir;
  4062. }
  4063. return 0;
  4064. }
  4065. /* If a redirect is immediately preceded by a number, that number is
  4066. * supposed to tell which file descriptor to redirect. This routine
  4067. * looks for such preceding numbers. In an ideal world this routine
  4068. * needs to handle all the following classes of redirects...
  4069. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4070. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4071. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4072. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4073. *
  4074. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4075. * "2.7 Redirection
  4076. * ... If n is quoted, the number shall not be recognized as part of
  4077. * the redirection expression. For example:
  4078. * echo \2>a
  4079. * writes the character 2 into file a"
  4080. * We are getting it right by setting ->has_quoted_part on any \<char>
  4081. *
  4082. * A -1 return means no valid number was found,
  4083. * the caller should use the appropriate default for this redirection.
  4084. */
  4085. static int redirect_opt_num(o_string *o)
  4086. {
  4087. int num;
  4088. if (o->data == NULL)
  4089. return -1;
  4090. num = bb_strtou(o->data, NULL, 10);
  4091. if (errno || num < 0)
  4092. return -1;
  4093. o_reset_to_empty_unquoted(o);
  4094. return num;
  4095. }
  4096. #if BB_MMU
  4097. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4098. fetch_till_str(input, word, skip_tabs)
  4099. #endif
  4100. static char *fetch_till_str(o_string *as_string,
  4101. struct in_str *input,
  4102. const char *word,
  4103. int heredoc_flags)
  4104. {
  4105. o_string heredoc = NULL_O_STRING;
  4106. unsigned past_EOL;
  4107. int prev = 0; /* not \ */
  4108. int ch;
  4109. /* Starting with "" is necessary for this case:
  4110. * cat <<EOF
  4111. *
  4112. * xxx
  4113. * EOF
  4114. */
  4115. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4116. goto jump_in;
  4117. while (1) {
  4118. ch = i_getch(input);
  4119. if (ch != EOF)
  4120. nommu_addchr(as_string, ch);
  4121. if (ch == '\n' || ch == EOF) {
  4122. check_heredoc_end:
  4123. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4124. /* End-of-line, and not a line continuation */
  4125. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4126. heredoc.data[past_EOL] = '\0';
  4127. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4128. return heredoc.data;
  4129. }
  4130. if (ch == '\n') {
  4131. /* This is a new line.
  4132. * Remember position and backslash-escaping status.
  4133. */
  4134. o_addchr(&heredoc, ch);
  4135. prev = ch;
  4136. jump_in:
  4137. past_EOL = heredoc.length;
  4138. /* Get 1st char of next line, possibly skipping leading tabs */
  4139. do {
  4140. ch = i_getch(input);
  4141. if (ch != EOF)
  4142. nommu_addchr(as_string, ch);
  4143. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4144. /* If this immediately ended the line,
  4145. * go back to end-of-line checks.
  4146. */
  4147. if (ch == '\n')
  4148. goto check_heredoc_end;
  4149. }
  4150. } else {
  4151. /* Backslash-line continuation in an unquoted
  4152. * heredoc. This does not need special handling
  4153. * for heredoc body (unquoted heredocs are
  4154. * expanded on "execution" and that would take
  4155. * care of this case too), but not the case
  4156. * of line continuation *in terminator*:
  4157. * cat <<EOF
  4158. * Ok1
  4159. * EO\
  4160. * F
  4161. */
  4162. heredoc.data[--heredoc.length] = '\0';
  4163. prev = 0; /* not '\' */
  4164. continue;
  4165. }
  4166. }
  4167. if (ch == EOF) {
  4168. o_free(&heredoc);
  4169. return NULL; /* error */
  4170. }
  4171. o_addchr(&heredoc, ch);
  4172. nommu_addchr(as_string, ch);
  4173. if (prev == '\\' && ch == '\\')
  4174. /* Correctly handle foo\\<eol> (not a line cont.) */
  4175. prev = 0; /* not '\' */
  4176. else
  4177. prev = ch;
  4178. }
  4179. }
  4180. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4181. * and load them all. There should be exactly heredoc_cnt of them.
  4182. */
  4183. #if BB_MMU
  4184. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4185. fetch_heredocs(pi, heredoc_cnt, input)
  4186. #endif
  4187. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4188. {
  4189. while (pi && heredoc_cnt) {
  4190. int i;
  4191. struct command *cmd = pi->cmds;
  4192. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4193. pi->num_cmds,
  4194. cmd->argv ? cmd->argv[0] : "NONE"
  4195. );
  4196. for (i = 0; i < pi->num_cmds; i++) {
  4197. struct redir_struct *redir = cmd->redirects;
  4198. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4199. i, cmd->argv ? cmd->argv[0] : "NONE");
  4200. while (redir) {
  4201. if (redir->rd_type == REDIRECT_HEREDOC) {
  4202. char *p;
  4203. redir->rd_type = REDIRECT_HEREDOC2;
  4204. /* redir->rd_dup is (ab)used to indicate <<- */
  4205. p = fetch_till_str(as_string, input,
  4206. redir->rd_filename, redir->rd_dup);
  4207. if (!p) {
  4208. syntax_error("unexpected EOF in here document");
  4209. return -1;
  4210. }
  4211. free(redir->rd_filename);
  4212. redir->rd_filename = p;
  4213. heredoc_cnt--;
  4214. }
  4215. redir = redir->next;
  4216. }
  4217. if (cmd->group) {
  4218. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4219. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4220. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4221. if (heredoc_cnt < 0)
  4222. return heredoc_cnt; /* error */
  4223. }
  4224. cmd++;
  4225. }
  4226. pi = pi->next;
  4227. }
  4228. return heredoc_cnt;
  4229. }
  4230. static int run_list(struct pipe *pi);
  4231. #if BB_MMU
  4232. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4233. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4234. #endif
  4235. static struct pipe *parse_stream(char **pstring,
  4236. int *heredoc_cnt_ptr,
  4237. struct in_str *input,
  4238. int end_trigger);
  4239. /* Returns number of heredocs not yet consumed,
  4240. * or -1 on error.
  4241. */
  4242. static int parse_group(struct parse_context *ctx,
  4243. struct in_str *input, int ch)
  4244. {
  4245. /* ctx->word contains characters seen prior to ( or {.
  4246. * Typically it's empty, but for function defs,
  4247. * it contains function name (without '()'). */
  4248. #if BB_MMU
  4249. # define as_string NULL
  4250. #else
  4251. char *as_string = NULL;
  4252. #endif
  4253. struct pipe *pipe_list;
  4254. int heredoc_cnt = 0;
  4255. int endch;
  4256. struct command *command = ctx->command;
  4257. debug_printf_parse("parse_group entered\n");
  4258. #if ENABLE_HUSH_FUNCTIONS
  4259. if (ch == '(' && !ctx->word.has_quoted_part) {
  4260. if (ctx->word.length)
  4261. if (done_word(ctx))
  4262. return -1;
  4263. if (!command->argv)
  4264. goto skip; /* (... */
  4265. if (command->argv[1]) { /* word word ... (... */
  4266. syntax_error_unexpected_ch('(');
  4267. return -1;
  4268. }
  4269. /* it is "word(..." or "word (..." */
  4270. do
  4271. ch = i_getch(input);
  4272. while (ch == ' ' || ch == '\t');
  4273. if (ch != ')') {
  4274. syntax_error_unexpected_ch(ch);
  4275. return -1;
  4276. }
  4277. nommu_addchr(&ctx->as_string, ch);
  4278. do
  4279. ch = i_getch(input);
  4280. while (ch == ' ' || ch == '\t' || ch == '\n');
  4281. if (ch != '{' && ch != '(') {
  4282. syntax_error_unexpected_ch(ch);
  4283. return -1;
  4284. }
  4285. nommu_addchr(&ctx->as_string, ch);
  4286. command->cmd_type = CMD_FUNCDEF;
  4287. goto skip;
  4288. }
  4289. #endif
  4290. #if 0 /* Prevented by caller */
  4291. if (command->argv /* word [word]{... */
  4292. || ctx->word.length /* word{... */
  4293. || ctx->word.has_quoted_part /* ""{... */
  4294. ) {
  4295. syntax_error(NULL);
  4296. debug_printf_parse("parse_group return -1: "
  4297. "syntax error, groups and arglists don't mix\n");
  4298. return -1;
  4299. }
  4300. #endif
  4301. IF_HUSH_FUNCTIONS(skip:)
  4302. endch = '}';
  4303. if (ch == '(') {
  4304. endch = ')';
  4305. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4306. command->cmd_type = CMD_SUBSHELL;
  4307. } else {
  4308. /* bash does not allow "{echo...", requires whitespace */
  4309. ch = i_peek(input);
  4310. if (ch != ' ' && ch != '\t' && ch != '\n'
  4311. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4312. ) {
  4313. syntax_error_unexpected_ch(ch);
  4314. return -1;
  4315. }
  4316. if (ch != '(') {
  4317. ch = i_getch(input);
  4318. nommu_addchr(&ctx->as_string, ch);
  4319. }
  4320. }
  4321. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4322. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4323. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4324. #if !BB_MMU
  4325. if (as_string)
  4326. o_addstr(&ctx->as_string, as_string);
  4327. #endif
  4328. /* empty ()/{} or parse error? */
  4329. if (!pipe_list || pipe_list == ERR_PTR) {
  4330. /* parse_stream already emitted error msg */
  4331. if (!BB_MMU)
  4332. free(as_string);
  4333. debug_printf_parse("parse_group return -1: "
  4334. "parse_stream returned %p\n", pipe_list);
  4335. return -1;
  4336. }
  4337. #if !BB_MMU
  4338. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4339. command->group_as_string = as_string;
  4340. debug_printf_parse("end of group, remembering as:'%s'\n",
  4341. command->group_as_string);
  4342. #endif
  4343. #if ENABLE_HUSH_FUNCTIONS
  4344. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4345. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4346. struct command *cmd2;
  4347. cmd2 = xzalloc(sizeof(*cmd2));
  4348. cmd2->cmd_type = CMD_SUBSHELL;
  4349. cmd2->group = pipe_list;
  4350. # if !BB_MMU
  4351. //UNTESTED!
  4352. cmd2->group_as_string = command->group_as_string;
  4353. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4354. # endif
  4355. pipe_list = new_pipe();
  4356. pipe_list->cmds = cmd2;
  4357. pipe_list->num_cmds = 1;
  4358. }
  4359. #endif
  4360. command->group = pipe_list;
  4361. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4362. return heredoc_cnt;
  4363. /* command remains "open", available for possible redirects */
  4364. #undef as_string
  4365. }
  4366. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4367. /* Subroutines for copying $(...) and `...` things */
  4368. /* '...' */
  4369. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4370. {
  4371. while (1) {
  4372. int ch = i_getch(input);
  4373. if (ch == EOF) {
  4374. syntax_error_unterm_ch('\'');
  4375. return 0;
  4376. }
  4377. if (ch == '\'')
  4378. return 1;
  4379. o_addchr(dest, ch);
  4380. }
  4381. }
  4382. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4383. {
  4384. while (1) {
  4385. int ch = i_getch(input);
  4386. if (ch == EOF) {
  4387. syntax_error_unterm_ch('\'');
  4388. return 0;
  4389. }
  4390. if (ch == '\'')
  4391. return 1;
  4392. o_addqchr(dest, ch);
  4393. }
  4394. }
  4395. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4396. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4397. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4398. {
  4399. while (1) {
  4400. int ch = i_getch(input);
  4401. if (ch == EOF) {
  4402. syntax_error_unterm_ch('"');
  4403. return 0;
  4404. }
  4405. if (ch == '"')
  4406. return 1;
  4407. if (ch == '\\') { /* \x. Copy both chars. */
  4408. o_addchr(dest, ch);
  4409. ch = i_getch(input);
  4410. }
  4411. o_addchr(dest, ch);
  4412. if (ch == '`') {
  4413. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4414. return 0;
  4415. o_addchr(dest, ch);
  4416. continue;
  4417. }
  4418. //if (ch == '$') ...
  4419. }
  4420. }
  4421. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4422. * \` quoting.
  4423. * "Within the backquoted style of command substitution, backslash
  4424. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4425. * The search for the matching backquote shall be satisfied by the first
  4426. * backquote found without a preceding backslash; during this search,
  4427. * if a non-escaped backquote is encountered within a shell comment,
  4428. * a here-document, an embedded command substitution of the $(command)
  4429. * form, or a quoted string, undefined results occur. A single-quoted
  4430. * or double-quoted string that begins, but does not end, within the
  4431. * "`...`" sequence produces undefined results."
  4432. * Example Output
  4433. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4434. */
  4435. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4436. {
  4437. while (1) {
  4438. int ch = i_getch(input);
  4439. if (ch == '`')
  4440. return 1;
  4441. if (ch == '\\') {
  4442. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4443. ch = i_getch(input);
  4444. if (ch != '`'
  4445. && ch != '$'
  4446. && ch != '\\'
  4447. && (!in_dquote || ch != '"')
  4448. ) {
  4449. o_addchr(dest, '\\');
  4450. }
  4451. }
  4452. if (ch == EOF) {
  4453. syntax_error_unterm_ch('`');
  4454. return 0;
  4455. }
  4456. o_addchr(dest, ch);
  4457. }
  4458. }
  4459. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4460. * quoting and nested ()s.
  4461. * "With the $(command) style of command substitution, all characters
  4462. * following the open parenthesis to the matching closing parenthesis
  4463. * constitute the command. Any valid shell script can be used for command,
  4464. * except a script consisting solely of redirections which produces
  4465. * unspecified results."
  4466. * Example Output
  4467. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4468. * echo $(echo 'TEST)' BEST) TEST) BEST
  4469. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4470. *
  4471. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4472. * can contain arbitrary constructs, just like $(cmd).
  4473. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4474. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4475. */
  4476. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4477. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4478. {
  4479. int ch;
  4480. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4481. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4482. char end_char2 = end_ch >> 8;
  4483. # endif
  4484. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4485. # if ENABLE_HUSH_INTERACTIVE
  4486. G.promptmode = 1; /* PS2 */
  4487. # endif
  4488. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4489. while (1) {
  4490. ch = i_getch(input);
  4491. if (ch == EOF) {
  4492. syntax_error_unterm_ch(end_ch);
  4493. return 0;
  4494. }
  4495. if (ch == end_ch
  4496. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4497. || ch == end_char2
  4498. # endif
  4499. ) {
  4500. if (!dbl)
  4501. break;
  4502. /* we look for closing )) of $((EXPR)) */
  4503. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4504. i_getch(input); /* eat second ')' */
  4505. break;
  4506. }
  4507. }
  4508. o_addchr(dest, ch);
  4509. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4510. if (ch == '(' || ch == '{') {
  4511. ch = (ch == '(' ? ')' : '}');
  4512. if (!add_till_closing_bracket(dest, input, ch))
  4513. return 0;
  4514. o_addchr(dest, ch);
  4515. continue;
  4516. }
  4517. if (ch == '\'') {
  4518. if (!add_till_single_quote(dest, input))
  4519. return 0;
  4520. o_addchr(dest, ch);
  4521. continue;
  4522. }
  4523. if (ch == '"') {
  4524. if (!add_till_double_quote(dest, input))
  4525. return 0;
  4526. o_addchr(dest, ch);
  4527. continue;
  4528. }
  4529. if (ch == '`') {
  4530. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4531. return 0;
  4532. o_addchr(dest, ch);
  4533. continue;
  4534. }
  4535. if (ch == '\\') {
  4536. /* \x. Copy verbatim. Important for \(, \) */
  4537. ch = i_getch(input);
  4538. if (ch == EOF) {
  4539. syntax_error_unterm_ch(end_ch);
  4540. return 0;
  4541. }
  4542. # if 0
  4543. if (ch == '\n') {
  4544. /* "backslash+newline", ignore both */
  4545. o_delchr(dest); /* undo insertion of '\' */
  4546. continue;
  4547. }
  4548. # endif
  4549. o_addchr(dest, ch);
  4550. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4551. continue;
  4552. }
  4553. }
  4554. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4555. return ch;
  4556. }
  4557. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4558. /* Return code: 0 for OK, 1 for syntax error */
  4559. #if BB_MMU
  4560. #define parse_dollar(as_string, dest, input, quote_mask) \
  4561. parse_dollar(dest, input, quote_mask)
  4562. #define as_string NULL
  4563. #endif
  4564. static int parse_dollar(o_string *as_string,
  4565. o_string *dest,
  4566. struct in_str *input, unsigned char quote_mask)
  4567. {
  4568. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4569. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4570. if (isalpha(ch)) {
  4571. make_var:
  4572. ch = i_getch(input);
  4573. nommu_addchr(as_string, ch);
  4574. /*make_var1:*/
  4575. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4576. while (1) {
  4577. debug_printf_parse(": '%c'\n", ch);
  4578. o_addchr(dest, ch | quote_mask);
  4579. quote_mask = 0;
  4580. ch = i_peek_and_eat_bkslash_nl(input);
  4581. if (!isalnum(ch) && ch != '_') {
  4582. /* End of variable name reached */
  4583. break;
  4584. }
  4585. ch = i_getch(input);
  4586. nommu_addchr(as_string, ch);
  4587. }
  4588. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4589. } else if (isdigit(ch)) {
  4590. make_one_char_var:
  4591. ch = i_getch(input);
  4592. nommu_addchr(as_string, ch);
  4593. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4594. debug_printf_parse(": '%c'\n", ch);
  4595. o_addchr(dest, ch | quote_mask);
  4596. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4597. } else switch (ch) {
  4598. case '$': /* pid */
  4599. case '!': /* last bg pid */
  4600. case '?': /* last exit code */
  4601. case '#': /* number of args */
  4602. case '*': /* args */
  4603. case '@': /* args */
  4604. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4605. goto make_one_char_var;
  4606. case '{': {
  4607. char len_single_ch;
  4608. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4609. ch = i_getch(input); /* eat '{' */
  4610. nommu_addchr(as_string, ch);
  4611. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4612. /* It should be ${?}, or ${#var},
  4613. * or even ${?+subst} - operator acting on a special variable,
  4614. * or the beginning of variable name.
  4615. */
  4616. if (ch == EOF
  4617. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4618. ) {
  4619. bad_dollar_syntax:
  4620. syntax_error_unterm_str("${name}");
  4621. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4622. return 0;
  4623. }
  4624. nommu_addchr(as_string, ch);
  4625. len_single_ch = ch;
  4626. ch |= quote_mask;
  4627. /* It's possible to just call add_till_closing_bracket() at this point.
  4628. * However, this regresses some of our testsuite cases
  4629. * which check invalid constructs like ${%}.
  4630. * Oh well... let's check that the var name part is fine... */
  4631. while (1) {
  4632. unsigned pos;
  4633. o_addchr(dest, ch);
  4634. debug_printf_parse(": '%c'\n", ch);
  4635. ch = i_getch(input);
  4636. nommu_addchr(as_string, ch);
  4637. if (ch == '}')
  4638. break;
  4639. if (!isalnum(ch) && ch != '_') {
  4640. unsigned end_ch;
  4641. unsigned char last_ch;
  4642. /* handle parameter expansions
  4643. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4644. */
  4645. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4646. if (len_single_ch != '#'
  4647. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4648. || i_peek(input) != '}'
  4649. ) {
  4650. goto bad_dollar_syntax;
  4651. }
  4652. /* else: it's "length of C" ${#C} op,
  4653. * where C is a single char
  4654. * special var name, e.g. ${#!}.
  4655. */
  4656. }
  4657. /* Eat everything until closing '}' (or ':') */
  4658. end_ch = '}';
  4659. if (BASH_SUBSTR
  4660. && ch == ':'
  4661. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4662. ) {
  4663. /* It's ${var:N[:M]} thing */
  4664. end_ch = '}' * 0x100 + ':';
  4665. }
  4666. if (BASH_PATTERN_SUBST
  4667. && ch == '/'
  4668. ) {
  4669. /* It's ${var/[/]pattern[/repl]} thing */
  4670. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4671. i_getch(input);
  4672. nommu_addchr(as_string, '/');
  4673. ch = '\\';
  4674. }
  4675. end_ch = '}' * 0x100 + '/';
  4676. }
  4677. o_addchr(dest, ch);
  4678. /* The pattern can't be empty.
  4679. * IOW: if the first char after "${v//" is a slash,
  4680. * it does not terminate the pattern - it's the first char of the pattern:
  4681. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4682. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4683. */
  4684. if (i_peek(input) == '/') {
  4685. o_addchr(dest, i_getch(input));
  4686. }
  4687. again:
  4688. if (!BB_MMU)
  4689. pos = dest->length;
  4690. #if ENABLE_HUSH_DOLLAR_OPS
  4691. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4692. if (last_ch == 0) /* error? */
  4693. return 0;
  4694. #else
  4695. # error Simple code to only allow ${var} is not implemented
  4696. #endif
  4697. if (as_string) {
  4698. o_addstr(as_string, dest->data + pos);
  4699. o_addchr(as_string, last_ch);
  4700. }
  4701. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4702. && (end_ch & 0xff00)
  4703. ) {
  4704. /* close the first block: */
  4705. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4706. /* while parsing N from ${var:N[:M]}
  4707. * or pattern from ${var/[/]pattern[/repl]} */
  4708. if ((end_ch & 0xff) == last_ch) {
  4709. /* got ':' or '/'- parse the rest */
  4710. end_ch = '}';
  4711. goto again;
  4712. }
  4713. /* got '}' */
  4714. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4715. /* it's ${var:N} - emulate :999999999 */
  4716. o_addstr(dest, "999999999");
  4717. } /* else: it's ${var/[/]pattern} */
  4718. }
  4719. break;
  4720. }
  4721. len_single_ch = 0; /* it can't be ${#C} op */
  4722. }
  4723. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4724. break;
  4725. }
  4726. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4727. case '(': {
  4728. unsigned pos;
  4729. ch = i_getch(input);
  4730. nommu_addchr(as_string, ch);
  4731. # if ENABLE_FEATURE_SH_MATH
  4732. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4733. ch = i_getch(input);
  4734. nommu_addchr(as_string, ch);
  4735. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4736. o_addchr(dest, quote_mask | '+');
  4737. if (!BB_MMU)
  4738. pos = dest->length;
  4739. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4740. return 0; /* error */
  4741. if (as_string) {
  4742. o_addstr(as_string, dest->data + pos);
  4743. o_addchr(as_string, ')');
  4744. o_addchr(as_string, ')');
  4745. }
  4746. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4747. break;
  4748. }
  4749. # endif
  4750. # if ENABLE_HUSH_TICK
  4751. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4752. o_addchr(dest, quote_mask | '`');
  4753. if (!BB_MMU)
  4754. pos = dest->length;
  4755. if (!add_till_closing_bracket(dest, input, ')'))
  4756. return 0; /* error */
  4757. if (as_string) {
  4758. o_addstr(as_string, dest->data + pos);
  4759. o_addchr(as_string, ')');
  4760. }
  4761. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4762. # endif
  4763. break;
  4764. }
  4765. #endif
  4766. case '_':
  4767. goto make_var;
  4768. #if 0
  4769. /* TODO: $_: */
  4770. /* $_ Shell or shell script name; or last argument of last command
  4771. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4772. * but in command's env, set to full pathname used to invoke it */
  4773. ch = i_getch(input);
  4774. nommu_addchr(as_string, ch);
  4775. ch = i_peek_and_eat_bkslash_nl(input);
  4776. if (isalnum(ch)) { /* it's $_name or $_123 */
  4777. ch = '_';
  4778. goto make_var1;
  4779. }
  4780. /* else: it's $_ */
  4781. #endif
  4782. default:
  4783. o_addQchr(dest, '$');
  4784. }
  4785. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4786. return 1;
  4787. #undef as_string
  4788. }
  4789. #if BB_MMU
  4790. #define encode_string(as_string, dest, input, dquote_end) \
  4791. encode_string(dest, input, dquote_end)
  4792. #define as_string NULL
  4793. #endif
  4794. static int encode_string(o_string *as_string,
  4795. o_string *dest,
  4796. struct in_str *input,
  4797. int dquote_end)
  4798. {
  4799. int ch;
  4800. int next;
  4801. again:
  4802. ch = i_getch(input);
  4803. if (ch != EOF)
  4804. nommu_addchr(as_string, ch);
  4805. if (ch == dquote_end) { /* may be only '"' or EOF */
  4806. debug_printf_parse("encode_string return 1 (ok)\n");
  4807. return 1;
  4808. }
  4809. /* note: can't move it above ch == dquote_end check! */
  4810. if (ch == EOF) {
  4811. syntax_error_unterm_ch('"');
  4812. return 0; /* error */
  4813. }
  4814. next = '\0';
  4815. if (ch != '\n') {
  4816. next = i_peek(input);
  4817. }
  4818. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4819. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4820. if (ch == '\\') {
  4821. if (next == EOF) {
  4822. /* Testcase: in interactive shell a file with
  4823. * echo "unterminated string\<eof>
  4824. * is sourced.
  4825. */
  4826. syntax_error_unterm_ch('"');
  4827. return 0; /* error */
  4828. }
  4829. /* bash:
  4830. * "The backslash retains its special meaning [in "..."]
  4831. * only when followed by one of the following characters:
  4832. * $, `, ", \, or <newline>. A double quote may be quoted
  4833. * within double quotes by preceding it with a backslash."
  4834. * NB: in (unquoted) heredoc, above does not apply to ",
  4835. * therefore we check for it by "next == dquote_end" cond.
  4836. */
  4837. if (next == dquote_end || strchr("$`\\\n", next)) {
  4838. ch = i_getch(input); /* eat next */
  4839. if (ch == '\n')
  4840. goto again; /* skip \<newline> */
  4841. } /* else: ch remains == '\\', and we double it below: */
  4842. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4843. nommu_addchr(as_string, ch);
  4844. goto again;
  4845. }
  4846. if (ch == '$') {
  4847. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4848. debug_printf_parse("encode_string return 0: "
  4849. "parse_dollar returned 0 (error)\n");
  4850. return 0;
  4851. }
  4852. goto again;
  4853. }
  4854. #if ENABLE_HUSH_TICK
  4855. if (ch == '`') {
  4856. //unsigned pos = dest->length;
  4857. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4858. o_addchr(dest, 0x80 | '`');
  4859. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4860. return 0; /* error */
  4861. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4862. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4863. goto again;
  4864. }
  4865. #endif
  4866. o_addQchr(dest, ch);
  4867. goto again;
  4868. #undef as_string
  4869. }
  4870. /*
  4871. * Scan input until EOF or end_trigger char.
  4872. * Return a list of pipes to execute, or NULL on EOF
  4873. * or if end_trigger character is met.
  4874. * On syntax error, exit if shell is not interactive,
  4875. * reset parsing machinery and start parsing anew,
  4876. * or return ERR_PTR.
  4877. */
  4878. static struct pipe *parse_stream(char **pstring,
  4879. int *heredoc_cnt_ptr,
  4880. struct in_str *input,
  4881. int end_trigger)
  4882. {
  4883. struct parse_context ctx;
  4884. int heredoc_cnt;
  4885. /* Single-quote triggers a bypass of the main loop until its mate is
  4886. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4887. */
  4888. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4889. end_trigger ? end_trigger : 'X');
  4890. debug_enter();
  4891. initialize_context(&ctx);
  4892. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4893. * Preventing this:
  4894. */
  4895. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4896. /* We used to separate words on $IFS here. This was wrong.
  4897. * $IFS is used only for word splitting when $var is expanded,
  4898. * here we should use blank chars as separators, not $IFS
  4899. */
  4900. heredoc_cnt = 0;
  4901. while (1) {
  4902. const char *is_blank;
  4903. const char *is_special;
  4904. int ch;
  4905. int next;
  4906. int redir_fd;
  4907. redir_type redir_style;
  4908. ch = i_getch(input);
  4909. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4910. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4911. if (ch == EOF) {
  4912. struct pipe *pi;
  4913. if (heredoc_cnt) {
  4914. syntax_error_unterm_str("here document");
  4915. goto parse_error;
  4916. }
  4917. if (end_trigger == ')') {
  4918. syntax_error_unterm_ch('(');
  4919. goto parse_error;
  4920. }
  4921. if (end_trigger == '}') {
  4922. syntax_error_unterm_ch('{');
  4923. goto parse_error;
  4924. }
  4925. if (done_word(&ctx)) {
  4926. goto parse_error;
  4927. }
  4928. o_free_and_set_NULL(&ctx.word);
  4929. done_pipe(&ctx, PIPE_SEQ);
  4930. pi = ctx.list_head;
  4931. /* If we got nothing... */
  4932. /* (this makes bare "&" cmd a no-op.
  4933. * bash says: "syntax error near unexpected token '&'") */
  4934. if (pi->num_cmds == 0
  4935. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4936. ) {
  4937. free_pipe_list(pi);
  4938. pi = NULL;
  4939. }
  4940. #if !BB_MMU
  4941. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4942. if (pstring)
  4943. *pstring = ctx.as_string.data;
  4944. else
  4945. o_free(&ctx.as_string);
  4946. #endif
  4947. // heredoc_cnt must be 0 here anyway
  4948. //if (heredoc_cnt_ptr)
  4949. // *heredoc_cnt_ptr = heredoc_cnt;
  4950. debug_leave();
  4951. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4952. debug_printf_parse("parse_stream return %p\n", pi);
  4953. return pi;
  4954. }
  4955. /* Handle "'" and "\" first, as they won't play nice with
  4956. * i_peek_and_eat_bkslash_nl() anyway:
  4957. * echo z\\
  4958. * and
  4959. * echo '\
  4960. * '
  4961. * would break.
  4962. */
  4963. if (ch == '\\') {
  4964. ch = i_getch(input);
  4965. if (ch == '\n')
  4966. continue; /* drop \<newline>, get next char */
  4967. nommu_addchr(&ctx.as_string, '\\');
  4968. o_addchr(&ctx.word, '\\');
  4969. if (ch == EOF) {
  4970. /* Testcase: eval 'echo Ok\' */
  4971. /* bash-4.3.43 was removing backslash,
  4972. * but 4.4.19 retains it, most other shells too
  4973. */
  4974. continue; /* get next char */
  4975. }
  4976. /* Example: echo Hello \2>file
  4977. * we need to know that word 2 is quoted
  4978. */
  4979. ctx.word.has_quoted_part = 1;
  4980. nommu_addchr(&ctx.as_string, ch);
  4981. o_addchr(&ctx.word, ch);
  4982. continue; /* get next char */
  4983. }
  4984. nommu_addchr(&ctx.as_string, ch);
  4985. if (ch == '\'') {
  4986. ctx.word.has_quoted_part = 1;
  4987. next = i_getch(input);
  4988. if (next == '\'' && !ctx.pending_redirect)
  4989. goto insert_empty_quoted_str_marker;
  4990. ch = next;
  4991. while (1) {
  4992. if (ch == EOF) {
  4993. syntax_error_unterm_ch('\'');
  4994. goto parse_error;
  4995. }
  4996. nommu_addchr(&ctx.as_string, ch);
  4997. if (ch == '\'')
  4998. break;
  4999. if (ch == SPECIAL_VAR_SYMBOL) {
  5000. /* Convert raw ^C to corresponding special variable reference */
  5001. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5002. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5003. }
  5004. o_addqchr(&ctx.word, ch);
  5005. ch = i_getch(input);
  5006. }
  5007. continue; /* get next char */
  5008. }
  5009. next = '\0';
  5010. if (ch != '\n')
  5011. next = i_peek_and_eat_bkslash_nl(input);
  5012. is_special = "{}<>;&|()#" /* special outside of "str" */
  5013. "$\"" IF_HUSH_TICK("`") /* always special */
  5014. SPECIAL_VAR_SYMBOL_STR;
  5015. /* Are { and } special here? */
  5016. if (ctx.command->argv /* word [word]{... - non-special */
  5017. || ctx.word.length /* word{... - non-special */
  5018. || ctx.word.has_quoted_part /* ""{... - non-special */
  5019. || (next != ';' /* }; - special */
  5020. && next != ')' /* }) - special */
  5021. && next != '(' /* {( - special */
  5022. && next != '&' /* }& and }&& ... - special */
  5023. && next != '|' /* }|| ... - special */
  5024. && !strchr(defifs, next) /* {word - non-special */
  5025. )
  5026. ) {
  5027. /* They are not special, skip "{}" */
  5028. is_special += 2;
  5029. }
  5030. is_special = strchr(is_special, ch);
  5031. is_blank = strchr(defifs, ch);
  5032. if (!is_special && !is_blank) { /* ordinary char */
  5033. ordinary_char:
  5034. o_addQchr(&ctx.word, ch);
  5035. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5036. || ctx.is_assignment == WORD_IS_KEYWORD)
  5037. && ch == '='
  5038. && endofname(ctx.word.data)[0] == '='
  5039. ) {
  5040. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5041. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5042. }
  5043. continue;
  5044. }
  5045. if (is_blank) {
  5046. #if ENABLE_HUSH_LINENO_VAR
  5047. /* Case:
  5048. * "while ...; do<whitespace><newline>
  5049. * cmd ..."
  5050. * would think that "cmd" starts in <whitespace> -
  5051. * i.e., at the previous line.
  5052. * We need to skip all whitespace before newlines.
  5053. */
  5054. while (ch != '\n') {
  5055. next = i_peek(input);
  5056. if (next != ' ' && next != '\t' && next != '\n')
  5057. break; /* next char is not ws */
  5058. ch = i_getch(input);
  5059. }
  5060. /* ch == last eaten whitespace char */
  5061. #endif
  5062. if (done_word(&ctx)) {
  5063. goto parse_error;
  5064. }
  5065. if (ch == '\n') {
  5066. /* Is this a case when newline is simply ignored?
  5067. * Some examples:
  5068. * "cmd | <newline> cmd ..."
  5069. * "case ... in <newline> word) ..."
  5070. */
  5071. if (IS_NULL_CMD(ctx.command)
  5072. && ctx.word.length == 0
  5073. && !ctx.word.has_quoted_part
  5074. && heredoc_cnt == 0
  5075. ) {
  5076. /* This newline can be ignored. But...
  5077. * Without check #1, interactive shell
  5078. * ignores even bare <newline>,
  5079. * and shows the continuation prompt:
  5080. * ps1_prompt$ <enter>
  5081. * ps2> _ <=== wrong, should be ps1
  5082. * Without check #2, "cmd & <newline>"
  5083. * is similarly mistreated.
  5084. * (BTW, this makes "cmd & cmd"
  5085. * and "cmd && cmd" non-orthogonal.
  5086. * Really, ask yourself, why
  5087. * "cmd && <newline>" doesn't start
  5088. * cmd but waits for more input?
  5089. * The only reason is that it might be
  5090. * a "cmd1 && <nl> cmd2 &" construct,
  5091. * cmd1 may need to run in BG).
  5092. */
  5093. struct pipe *pi = ctx.list_head;
  5094. if (pi->num_cmds != 0 /* check #1 */
  5095. && pi->followup != PIPE_BG /* check #2 */
  5096. ) {
  5097. continue;
  5098. }
  5099. }
  5100. /* Treat newline as a command separator. */
  5101. done_pipe(&ctx, PIPE_SEQ);
  5102. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5103. if (heredoc_cnt) {
  5104. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5105. if (heredoc_cnt != 0)
  5106. goto parse_error;
  5107. }
  5108. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5109. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5110. ch = ';';
  5111. /* note: if (is_blank) continue;
  5112. * will still trigger for us */
  5113. }
  5114. }
  5115. /* "cmd}" or "cmd }..." without semicolon or &:
  5116. * } is an ordinary char in this case, even inside { cmd; }
  5117. * Pathological example: { ""}; } should exec "}" cmd
  5118. */
  5119. if (ch == '}') {
  5120. if (ctx.word.length != 0 /* word} */
  5121. || ctx.word.has_quoted_part /* ""} */
  5122. ) {
  5123. goto ordinary_char;
  5124. }
  5125. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5126. /* Generally, there should be semicolon: "cmd; }"
  5127. * However, bash allows to omit it if "cmd" is
  5128. * a group. Examples:
  5129. * { { echo 1; } }
  5130. * {(echo 1)}
  5131. * { echo 0 >&2 | { echo 1; } }
  5132. * { while false; do :; done }
  5133. * { case a in b) ;; esac }
  5134. */
  5135. if (ctx.command->group)
  5136. goto term_group;
  5137. goto ordinary_char;
  5138. }
  5139. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5140. /* Can't be an end of {cmd}, skip the check */
  5141. goto skip_end_trigger;
  5142. /* else: } does terminate a group */
  5143. }
  5144. term_group:
  5145. if (end_trigger && end_trigger == ch
  5146. && (ch != ';' || heredoc_cnt == 0)
  5147. #if ENABLE_HUSH_CASE
  5148. && (ch != ')'
  5149. || ctx.ctx_res_w != RES_MATCH
  5150. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5151. )
  5152. #endif
  5153. ) {
  5154. if (done_word(&ctx)) {
  5155. goto parse_error;
  5156. }
  5157. done_pipe(&ctx, PIPE_SEQ);
  5158. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5159. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5160. /* Do we sit outside of any if's, loops or case's? */
  5161. if (!HAS_KEYWORDS
  5162. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5163. ) {
  5164. o_free_and_set_NULL(&ctx.word);
  5165. #if !BB_MMU
  5166. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5167. if (pstring)
  5168. *pstring = ctx.as_string.data;
  5169. else
  5170. o_free(&ctx.as_string);
  5171. #endif
  5172. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5173. /* Example: bare "{ }", "()" */
  5174. G.last_exitcode = 2; /* bash compat */
  5175. syntax_error_unexpected_ch(ch);
  5176. goto parse_error2;
  5177. }
  5178. if (heredoc_cnt_ptr)
  5179. *heredoc_cnt_ptr = heredoc_cnt;
  5180. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5181. debug_printf_parse("parse_stream return %p: "
  5182. "end_trigger char found\n",
  5183. ctx.list_head);
  5184. debug_leave();
  5185. return ctx.list_head;
  5186. }
  5187. }
  5188. if (is_blank)
  5189. continue;
  5190. /* Catch <, > before deciding whether this word is
  5191. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5192. switch (ch) {
  5193. case '>':
  5194. redir_fd = redirect_opt_num(&ctx.word);
  5195. if (done_word(&ctx)) {
  5196. goto parse_error;
  5197. }
  5198. redir_style = REDIRECT_OVERWRITE;
  5199. if (next == '>') {
  5200. redir_style = REDIRECT_APPEND;
  5201. ch = i_getch(input);
  5202. nommu_addchr(&ctx.as_string, ch);
  5203. }
  5204. #if 0
  5205. else if (next == '(') {
  5206. syntax_error(">(process) not supported");
  5207. goto parse_error;
  5208. }
  5209. #endif
  5210. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5211. goto parse_error;
  5212. continue; /* get next char */
  5213. case '<':
  5214. redir_fd = redirect_opt_num(&ctx.word);
  5215. if (done_word(&ctx)) {
  5216. goto parse_error;
  5217. }
  5218. redir_style = REDIRECT_INPUT;
  5219. if (next == '<') {
  5220. redir_style = REDIRECT_HEREDOC;
  5221. heredoc_cnt++;
  5222. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5223. ch = i_getch(input);
  5224. nommu_addchr(&ctx.as_string, ch);
  5225. } else if (next == '>') {
  5226. redir_style = REDIRECT_IO;
  5227. ch = i_getch(input);
  5228. nommu_addchr(&ctx.as_string, ch);
  5229. }
  5230. #if 0
  5231. else if (next == '(') {
  5232. syntax_error("<(process) not supported");
  5233. goto parse_error;
  5234. }
  5235. #endif
  5236. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5237. goto parse_error;
  5238. continue; /* get next char */
  5239. case '#':
  5240. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5241. /* skip "#comment" */
  5242. /* note: we do not add it to &ctx.as_string */
  5243. /* TODO: in bash:
  5244. * comment inside $() goes to the next \n, even inside quoted string (!):
  5245. * cmd "$(cmd2 #comment)" - syntax error
  5246. * cmd "`cmd2 #comment`" - ok
  5247. * We accept both (comment ends where command subst ends, in both cases).
  5248. */
  5249. while (1) {
  5250. ch = i_peek(input);
  5251. if (ch == '\n') {
  5252. nommu_addchr(&ctx.as_string, '\n');
  5253. break;
  5254. }
  5255. ch = i_getch(input);
  5256. if (ch == EOF)
  5257. break;
  5258. }
  5259. continue; /* get next char */
  5260. }
  5261. break;
  5262. }
  5263. skip_end_trigger:
  5264. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5265. /* check that we are not in word in "a=1 2>word b=1": */
  5266. && !ctx.pending_redirect
  5267. ) {
  5268. /* ch is a special char and thus this word
  5269. * cannot be an assignment */
  5270. ctx.is_assignment = NOT_ASSIGNMENT;
  5271. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5272. }
  5273. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5274. switch (ch) {
  5275. case SPECIAL_VAR_SYMBOL:
  5276. /* Convert raw ^C to corresponding special variable reference */
  5277. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5278. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5279. /* fall through */
  5280. case '#':
  5281. /* non-comment #: "echo a#b" etc */
  5282. o_addchr(&ctx.word, ch);
  5283. continue; /* get next char */
  5284. case '$':
  5285. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5286. debug_printf_parse("parse_stream parse error: "
  5287. "parse_dollar returned 0 (error)\n");
  5288. goto parse_error;
  5289. }
  5290. continue; /* get next char */
  5291. case '"':
  5292. ctx.word.has_quoted_part = 1;
  5293. if (next == '"' && !ctx.pending_redirect) {
  5294. i_getch(input); /* eat second " */
  5295. insert_empty_quoted_str_marker:
  5296. nommu_addchr(&ctx.as_string, next);
  5297. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5298. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5299. continue; /* get next char */
  5300. }
  5301. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5302. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5303. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5304. goto parse_error;
  5305. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5306. continue; /* get next char */
  5307. #if ENABLE_HUSH_TICK
  5308. case '`': {
  5309. USE_FOR_NOMMU(unsigned pos;)
  5310. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5311. o_addchr(&ctx.word, '`');
  5312. USE_FOR_NOMMU(pos = ctx.word.length;)
  5313. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5314. goto parse_error;
  5315. # if !BB_MMU
  5316. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5317. o_addchr(&ctx.as_string, '`');
  5318. # endif
  5319. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5320. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5321. continue; /* get next char */
  5322. }
  5323. #endif
  5324. case ';':
  5325. #if ENABLE_HUSH_CASE
  5326. case_semi:
  5327. #endif
  5328. if (done_word(&ctx)) {
  5329. goto parse_error;
  5330. }
  5331. done_pipe(&ctx, PIPE_SEQ);
  5332. #if ENABLE_HUSH_CASE
  5333. /* Eat multiple semicolons, detect
  5334. * whether it means something special */
  5335. while (1) {
  5336. ch = i_peek_and_eat_bkslash_nl(input);
  5337. if (ch != ';')
  5338. break;
  5339. ch = i_getch(input);
  5340. nommu_addchr(&ctx.as_string, ch);
  5341. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5342. ctx.ctx_dsemicolon = 1;
  5343. ctx.ctx_res_w = RES_MATCH;
  5344. break;
  5345. }
  5346. }
  5347. #endif
  5348. new_cmd:
  5349. /* We just finished a cmd. New one may start
  5350. * with an assignment */
  5351. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5352. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5353. continue; /* get next char */
  5354. case '&':
  5355. if (done_word(&ctx)) {
  5356. goto parse_error;
  5357. }
  5358. if (next == '&') {
  5359. ch = i_getch(input);
  5360. nommu_addchr(&ctx.as_string, ch);
  5361. done_pipe(&ctx, PIPE_AND);
  5362. } else {
  5363. done_pipe(&ctx, PIPE_BG);
  5364. }
  5365. goto new_cmd;
  5366. case '|':
  5367. if (done_word(&ctx)) {
  5368. goto parse_error;
  5369. }
  5370. #if ENABLE_HUSH_CASE
  5371. if (ctx.ctx_res_w == RES_MATCH)
  5372. break; /* we are in case's "word | word)" */
  5373. #endif
  5374. if (next == '|') { /* || */
  5375. ch = i_getch(input);
  5376. nommu_addchr(&ctx.as_string, ch);
  5377. done_pipe(&ctx, PIPE_OR);
  5378. } else {
  5379. /* we could pick up a file descriptor choice here
  5380. * with redirect_opt_num(), but bash doesn't do it.
  5381. * "echo foo 2| cat" yields "foo 2". */
  5382. done_command(&ctx);
  5383. }
  5384. goto new_cmd;
  5385. case '(':
  5386. #if ENABLE_HUSH_CASE
  5387. /* "case... in [(]word)..." - skip '(' */
  5388. if (ctx.ctx_res_w == RES_MATCH
  5389. && ctx.command->argv == NULL /* not (word|(... */
  5390. && ctx.word.length == 0 /* not word(... */
  5391. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5392. ) {
  5393. continue; /* get next char */
  5394. }
  5395. #endif
  5396. /* fall through */
  5397. case '{': {
  5398. int n = parse_group(&ctx, input, ch);
  5399. if (n < 0) {
  5400. goto parse_error;
  5401. }
  5402. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5403. heredoc_cnt += n;
  5404. goto new_cmd;
  5405. }
  5406. case ')':
  5407. #if ENABLE_HUSH_CASE
  5408. if (ctx.ctx_res_w == RES_MATCH)
  5409. goto case_semi;
  5410. #endif
  5411. case '}':
  5412. /* proper use of this character is caught by end_trigger:
  5413. * if we see {, we call parse_group(..., end_trigger='}')
  5414. * and it will match } earlier (not here). */
  5415. G.last_exitcode = 2;
  5416. syntax_error_unexpected_ch(ch);
  5417. goto parse_error2;
  5418. default:
  5419. if (HUSH_DEBUG)
  5420. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5421. }
  5422. } /* while (1) */
  5423. parse_error:
  5424. G.last_exitcode = 1;
  5425. parse_error2:
  5426. {
  5427. struct parse_context *pctx;
  5428. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5429. /* Clean up allocated tree.
  5430. * Sample for finding leaks on syntax error recovery path.
  5431. * Run it from interactive shell, watch pmap `pidof hush`.
  5432. * while if false; then false; fi; do break; fi
  5433. * Samples to catch leaks at execution:
  5434. * while if (true | { true;}); then echo ok; fi; do break; done
  5435. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5436. */
  5437. pctx = &ctx;
  5438. do {
  5439. /* Update pipe/command counts,
  5440. * otherwise freeing may miss some */
  5441. done_pipe(pctx, PIPE_SEQ);
  5442. debug_printf_clean("freeing list %p from ctx %p\n",
  5443. pctx->list_head, pctx);
  5444. debug_print_tree(pctx->list_head, 0);
  5445. free_pipe_list(pctx->list_head);
  5446. debug_printf_clean("freed list %p\n", pctx->list_head);
  5447. #if !BB_MMU
  5448. o_free(&pctx->as_string);
  5449. #endif
  5450. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5451. if (pctx != &ctx) {
  5452. free(pctx);
  5453. }
  5454. IF_HAS_KEYWORDS(pctx = p2;)
  5455. } while (HAS_KEYWORDS && pctx);
  5456. o_free(&ctx.word);
  5457. #if !BB_MMU
  5458. if (pstring)
  5459. *pstring = NULL;
  5460. #endif
  5461. debug_leave();
  5462. return ERR_PTR;
  5463. }
  5464. }
  5465. /*** Execution routines ***/
  5466. /* Expansion can recurse, need forward decls: */
  5467. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5468. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5469. expand_string_to_string(str)
  5470. #endif
  5471. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5472. #if ENABLE_HUSH_TICK
  5473. static int process_command_subs(o_string *dest, const char *s);
  5474. #endif
  5475. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5476. /* expand_strvec_to_strvec() takes a list of strings, expands
  5477. * all variable references within and returns a pointer to
  5478. * a list of expanded strings, possibly with larger number
  5479. * of strings. (Think VAR="a b"; echo $VAR).
  5480. * This new list is allocated as a single malloc block.
  5481. * NULL-terminated list of char* pointers is at the beginning of it,
  5482. * followed by strings themselves.
  5483. * Caller can deallocate entire list by single free(list). */
  5484. /* A horde of its helpers come first: */
  5485. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5486. {
  5487. while (--len >= 0) {
  5488. char c = *str++;
  5489. #if ENABLE_HUSH_BRACE_EXPANSION
  5490. if (c == '{' || c == '}') {
  5491. /* { -> \{, } -> \} */
  5492. o_addchr(o, '\\');
  5493. /* And now we want to add { or } and continue:
  5494. * o_addchr(o, c);
  5495. * continue;
  5496. * luckily, just falling through achieves this.
  5497. */
  5498. }
  5499. #endif
  5500. o_addchr(o, c);
  5501. if (c == '\\') {
  5502. /* \z -> \\\z; \<eol> -> \\<eol> */
  5503. o_addchr(o, '\\');
  5504. if (len) {
  5505. len--;
  5506. o_addchr(o, '\\');
  5507. o_addchr(o, *str++);
  5508. }
  5509. }
  5510. }
  5511. }
  5512. /* Store given string, finalizing the word and starting new one whenever
  5513. * we encounter IFS char(s). This is used for expanding variable values.
  5514. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5515. * Return in output->ended_in_ifs:
  5516. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5517. */
  5518. static int expand_on_ifs(o_string *output, int n, const char *str)
  5519. {
  5520. int last_is_ifs = 0;
  5521. while (1) {
  5522. int word_len;
  5523. if (!*str) /* EOL - do not finalize word */
  5524. break;
  5525. word_len = strcspn(str, G.ifs);
  5526. if (word_len) {
  5527. /* We have WORD_LEN leading non-IFS chars */
  5528. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5529. o_addblock(output, str, word_len);
  5530. } else {
  5531. /* Protect backslashes against globbing up :)
  5532. * Example: "v='\*'; echo b$v" prints "b\*"
  5533. * (and does not try to glob on "*")
  5534. */
  5535. o_addblock_duplicate_backslash(output, str, word_len);
  5536. /*/ Why can't we do it easier? */
  5537. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5538. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5539. }
  5540. last_is_ifs = 0;
  5541. str += word_len;
  5542. if (!*str) /* EOL - do not finalize word */
  5543. break;
  5544. }
  5545. /* We know str here points to at least one IFS char */
  5546. last_is_ifs = 1;
  5547. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5548. if (!*str) /* EOL - do not finalize word */
  5549. break;
  5550. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5551. && strchr(G.ifs, *str) /* the second check would fail */
  5552. ) {
  5553. /* This is a non-whitespace $IFS char */
  5554. /* Skip it and IFS whitespace chars, start new word */
  5555. str++;
  5556. str += strspn(str, G.ifs_whitespace);
  5557. goto new_word;
  5558. }
  5559. /* Start new word... but not always! */
  5560. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5561. if (output->has_quoted_part
  5562. /*
  5563. * Case "v=' a'; echo $v":
  5564. * here nothing precedes the space in $v expansion,
  5565. * therefore we should not finish the word
  5566. * (IOW: if there *is* word to finalize, only then do it):
  5567. * It's okay if this accesses the byte before first argv[]:
  5568. * past call to o_save_ptr() cleared it to zero byte
  5569. * (grep for -prev-ifs-check-).
  5570. */
  5571. || output->data[output->length - 1]
  5572. ) {
  5573. new_word:
  5574. o_addchr(output, '\0');
  5575. debug_print_list("expand_on_ifs", output, n);
  5576. n = o_save_ptr(output, n);
  5577. }
  5578. }
  5579. output->ended_in_ifs = last_is_ifs;
  5580. debug_print_list("expand_on_ifs[1]", output, n);
  5581. return n;
  5582. }
  5583. /* Helper to expand $((...)) and heredoc body. These act as if
  5584. * they are in double quotes, with the exception that they are not :).
  5585. * Just the rules are similar: "expand only $var and `cmd`"
  5586. *
  5587. * Returns malloced string.
  5588. * As an optimization, we return NULL if expansion is not needed.
  5589. */
  5590. static char *encode_then_expand_string(const char *str)
  5591. {
  5592. char *exp_str;
  5593. struct in_str input;
  5594. o_string dest = NULL_O_STRING;
  5595. const char *cp;
  5596. cp = str;
  5597. for (;;) {
  5598. if (!*cp) return NULL; /* string has no special chars */
  5599. if (*cp == '$') break;
  5600. if (*cp == '\\') break;
  5601. #if ENABLE_HUSH_TICK
  5602. if (*cp == '`') break;
  5603. #endif
  5604. cp++;
  5605. }
  5606. /* We need to expand. Example:
  5607. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5608. */
  5609. setup_string_in_str(&input, str);
  5610. encode_string(NULL, &dest, &input, EOF);
  5611. //TODO: error check (encode_string returns 0 on error)?
  5612. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5613. exp_str = expand_string_to_string(dest.data,
  5614. EXP_FLAG_ESC_GLOB_CHARS,
  5615. /*unbackslash:*/ 1
  5616. );
  5617. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5618. o_free(&dest);
  5619. return exp_str;
  5620. }
  5621. static const char *first_special_char_in_vararg(const char *cp)
  5622. {
  5623. for (;;) {
  5624. if (!*cp) return NULL; /* string has no special chars */
  5625. if (*cp == '$') return cp;
  5626. if (*cp == '\\') return cp;
  5627. if (*cp == '\'') return cp;
  5628. if (*cp == '"') return cp;
  5629. #if ENABLE_HUSH_TICK
  5630. if (*cp == '`') return cp;
  5631. #endif
  5632. /* dquoted "${x:+ARG}" should not glob, therefore
  5633. * '*' et al require some non-literal processing: */
  5634. if (*cp == '*') return cp;
  5635. if (*cp == '?') return cp;
  5636. if (*cp == '[') return cp;
  5637. cp++;
  5638. }
  5639. }
  5640. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5641. * These can contain single- and double-quoted strings,
  5642. * and treated as if the ARG string is initially unquoted. IOW:
  5643. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5644. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5645. * (word splitting and globbing of the ${var...} result).
  5646. */
  5647. #if !BASH_PATTERN_SUBST
  5648. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5649. encode_then_expand_vararg(str, handle_squotes)
  5650. #endif
  5651. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5652. {
  5653. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5654. const int do_unbackslash = 0;
  5655. #endif
  5656. char *exp_str;
  5657. struct in_str input;
  5658. o_string dest = NULL_O_STRING;
  5659. if (!first_special_char_in_vararg(str)) {
  5660. /* string has no special chars */
  5661. return NULL;
  5662. }
  5663. setup_string_in_str(&input, str);
  5664. dest.data = xzalloc(1); /* start as "", not as NULL */
  5665. exp_str = NULL;
  5666. for (;;) {
  5667. int ch;
  5668. ch = i_getch(&input);
  5669. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5670. __func__, ch, ch, !!dest.o_expflags);
  5671. if (!dest.o_expflags) {
  5672. if (ch == EOF)
  5673. break;
  5674. if (handle_squotes && ch == '\'') {
  5675. if (!add_till_single_quote_dquoted(&dest, &input))
  5676. goto ret; /* error */
  5677. continue;
  5678. }
  5679. }
  5680. if (ch == EOF) {
  5681. syntax_error_unterm_ch('"');
  5682. goto ret; /* error */
  5683. }
  5684. if (ch == '"') {
  5685. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5686. continue;
  5687. }
  5688. if (ch == '\\') {
  5689. ch = i_getch(&input);
  5690. if (ch == EOF) {
  5691. //example? error message? syntax_error_unterm_ch('"');
  5692. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5693. goto ret;
  5694. }
  5695. o_addqchr(&dest, ch);
  5696. continue;
  5697. }
  5698. if (ch == '$') {
  5699. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5700. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5701. goto ret;
  5702. }
  5703. continue;
  5704. }
  5705. #if ENABLE_HUSH_TICK
  5706. if (ch == '`') {
  5707. //unsigned pos = dest->length;
  5708. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5709. o_addchr(&dest, 0x80 | '`');
  5710. if (!add_till_backquote(&dest, &input,
  5711. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5712. )
  5713. ) {
  5714. goto ret; /* error */
  5715. }
  5716. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5717. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5718. continue;
  5719. }
  5720. #endif
  5721. o_addQchr(&dest, ch);
  5722. } /* for (;;) */
  5723. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5724. exp_str = expand_string_to_string(dest.data,
  5725. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5726. do_unbackslash
  5727. );
  5728. ret:
  5729. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5730. o_free(&dest);
  5731. return exp_str;
  5732. }
  5733. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5734. */
  5735. static int encode_then_append_var_plusminus(o_string *output, int n,
  5736. char *str, int dquoted)
  5737. {
  5738. struct in_str input;
  5739. o_string dest = NULL_O_STRING;
  5740. if (!first_special_char_in_vararg(str)
  5741. && '\0' == str[strcspn(str, G.ifs)]
  5742. ) {
  5743. /* string has no special chars
  5744. * && string has no $IFS chars
  5745. */
  5746. if (dquoted) {
  5747. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5748. * set -- "${notexist-}"; echo $#
  5749. */
  5750. output->has_quoted_part = 1;
  5751. }
  5752. return expand_vars_to_list(output, n, str);
  5753. }
  5754. setup_string_in_str(&input, str);
  5755. for (;;) {
  5756. int ch;
  5757. ch = i_getch(&input);
  5758. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5759. __func__, ch, ch, dest.o_expflags);
  5760. if (!dest.o_expflags) {
  5761. if (ch == EOF)
  5762. break;
  5763. if (!dquoted && strchr(G.ifs, ch)) {
  5764. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5765. * do not assume we are at the start of the word (PREFIX above).
  5766. */
  5767. if (dest.data) {
  5768. n = expand_vars_to_list(output, n, dest.data);
  5769. o_free_and_set_NULL(&dest);
  5770. o_addchr(output, '\0');
  5771. n = o_save_ptr(output, n); /* create next word */
  5772. } else
  5773. if (output->length != o_get_last_ptr(output, n)
  5774. || output->has_quoted_part
  5775. ) {
  5776. /* For these cases:
  5777. * f() { for i; do echo "|$i|"; done; }; x=x
  5778. * f a${x:+ }b # 1st condition
  5779. * |a|
  5780. * |b|
  5781. * f ""${x:+ }b # 2nd condition
  5782. * ||
  5783. * |b|
  5784. */
  5785. o_addchr(output, '\0');
  5786. n = o_save_ptr(output, n); /* create next word */
  5787. }
  5788. continue;
  5789. }
  5790. if (!dquoted && ch == '\'') {
  5791. if (!add_till_single_quote_dquoted(&dest, &input))
  5792. goto ret; /* error */
  5793. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5794. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5795. continue;
  5796. }
  5797. }
  5798. if (ch == EOF) {
  5799. syntax_error_unterm_ch('"');
  5800. goto ret; /* error */
  5801. }
  5802. if (ch == '"') {
  5803. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5804. if (dest.o_expflags) {
  5805. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5806. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5807. }
  5808. continue;
  5809. }
  5810. if (ch == '\\') {
  5811. ch = i_getch(&input);
  5812. if (ch == EOF) {
  5813. //example? error message? syntax_error_unterm_ch('"');
  5814. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5815. goto ret;
  5816. }
  5817. o_addqchr(&dest, ch);
  5818. continue;
  5819. }
  5820. if (ch == '$') {
  5821. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5822. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5823. goto ret;
  5824. }
  5825. continue;
  5826. }
  5827. #if ENABLE_HUSH_TICK
  5828. if (ch == '`') {
  5829. //unsigned pos = dest->length;
  5830. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5831. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5832. if (!add_till_backquote(&dest, &input,
  5833. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5834. )
  5835. ) {
  5836. goto ret; /* error */
  5837. }
  5838. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5839. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5840. continue;
  5841. }
  5842. #endif
  5843. if (dquoted) {
  5844. /* Always glob-protect if in dquotes:
  5845. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5846. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5847. */
  5848. o_addqchr(&dest, ch);
  5849. } else {
  5850. /* Glob-protect only if char is quoted:
  5851. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5852. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5853. */
  5854. o_addQchr(&dest, ch);
  5855. }
  5856. } /* for (;;) */
  5857. if (dest.data) {
  5858. n = expand_vars_to_list(output, n, dest.data);
  5859. }
  5860. ret:
  5861. o_free(&dest);
  5862. return n;
  5863. }
  5864. #if ENABLE_FEATURE_SH_MATH
  5865. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5866. {
  5867. arith_state_t math_state;
  5868. arith_t res;
  5869. char *exp_str;
  5870. math_state.lookupvar = get_local_var_value;
  5871. math_state.setvar = set_local_var_from_halves;
  5872. //math_state.endofname = endofname;
  5873. exp_str = encode_then_expand_string(arg);
  5874. res = arith(&math_state, exp_str ? exp_str : arg);
  5875. free(exp_str);
  5876. if (errmsg_p)
  5877. *errmsg_p = math_state.errmsg;
  5878. if (math_state.errmsg)
  5879. msg_and_die_if_script(math_state.errmsg);
  5880. return res;
  5881. }
  5882. #endif
  5883. #if BASH_PATTERN_SUBST
  5884. /* ${var/[/]pattern[/repl]} helpers */
  5885. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5886. {
  5887. while (1) {
  5888. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5889. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5890. if (end) {
  5891. *size = end - val;
  5892. return val;
  5893. }
  5894. if (*val == '\0')
  5895. return NULL;
  5896. /* Optimization: if "*pat" did not match the start of "string",
  5897. * we know that "tring", "ring" etc will not match too:
  5898. */
  5899. if (pattern[0] == '*')
  5900. return NULL;
  5901. val++;
  5902. }
  5903. }
  5904. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5905. {
  5906. char *result = NULL;
  5907. unsigned res_len = 0;
  5908. unsigned repl_len = strlen(repl);
  5909. /* Null pattern never matches, including if "var" is empty */
  5910. if (!pattern[0])
  5911. return result; /* NULL, no replaces happened */
  5912. while (1) {
  5913. int size;
  5914. char *s = strstr_pattern(val, pattern, &size);
  5915. if (!s)
  5916. break;
  5917. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5918. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5919. res_len += (s - val) + repl_len;
  5920. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5921. val = s + size;
  5922. if (exp_op == '/')
  5923. break;
  5924. }
  5925. if (*val && result) {
  5926. result = xrealloc(result, res_len + strlen(val) + 1);
  5927. strcpy(result + res_len, val);
  5928. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5929. }
  5930. debug_printf_varexp("result:'%s'\n", result);
  5931. return result;
  5932. }
  5933. #endif /* BASH_PATTERN_SUBST */
  5934. static int append_str_maybe_ifs_split(o_string *output, int n,
  5935. int first_ch, const char *val)
  5936. {
  5937. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5938. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5939. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5940. if (val && val[0])
  5941. n = expand_on_ifs(output, n, val);
  5942. } else { /* quoted "$VAR" */
  5943. output->has_quoted_part = 1;
  5944. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5945. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5946. if (val && val[0])
  5947. o_addQstr(output, val);
  5948. }
  5949. return n;
  5950. }
  5951. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5952. */
  5953. static NOINLINE int expand_one_var(o_string *output, int n,
  5954. int first_ch, char *arg, char **pp)
  5955. {
  5956. const char *val;
  5957. char *to_be_freed;
  5958. char *p;
  5959. char *var;
  5960. char exp_op;
  5961. char exp_save = exp_save; /* for compiler */
  5962. char *exp_saveptr; /* points to expansion operator */
  5963. char *exp_word = exp_word; /* for compiler */
  5964. char arg0;
  5965. val = NULL;
  5966. to_be_freed = NULL;
  5967. p = *pp;
  5968. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5969. var = arg;
  5970. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5971. arg0 = arg[0];
  5972. arg[0] = (arg0 & 0x7f);
  5973. exp_op = 0;
  5974. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5975. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5976. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5977. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5978. ) {
  5979. /* It must be length operator: ${#var} */
  5980. var++;
  5981. exp_op = 'L';
  5982. } else {
  5983. /* Maybe handle parameter expansion */
  5984. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5985. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5986. ) {
  5987. /* ${?:0}, ${#[:]%0} etc */
  5988. exp_saveptr = var + 1;
  5989. } else {
  5990. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5991. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5992. }
  5993. exp_op = exp_save = *exp_saveptr;
  5994. if (exp_op) {
  5995. exp_word = exp_saveptr + 1;
  5996. if (exp_op == ':') {
  5997. exp_op = *exp_word++;
  5998. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5999. if (BASH_SUBSTR
  6000. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6001. ) {
  6002. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6003. exp_op = ':';
  6004. exp_word--;
  6005. }
  6006. }
  6007. *exp_saveptr = '\0';
  6008. } /* else: it's not an expansion op, but bare ${var} */
  6009. }
  6010. /* Look up the variable in question */
  6011. if (isdigit(var[0])) {
  6012. /* parse_dollar should have vetted var for us */
  6013. int nn = xatoi_positive(var);
  6014. if (nn < G.global_argc)
  6015. val = G.global_argv[nn];
  6016. /* else val remains NULL: $N with too big N */
  6017. } else {
  6018. switch (var[0]) {
  6019. case '$': /* pid */
  6020. val = utoa(G.root_pid);
  6021. break;
  6022. case '!': /* bg pid */
  6023. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6024. break;
  6025. case '?': /* exitcode */
  6026. val = utoa(G.last_exitcode);
  6027. break;
  6028. case '#': /* argc */
  6029. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6030. break;
  6031. case '-': { /* active options */
  6032. /* Check set_mode() to see what option chars we support */
  6033. char *cp;
  6034. val = cp = G.optstring_buf;
  6035. if (G.o_opt[OPT_O_ERREXIT])
  6036. *cp++ = 'e';
  6037. if (G_interactive_fd)
  6038. *cp++ = 'i';
  6039. if (G_x_mode)
  6040. *cp++ = 'x';
  6041. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6042. * commands read but are not executed,
  6043. * so $- can not execute too, 'n' is never seen in $-.
  6044. */
  6045. if (G.opt_c)
  6046. *cp++ = 'c';
  6047. if (G.opt_s)
  6048. *cp++ = 's';
  6049. *cp = '\0';
  6050. break;
  6051. }
  6052. default:
  6053. val = get_local_var_value(var);
  6054. }
  6055. }
  6056. /* Handle any expansions */
  6057. if (exp_op == 'L') {
  6058. reinit_unicode_for_hush();
  6059. debug_printf_expand("expand: length(%s)=", val);
  6060. val = utoa(val ? unicode_strlen(val) : 0);
  6061. debug_printf_expand("%s\n", val);
  6062. } else if (exp_op) {
  6063. if (exp_op == '%' || exp_op == '#') {
  6064. /* Standard-mandated substring removal ops:
  6065. * ${parameter%word} - remove smallest suffix pattern
  6066. * ${parameter%%word} - remove largest suffix pattern
  6067. * ${parameter#word} - remove smallest prefix pattern
  6068. * ${parameter##word} - remove largest prefix pattern
  6069. *
  6070. * Word is expanded to produce a glob pattern.
  6071. * Then var's value is matched to it and matching part removed.
  6072. */
  6073. //FIXME: ${x#...${...}...}
  6074. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6075. //inner ${...} may have side effects!
  6076. if (val && val[0]) {
  6077. char *t;
  6078. char *exp_exp_word;
  6079. char *loc;
  6080. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6081. if (exp_op == *exp_word) /* ## or %% */
  6082. exp_word++;
  6083. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6084. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6085. if (exp_exp_word)
  6086. exp_word = exp_exp_word;
  6087. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6088. /*
  6089. * HACK ALERT. We depend here on the fact that
  6090. * G.global_argv and results of utoa and get_local_var_value
  6091. * are actually in writable memory:
  6092. * scan_and_match momentarily stores NULs there.
  6093. */
  6094. t = (char*)val;
  6095. loc = scan_and_match(t, exp_word, scan_flags);
  6096. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6097. free(exp_exp_word);
  6098. if (loc) { /* match was found */
  6099. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6100. val = loc; /* take right part */
  6101. else /* %[%] */
  6102. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6103. }
  6104. }
  6105. }
  6106. #if BASH_PATTERN_SUBST
  6107. else if (exp_op == '/' || exp_op == '\\') {
  6108. /* It's ${var/[/]pattern[/repl]} thing.
  6109. * Note that in encoded form it has TWO parts:
  6110. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6111. * and if // is used, it is encoded as \:
  6112. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6113. */
  6114. if (val && val[0]) {
  6115. /* pattern uses non-standard expansion.
  6116. * repl should be unbackslashed and globbed
  6117. * by the usual expansion rules:
  6118. * >az >bz
  6119. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6120. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6121. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6122. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6123. * (note that a*z _pattern_ is never globbed!)
  6124. */
  6125. char *pattern, *repl, *t;
  6126. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6127. if (!pattern)
  6128. pattern = xstrdup(exp_word);
  6129. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6130. *p++ = SPECIAL_VAR_SYMBOL;
  6131. exp_word = p;
  6132. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6133. *p = '\0';
  6134. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6135. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6136. /* HACK ALERT. We depend here on the fact that
  6137. * G.global_argv and results of utoa and get_local_var_value
  6138. * are actually in writable memory:
  6139. * replace_pattern momentarily stores NULs there. */
  6140. t = (char*)val;
  6141. to_be_freed = replace_pattern(t,
  6142. pattern,
  6143. (repl ? repl : exp_word),
  6144. exp_op);
  6145. if (to_be_freed) /* at least one replace happened */
  6146. val = to_be_freed;
  6147. free(pattern);
  6148. free(repl);
  6149. } else {
  6150. /* Empty variable always gives nothing */
  6151. // "v=''; echo ${v/*/w}" prints "", not "w"
  6152. /* Just skip "replace" part */
  6153. *p++ = SPECIAL_VAR_SYMBOL;
  6154. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6155. *p = '\0';
  6156. }
  6157. }
  6158. #endif /* BASH_PATTERN_SUBST */
  6159. else if (exp_op == ':') {
  6160. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6161. /* It's ${var:N[:M]} bashism.
  6162. * Note that in encoded form it has TWO parts:
  6163. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6164. */
  6165. arith_t beg, len;
  6166. const char *errmsg;
  6167. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6168. if (errmsg)
  6169. goto arith_err;
  6170. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6171. *p++ = SPECIAL_VAR_SYMBOL;
  6172. exp_word = p;
  6173. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6174. *p = '\0';
  6175. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6176. if (errmsg)
  6177. goto arith_err;
  6178. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6179. if (beg < 0) {
  6180. /* negative beg counts from the end */
  6181. beg = (arith_t)strlen(val) + beg;
  6182. if (beg < 0) /* ${v: -999999} is "" */
  6183. beg = len = 0;
  6184. }
  6185. debug_printf_varexp("from val:'%s'\n", val);
  6186. if (len < 0) {
  6187. /* in bash, len=-n means strlen()-n */
  6188. len = (arith_t)strlen(val) - beg + len;
  6189. if (len < 0) /* bash compat */
  6190. msg_and_die_if_script("%s: substring expression < 0", var);
  6191. }
  6192. if (len <= 0 || !val || beg >= strlen(val)) {
  6193. arith_err:
  6194. val = NULL;
  6195. } else {
  6196. /* Paranoia. What if user entered 9999999999999
  6197. * which fits in arith_t but not int? */
  6198. if (len >= INT_MAX)
  6199. len = INT_MAX;
  6200. val = to_be_freed = xstrndup(val + beg, len);
  6201. }
  6202. debug_printf_varexp("val:'%s'\n", val);
  6203. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6204. msg_and_die_if_script("malformed ${%s:...}", var);
  6205. val = NULL;
  6206. #endif
  6207. } else { /* one of "-=+?" */
  6208. /* Standard-mandated substitution ops:
  6209. * ${var?word} - indicate error if unset
  6210. * If var is unset, word (or a message indicating it is unset
  6211. * if word is null) is written to standard error
  6212. * and the shell exits with a non-zero exit status.
  6213. * Otherwise, the value of var is substituted.
  6214. * ${var-word} - use default value
  6215. * If var is unset, word is substituted.
  6216. * ${var=word} - assign and use default value
  6217. * If var is unset, word is assigned to var.
  6218. * In all cases, final value of var is substituted.
  6219. * ${var+word} - use alternative value
  6220. * If var is unset, null is substituted.
  6221. * Otherwise, word is substituted.
  6222. *
  6223. * Word is subjected to tilde expansion, parameter expansion,
  6224. * command substitution, and arithmetic expansion.
  6225. * If word is not needed, it is not expanded.
  6226. *
  6227. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6228. * but also treat null var as if it is unset.
  6229. *
  6230. * Word-splitting and single quote behavior:
  6231. *
  6232. * $ f() { for i; do echo "|$i|"; done; };
  6233. *
  6234. * $ x=; f ${x:?'x y' z}
  6235. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6236. * $ x=; f "${x:?'x y' z}"
  6237. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6238. *
  6239. * $ x=; f ${x:='x y' z}
  6240. * |x|
  6241. * |y|
  6242. * |z|
  6243. * $ x=; f "${x:='x y' z}"
  6244. * |'x y' z|
  6245. *
  6246. * $ x=x; f ${x:+'x y' z}
  6247. * |x y|
  6248. * |z|
  6249. * $ x=x; f "${x:+'x y' z}"
  6250. * |'x y' z|
  6251. *
  6252. * $ x=; f ${x:-'x y' z}
  6253. * |x y|
  6254. * |z|
  6255. * $ x=; f "${x:-'x y' z}"
  6256. * |'x y' z|
  6257. */
  6258. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6259. if (exp_op == '+')
  6260. use_word = !use_word;
  6261. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6262. (exp_save == ':') ? "true" : "false", use_word);
  6263. if (use_word) {
  6264. if (exp_op == '+' || exp_op == '-') {
  6265. /* ${var+word} - use alternative value */
  6266. /* ${var-word} - use default value */
  6267. n = encode_then_append_var_plusminus(output, n, exp_word,
  6268. /*dquoted:*/ (arg0 & 0x80)
  6269. );
  6270. val = NULL;
  6271. } else {
  6272. /* ${var?word} - indicate error if unset */
  6273. /* ${var=word} - assign and use default value */
  6274. to_be_freed = encode_then_expand_vararg(exp_word,
  6275. /*handle_squotes:*/ !(arg0 & 0x80),
  6276. /*unbackslash:*/ 0
  6277. );
  6278. if (to_be_freed)
  6279. exp_word = to_be_freed;
  6280. if (exp_op == '?') {
  6281. /* mimic bash message */
  6282. msg_and_die_if_script("%s: %s",
  6283. var,
  6284. exp_word[0]
  6285. ? exp_word
  6286. : "parameter null or not set"
  6287. /* ash has more specific messages, a-la: */
  6288. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6289. );
  6290. //TODO: how interactive bash aborts expansion mid-command?
  6291. //It aborts the entire line, returns to prompt:
  6292. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6293. // bash: x: x y z
  6294. // $
  6295. // ("echo YO" is not executed, neither the f function call)
  6296. } else {
  6297. val = exp_word;
  6298. }
  6299. if (exp_op == '=') {
  6300. /* ${var=[word]} or ${var:=[word]} */
  6301. if (isdigit(var[0]) || var[0] == '#') {
  6302. /* mimic bash message */
  6303. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6304. val = NULL;
  6305. } else {
  6306. char *new_var = xasprintf("%s=%s", var, val);
  6307. set_local_var(new_var, /*flag:*/ 0);
  6308. }
  6309. }
  6310. }
  6311. }
  6312. } /* one of "-=+?" */
  6313. *exp_saveptr = exp_save;
  6314. } /* if (exp_op) */
  6315. arg[0] = arg0;
  6316. *pp = p;
  6317. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6318. free(to_be_freed);
  6319. return n;
  6320. }
  6321. /* Expand all variable references in given string, adding words to list[]
  6322. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6323. * to be filled). This routine is extremely tricky: has to deal with
  6324. * variables/parameters with whitespace, $* and $@, and constructs like
  6325. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6326. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6327. {
  6328. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6329. * expansion of right-hand side of assignment == 1-element expand.
  6330. */
  6331. char cant_be_null = 0; /* only bit 0x80 matters */
  6332. char *p;
  6333. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6334. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6335. debug_print_list("expand_vars_to_list[0]", output, n);
  6336. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6337. char first_ch;
  6338. #if ENABLE_FEATURE_SH_MATH
  6339. char arith_buf[sizeof(arith_t)*3 + 2];
  6340. #endif
  6341. if (output->ended_in_ifs) {
  6342. o_addchr(output, '\0');
  6343. n = o_save_ptr(output, n);
  6344. output->ended_in_ifs = 0;
  6345. }
  6346. o_addblock(output, arg, p - arg);
  6347. debug_print_list("expand_vars_to_list[1]", output, n);
  6348. arg = ++p;
  6349. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6350. /* Fetch special var name (if it is indeed one of them)
  6351. * and quote bit, force the bit on if singleword expansion -
  6352. * important for not getting v=$@ expand to many words. */
  6353. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6354. /* Is this variable quoted and thus expansion can't be null?
  6355. * "$@" is special. Even if quoted, it can still
  6356. * expand to nothing (not even an empty string),
  6357. * thus it is excluded. */
  6358. if ((first_ch & 0x7f) != '@')
  6359. cant_be_null |= first_ch;
  6360. switch (first_ch & 0x7f) {
  6361. /* Highest bit in first_ch indicates that var is double-quoted */
  6362. case '*':
  6363. case '@': {
  6364. int i;
  6365. if (!G.global_argv[1])
  6366. break;
  6367. i = 1;
  6368. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6369. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6370. while (G.global_argv[i]) {
  6371. n = expand_on_ifs(output, n, G.global_argv[i]);
  6372. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6373. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6374. /* this argv[] is not empty and not last:
  6375. * put terminating NUL, start new word */
  6376. o_addchr(output, '\0');
  6377. debug_print_list("expand_vars_to_list[2]", output, n);
  6378. n = o_save_ptr(output, n);
  6379. debug_print_list("expand_vars_to_list[3]", output, n);
  6380. }
  6381. }
  6382. } else
  6383. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6384. * and in this case should treat it like '$*' - see 'else...' below */
  6385. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6386. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6387. ) {
  6388. while (1) {
  6389. o_addQstr(output, G.global_argv[i]);
  6390. if (++i >= G.global_argc)
  6391. break;
  6392. o_addchr(output, '\0');
  6393. debug_print_list("expand_vars_to_list[4]", output, n);
  6394. n = o_save_ptr(output, n);
  6395. }
  6396. } else { /* quoted $* (or v="$@" case): add as one word */
  6397. while (1) {
  6398. o_addQstr(output, G.global_argv[i]);
  6399. if (!G.global_argv[++i])
  6400. break;
  6401. if (G.ifs[0])
  6402. o_addchr(output, G.ifs[0]);
  6403. }
  6404. output->has_quoted_part = 1;
  6405. }
  6406. break;
  6407. }
  6408. case SPECIAL_VAR_SYMBOL: {
  6409. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6410. /* "Empty variable", used to make "" etc to not disappear */
  6411. output->has_quoted_part = 1;
  6412. cant_be_null = 0x80;
  6413. arg++;
  6414. break;
  6415. }
  6416. case SPECIAL_VAR_QUOTED_SVS:
  6417. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6418. /* "^C variable", represents literal ^C char (possible in scripts) */
  6419. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6420. arg++;
  6421. break;
  6422. #if ENABLE_HUSH_TICK
  6423. case '`': {
  6424. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6425. o_string subst_result = NULL_O_STRING;
  6426. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6427. arg++;
  6428. /* Can't just stuff it into output o_string,
  6429. * expanded result may need to be globbed
  6430. * and $IFS-split */
  6431. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6432. G.last_exitcode = process_command_subs(&subst_result, arg);
  6433. G.expand_exitcode = G.last_exitcode;
  6434. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6435. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6436. o_free(&subst_result);
  6437. break;
  6438. }
  6439. #endif
  6440. #if ENABLE_FEATURE_SH_MATH
  6441. case '+': {
  6442. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6443. arith_t res;
  6444. arg++; /* skip '+' */
  6445. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6446. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6447. res = expand_and_evaluate_arith(arg, NULL);
  6448. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6449. sprintf(arith_buf, ARITH_FMT, res);
  6450. if (res < 0
  6451. && first_ch == (char)('+'|0x80)
  6452. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6453. ) {
  6454. /* Quoted negative ariths, like filename[0"$((-9))"],
  6455. * should not be interpreted as glob ranges.
  6456. * Convert leading '-' to '\-':
  6457. */
  6458. o_grow_by(output, 1);
  6459. output->data[output->length++] = '\\';
  6460. }
  6461. o_addstr(output, arith_buf);
  6462. break;
  6463. }
  6464. #endif
  6465. default:
  6466. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6467. n = expand_one_var(output, n, first_ch, arg, &p);
  6468. break;
  6469. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6470. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6471. * Do the check to avoid writing to a const string. */
  6472. if (*p != SPECIAL_VAR_SYMBOL)
  6473. *p = SPECIAL_VAR_SYMBOL;
  6474. arg = ++p;
  6475. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6476. if (*arg) {
  6477. /* handle trailing string */
  6478. if (output->ended_in_ifs) {
  6479. o_addchr(output, '\0');
  6480. n = o_save_ptr(output, n);
  6481. }
  6482. debug_print_list("expand_vars_to_list[a]", output, n);
  6483. /* this part is literal, and it was already pre-quoted
  6484. * if needed (much earlier), do not use o_addQstr here!
  6485. */
  6486. o_addstr(output, arg);
  6487. debug_print_list("expand_vars_to_list[b]", output, n);
  6488. } else
  6489. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6490. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6491. && !output->has_quoted_part
  6492. ) {
  6493. n--;
  6494. /* allow to reuse list[n] later without re-growth */
  6495. output->has_empty_slot = 1;
  6496. }
  6497. return n;
  6498. }
  6499. static char **expand_variables(char **argv, unsigned expflags)
  6500. {
  6501. int n;
  6502. char **list;
  6503. o_string output = NULL_O_STRING;
  6504. output.o_expflags = expflags;
  6505. n = 0;
  6506. for (;;) {
  6507. /* go to next list[n] */
  6508. output.ended_in_ifs = 0;
  6509. n = o_save_ptr(&output, n);
  6510. if (!*argv)
  6511. break;
  6512. /* expand argv[i] */
  6513. n = expand_vars_to_list(&output, n, *argv++);
  6514. /* if (!output->has_empty_slot) -- need this?? */
  6515. o_addchr(&output, '\0');
  6516. }
  6517. debug_print_list("expand_variables", &output, n);
  6518. /* output.data (malloced in one block) gets returned in "list" */
  6519. list = o_finalize_list(&output, n);
  6520. debug_print_strings("expand_variables[1]", list);
  6521. return list;
  6522. }
  6523. static char **expand_strvec_to_strvec(char **argv)
  6524. {
  6525. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6526. }
  6527. #if defined(CMD_SINGLEWORD_NOGLOB)
  6528. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6529. {
  6530. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6531. }
  6532. #endif
  6533. /* Used for expansion of right hand of assignments,
  6534. * $((...)), heredocs, variable expansion parts.
  6535. *
  6536. * NB: should NOT do globbing!
  6537. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6538. */
  6539. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6540. {
  6541. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6542. const int do_unbackslash = 1;
  6543. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6544. #endif
  6545. char *argv[2], **list;
  6546. debug_printf_expand("string_to_string<='%s'\n", str);
  6547. /* This is generally an optimization, but it also
  6548. * handles "", which otherwise trips over !list[0] check below.
  6549. * (is this ever happens that we actually get str="" here?)
  6550. */
  6551. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6552. //TODO: Can use on strings with \ too, just unbackslash() them?
  6553. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6554. return xstrdup(str);
  6555. }
  6556. argv[0] = (char*)str;
  6557. argv[1] = NULL;
  6558. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6559. if (!list[0]) {
  6560. /* Example where it happens:
  6561. * x=; echo ${x:-"$@"}
  6562. */
  6563. ((char*)list)[0] = '\0';
  6564. } else {
  6565. if (HUSH_DEBUG)
  6566. if (list[1])
  6567. bb_simple_error_msg_and_die("BUG in varexp2");
  6568. /* actually, just move string 2*sizeof(char*) bytes back */
  6569. overlapping_strcpy((char*)list, list[0]);
  6570. if (do_unbackslash)
  6571. unbackslash((char*)list);
  6572. }
  6573. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6574. return (char*)list;
  6575. }
  6576. #if 0
  6577. static char* expand_strvec_to_string(char **argv)
  6578. {
  6579. char **list;
  6580. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6581. /* Convert all NULs to spaces */
  6582. if (list[0]) {
  6583. int n = 1;
  6584. while (list[n]) {
  6585. if (HUSH_DEBUG)
  6586. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6587. bb_error_msg_and_die("BUG in varexp3");
  6588. /* bash uses ' ' regardless of $IFS contents */
  6589. list[n][-1] = ' ';
  6590. n++;
  6591. }
  6592. }
  6593. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6594. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6595. return (char*)list;
  6596. }
  6597. #endif
  6598. static char **expand_assignments(char **argv, int count)
  6599. {
  6600. int i;
  6601. char **p;
  6602. G.expanded_assignments = p = NULL;
  6603. /* Expand assignments into one string each */
  6604. for (i = 0; i < count; i++) {
  6605. p = add_string_to_strings(p,
  6606. expand_string_to_string(argv[i],
  6607. EXP_FLAG_ESC_GLOB_CHARS,
  6608. /*unbackslash:*/ 1
  6609. )
  6610. );
  6611. G.expanded_assignments = p;
  6612. }
  6613. G.expanded_assignments = NULL;
  6614. return p;
  6615. }
  6616. static void switch_off_special_sigs(unsigned mask)
  6617. {
  6618. unsigned sig = 0;
  6619. while ((mask >>= 1) != 0) {
  6620. sig++;
  6621. if (!(mask & 1))
  6622. continue;
  6623. #if ENABLE_HUSH_TRAP
  6624. if (G_traps) {
  6625. if (G_traps[sig] && !G_traps[sig][0])
  6626. /* trap is '', has to remain SIG_IGN */
  6627. continue;
  6628. free(G_traps[sig]);
  6629. G_traps[sig] = NULL;
  6630. }
  6631. #endif
  6632. /* We are here only if no trap or trap was not '' */
  6633. install_sighandler(sig, SIG_DFL);
  6634. }
  6635. }
  6636. #if BB_MMU
  6637. /* never called */
  6638. void re_execute_shell(char ***to_free, const char *s,
  6639. char *g_argv0, char **g_argv,
  6640. char **builtin_argv) NORETURN;
  6641. static void reset_traps_to_defaults(void)
  6642. {
  6643. /* This function is always called in a child shell
  6644. * after fork (not vfork, NOMMU doesn't use this function).
  6645. */
  6646. IF_HUSH_TRAP(unsigned sig;)
  6647. unsigned mask;
  6648. /* Child shells are not interactive.
  6649. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6650. * Testcase: (while :; do :; done) + ^Z should background.
  6651. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6652. */
  6653. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6654. if (!G_traps && !mask)
  6655. return; /* already no traps and no special sigs */
  6656. /* Switch off special sigs */
  6657. switch_off_special_sigs(mask);
  6658. # if ENABLE_HUSH_JOB
  6659. G_fatal_sig_mask = 0;
  6660. # endif
  6661. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6662. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6663. * remain set in G.special_sig_mask */
  6664. # if ENABLE_HUSH_TRAP
  6665. if (!G_traps)
  6666. return;
  6667. /* Reset all sigs to default except ones with empty traps */
  6668. for (sig = 0; sig < NSIG; sig++) {
  6669. if (!G_traps[sig])
  6670. continue; /* no trap: nothing to do */
  6671. if (!G_traps[sig][0])
  6672. continue; /* empty trap: has to remain SIG_IGN */
  6673. /* sig has non-empty trap, reset it: */
  6674. free(G_traps[sig]);
  6675. G_traps[sig] = NULL;
  6676. /* There is no signal for trap 0 (EXIT) */
  6677. if (sig == 0)
  6678. continue;
  6679. install_sighandler(sig, pick_sighandler(sig));
  6680. }
  6681. # endif
  6682. }
  6683. #else /* !BB_MMU */
  6684. static void re_execute_shell(char ***to_free, const char *s,
  6685. char *g_argv0, char **g_argv,
  6686. char **builtin_argv) NORETURN;
  6687. static void re_execute_shell(char ***to_free, const char *s,
  6688. char *g_argv0, char **g_argv,
  6689. char **builtin_argv)
  6690. {
  6691. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6692. /* delims + 2 * (number of bytes in printed hex numbers) */
  6693. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6694. char *heredoc_argv[4];
  6695. struct variable *cur;
  6696. # if ENABLE_HUSH_FUNCTIONS
  6697. struct function *funcp;
  6698. # endif
  6699. char **argv, **pp;
  6700. unsigned cnt;
  6701. unsigned long long empty_trap_mask;
  6702. if (!g_argv0) { /* heredoc */
  6703. argv = heredoc_argv;
  6704. argv[0] = (char *) G.argv0_for_re_execing;
  6705. argv[1] = (char *) "-<";
  6706. argv[2] = (char *) s;
  6707. argv[3] = NULL;
  6708. pp = &argv[3]; /* used as pointer to empty environment */
  6709. goto do_exec;
  6710. }
  6711. cnt = 0;
  6712. pp = builtin_argv;
  6713. if (pp) while (*pp++)
  6714. cnt++;
  6715. empty_trap_mask = 0;
  6716. if (G_traps) {
  6717. int sig;
  6718. for (sig = 1; sig < NSIG; sig++) {
  6719. if (G_traps[sig] && !G_traps[sig][0])
  6720. empty_trap_mask |= 1LL << sig;
  6721. }
  6722. }
  6723. sprintf(param_buf, NOMMU_HACK_FMT
  6724. , (unsigned) G.root_pid
  6725. , (unsigned) G.root_ppid
  6726. , (unsigned) G.last_bg_pid
  6727. , (unsigned) G.last_exitcode
  6728. , cnt
  6729. , empty_trap_mask
  6730. IF_HUSH_LOOPS(, G.depth_of_loop)
  6731. );
  6732. # undef NOMMU_HACK_FMT
  6733. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6734. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6735. */
  6736. cnt += 6;
  6737. for (cur = G.top_var; cur; cur = cur->next) {
  6738. if (!cur->flg_export || cur->flg_read_only)
  6739. cnt += 2;
  6740. }
  6741. # if ENABLE_HUSH_FUNCTIONS
  6742. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6743. cnt += 3;
  6744. # endif
  6745. pp = g_argv;
  6746. while (*pp++)
  6747. cnt++;
  6748. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6749. *pp++ = (char *) G.argv0_for_re_execing;
  6750. *pp++ = param_buf;
  6751. for (cur = G.top_var; cur; cur = cur->next) {
  6752. if (strcmp(cur->varstr, hush_version_str) == 0)
  6753. continue;
  6754. if (cur->flg_read_only) {
  6755. *pp++ = (char *) "-R";
  6756. *pp++ = cur->varstr;
  6757. } else if (!cur->flg_export) {
  6758. *pp++ = (char *) "-V";
  6759. *pp++ = cur->varstr;
  6760. }
  6761. }
  6762. # if ENABLE_HUSH_FUNCTIONS
  6763. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6764. *pp++ = (char *) "-F";
  6765. *pp++ = funcp->name;
  6766. *pp++ = funcp->body_as_string;
  6767. }
  6768. # endif
  6769. /* We can pass activated traps here. Say, -Tnn:trap_string
  6770. *
  6771. * However, POSIX says that subshells reset signals with traps
  6772. * to SIG_DFL.
  6773. * I tested bash-3.2 and it not only does that with true subshells
  6774. * of the form ( list ), but with any forked children shells.
  6775. * I set trap "echo W" WINCH; and then tried:
  6776. *
  6777. * { echo 1; sleep 20; echo 2; } &
  6778. * while true; do echo 1; sleep 20; echo 2; break; done &
  6779. * true | { echo 1; sleep 20; echo 2; } | cat
  6780. *
  6781. * In all these cases sending SIGWINCH to the child shell
  6782. * did not run the trap. If I add trap "echo V" WINCH;
  6783. * _inside_ group (just before echo 1), it works.
  6784. *
  6785. * I conclude it means we don't need to pass active traps here.
  6786. */
  6787. *pp++ = (char *) "-c";
  6788. *pp++ = (char *) s;
  6789. if (builtin_argv) {
  6790. while (*++builtin_argv)
  6791. *pp++ = *builtin_argv;
  6792. *pp++ = (char *) "";
  6793. }
  6794. *pp++ = g_argv0;
  6795. while (*g_argv)
  6796. *pp++ = *g_argv++;
  6797. /* *pp = NULL; - is already there */
  6798. pp = environ;
  6799. do_exec:
  6800. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6801. /* Don't propagate SIG_IGN to the child */
  6802. if (SPECIAL_JOBSTOP_SIGS != 0)
  6803. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6804. execve(bb_busybox_exec_path, argv, pp);
  6805. /* Fallback. Useful for init=/bin/hush usage etc */
  6806. if (argv[0][0] == '/')
  6807. execve(argv[0], argv, pp);
  6808. xfunc_error_retval = 127;
  6809. bb_simple_error_msg_and_die("can't re-execute the shell");
  6810. }
  6811. #endif /* !BB_MMU */
  6812. static int run_and_free_list(struct pipe *pi);
  6813. /* Executing from string: eval, sh -c '...'
  6814. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6815. * end_trigger controls how often we stop parsing
  6816. * NUL: parse all, execute, return
  6817. * ';': parse till ';' or newline, execute, repeat till EOF
  6818. */
  6819. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6820. {
  6821. /* Why we need empty flag?
  6822. * An obscure corner case "false; ``; echo $?":
  6823. * empty command in `` should still set $? to 0.
  6824. * But we can't just set $? to 0 at the start,
  6825. * this breaks "false; echo `echo $?`" case.
  6826. */
  6827. bool empty = 1;
  6828. while (1) {
  6829. struct pipe *pipe_list;
  6830. #if ENABLE_HUSH_INTERACTIVE
  6831. if (end_trigger == ';') {
  6832. G.promptmode = 0; /* PS1 */
  6833. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6834. }
  6835. #endif
  6836. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6837. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6838. /* If we are in "big" script
  6839. * (not in `cmd` or something similar)...
  6840. */
  6841. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6842. /* Discard cached input (rest of line) */
  6843. int ch = inp->last_char;
  6844. while (ch != EOF && ch != '\n') {
  6845. //bb_error_msg("Discarded:'%c'", ch);
  6846. ch = i_getch(inp);
  6847. }
  6848. /* Force prompt */
  6849. inp->p = NULL;
  6850. /* This stream isn't empty */
  6851. empty = 0;
  6852. continue;
  6853. }
  6854. if (!pipe_list && empty)
  6855. G.last_exitcode = 0;
  6856. break;
  6857. }
  6858. debug_print_tree(pipe_list, 0);
  6859. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6860. run_and_free_list(pipe_list);
  6861. empty = 0;
  6862. if (G_flag_return_in_progress == 1)
  6863. break;
  6864. }
  6865. }
  6866. static void parse_and_run_string(const char *s)
  6867. {
  6868. struct in_str input;
  6869. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6870. setup_string_in_str(&input, s);
  6871. parse_and_run_stream(&input, '\0');
  6872. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6873. }
  6874. static void parse_and_run_file(HFILE *fp)
  6875. {
  6876. struct in_str input;
  6877. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6878. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6879. setup_file_in_str(&input, fp);
  6880. parse_and_run_stream(&input, ';');
  6881. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6882. }
  6883. #if ENABLE_HUSH_TICK
  6884. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6885. {
  6886. pid_t pid;
  6887. int channel[2];
  6888. # if !BB_MMU
  6889. char **to_free = NULL;
  6890. # endif
  6891. xpipe(channel);
  6892. pid = BB_MMU ? xfork() : xvfork();
  6893. if (pid == 0) { /* child */
  6894. disable_restore_tty_pgrp_on_exit();
  6895. /* Process substitution is not considered to be usual
  6896. * 'command execution'.
  6897. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6898. */
  6899. bb_signals(0
  6900. + (1 << SIGTSTP)
  6901. + (1 << SIGTTIN)
  6902. + (1 << SIGTTOU)
  6903. , SIG_IGN);
  6904. close(channel[0]); /* NB: close _first_, then move fd! */
  6905. xmove_fd(channel[1], 1);
  6906. # if ENABLE_HUSH_TRAP
  6907. /* Awful hack for `trap` or $(trap).
  6908. *
  6909. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6910. * contains an example where "trap" is executed in a subshell:
  6911. *
  6912. * save_traps=$(trap)
  6913. * ...
  6914. * eval "$save_traps"
  6915. *
  6916. * Standard does not say that "trap" in subshell shall print
  6917. * parent shell's traps. It only says that its output
  6918. * must have suitable form, but then, in the above example
  6919. * (which is not supposed to be normative), it implies that.
  6920. *
  6921. * bash (and probably other shell) does implement it
  6922. * (traps are reset to defaults, but "trap" still shows them),
  6923. * but as a result, "trap" logic is hopelessly messed up:
  6924. *
  6925. * # trap
  6926. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6927. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6928. * # true | trap <--- trap is in subshell - no output (ditto)
  6929. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6930. * trap -- 'echo Ho' SIGWINCH
  6931. * # echo `(trap)` <--- in subshell in subshell - output
  6932. * trap -- 'echo Ho' SIGWINCH
  6933. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6934. * trap -- 'echo Ho' SIGWINCH
  6935. *
  6936. * The rules when to forget and when to not forget traps
  6937. * get really complex and nonsensical.
  6938. *
  6939. * Our solution: ONLY bare $(trap) or `trap` is special.
  6940. */
  6941. s = skip_whitespace(s);
  6942. if (is_prefixed_with(s, "trap")
  6943. && skip_whitespace(s + 4)[0] == '\0'
  6944. ) {
  6945. static const char *const argv[] = { NULL, NULL };
  6946. builtin_trap((char**)argv);
  6947. fflush_all(); /* important */
  6948. _exit(0);
  6949. }
  6950. # endif
  6951. # if BB_MMU
  6952. /* Prevent it from trying to handle ctrl-z etc */
  6953. IF_HUSH_JOB(G.run_list_level = 1;)
  6954. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6955. reset_traps_to_defaults();
  6956. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6957. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6958. parse_and_run_string(s);
  6959. _exit(G.last_exitcode);
  6960. # else
  6961. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6962. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6963. * huge=`cat BIG` # was blocking here forever
  6964. * echo OK
  6965. */
  6966. re_execute_shell(&to_free,
  6967. s,
  6968. G.global_argv[0],
  6969. G.global_argv + 1,
  6970. NULL);
  6971. # endif
  6972. }
  6973. /* parent */
  6974. *pid_p = pid;
  6975. # if ENABLE_HUSH_FAST
  6976. G.count_SIGCHLD++;
  6977. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6978. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6979. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6980. # endif
  6981. enable_restore_tty_pgrp_on_exit();
  6982. # if !BB_MMU
  6983. free(to_free);
  6984. # endif
  6985. close(channel[1]);
  6986. return channel[0];
  6987. }
  6988. /* Return code is exit status of the process that is run. */
  6989. static int process_command_subs(o_string *dest, const char *s)
  6990. {
  6991. FILE *fp;
  6992. pid_t pid;
  6993. int status, ch, eol_cnt;
  6994. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6995. /* Now send results of command back into original context */
  6996. eol_cnt = 0;
  6997. while ((ch = getc(fp)) != EOF) {
  6998. if (ch == '\0')
  6999. continue;
  7000. if (ch == '\n') {
  7001. eol_cnt++;
  7002. continue;
  7003. }
  7004. while (eol_cnt) {
  7005. o_addchr(dest, '\n');
  7006. eol_cnt--;
  7007. }
  7008. o_addQchr(dest, ch);
  7009. }
  7010. debug_printf("done reading from `cmd` pipe, closing it\n");
  7011. fclose(fp);
  7012. /* We need to extract exitcode. Test case
  7013. * "true; echo `sleep 1; false` $?"
  7014. * should print 1 */
  7015. safe_waitpid(pid, &status, 0);
  7016. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7017. return WEXITSTATUS(status);
  7018. }
  7019. #endif /* ENABLE_HUSH_TICK */
  7020. static void setup_heredoc(struct redir_struct *redir)
  7021. {
  7022. struct fd_pair pair;
  7023. pid_t pid;
  7024. int len, written;
  7025. /* the _body_ of heredoc (misleading field name) */
  7026. const char *heredoc = redir->rd_filename;
  7027. char *expanded;
  7028. #if !BB_MMU
  7029. char **to_free;
  7030. #endif
  7031. expanded = NULL;
  7032. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7033. expanded = encode_then_expand_string(heredoc);
  7034. if (expanded)
  7035. heredoc = expanded;
  7036. }
  7037. len = strlen(heredoc);
  7038. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7039. xpiped_pair(pair);
  7040. xmove_fd(pair.rd, redir->rd_fd);
  7041. /* Try writing without forking. Newer kernels have
  7042. * dynamically growing pipes. Must use non-blocking write! */
  7043. ndelay_on(pair.wr);
  7044. while (1) {
  7045. written = write(pair.wr, heredoc, len);
  7046. if (written <= 0)
  7047. break;
  7048. len -= written;
  7049. if (len == 0) {
  7050. close(pair.wr);
  7051. free(expanded);
  7052. return;
  7053. }
  7054. heredoc += written;
  7055. }
  7056. ndelay_off(pair.wr);
  7057. /* Okay, pipe buffer was not big enough */
  7058. /* Note: we must not create a stray child (bastard? :)
  7059. * for the unsuspecting parent process. Child creates a grandchild
  7060. * and exits before parent execs the process which consumes heredoc
  7061. * (that exec happens after we return from this function) */
  7062. #if !BB_MMU
  7063. to_free = NULL;
  7064. #endif
  7065. pid = xvfork();
  7066. if (pid == 0) {
  7067. /* child */
  7068. disable_restore_tty_pgrp_on_exit();
  7069. pid = BB_MMU ? xfork() : xvfork();
  7070. if (pid != 0)
  7071. _exit(0);
  7072. /* grandchild */
  7073. close(redir->rd_fd); /* read side of the pipe */
  7074. #if BB_MMU
  7075. full_write(pair.wr, heredoc, len); /* may loop or block */
  7076. _exit(0);
  7077. #else
  7078. /* Delegate blocking writes to another process */
  7079. xmove_fd(pair.wr, STDOUT_FILENO);
  7080. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7081. #endif
  7082. }
  7083. /* parent */
  7084. #if ENABLE_HUSH_FAST
  7085. G.count_SIGCHLD++;
  7086. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7087. #endif
  7088. enable_restore_tty_pgrp_on_exit();
  7089. #if !BB_MMU
  7090. free(to_free);
  7091. #endif
  7092. close(pair.wr);
  7093. free(expanded);
  7094. wait(NULL); /* wait till child has died */
  7095. }
  7096. struct squirrel {
  7097. int orig_fd;
  7098. int moved_to;
  7099. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7100. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7101. };
  7102. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7103. {
  7104. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7105. sq[i].orig_fd = orig;
  7106. sq[i].moved_to = moved;
  7107. sq[i+1].orig_fd = -1; /* end marker */
  7108. return sq;
  7109. }
  7110. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7111. {
  7112. int moved_to;
  7113. int i;
  7114. i = 0;
  7115. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7116. /* If we collide with an already moved fd... */
  7117. if (fd == sq[i].moved_to) {
  7118. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7119. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7120. if (sq[i].moved_to < 0) /* what? */
  7121. xfunc_die();
  7122. return sq;
  7123. }
  7124. if (fd == sq[i].orig_fd) {
  7125. /* Example: echo Hello >/dev/null 1>&2 */
  7126. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7127. return sq;
  7128. }
  7129. }
  7130. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7131. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7132. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7133. if (moved_to < 0 && errno != EBADF)
  7134. xfunc_die();
  7135. return append_squirrel(sq, i, fd, moved_to);
  7136. }
  7137. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7138. {
  7139. int i;
  7140. i = 0;
  7141. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7142. /* If we collide with an already moved fd... */
  7143. if (fd == sq[i].orig_fd) {
  7144. /* Examples:
  7145. * "echo 3>FILE 3>&- 3>FILE"
  7146. * "echo 3>&- 3>FILE"
  7147. * No need for last redirect to insert
  7148. * another "need to close 3" indicator.
  7149. */
  7150. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7151. return sq;
  7152. }
  7153. }
  7154. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7155. return append_squirrel(sq, i, fd, -1);
  7156. }
  7157. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7158. * Move all conflicting internally used fds,
  7159. * and remember them so that we can restore them later.
  7160. */
  7161. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7162. {
  7163. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7164. avoid_fd = 9;
  7165. #if ENABLE_HUSH_INTERACTIVE
  7166. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7167. && fd == G_interactive_fd
  7168. ) {
  7169. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7170. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7171. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7172. return 1; /* "we closed fd" */
  7173. }
  7174. #endif
  7175. /* Are we called from setup_redirects(squirrel==NULL)
  7176. * in redirect in a [v]forked child?
  7177. */
  7178. if (sqp == NULL) {
  7179. /* No need to move script fds.
  7180. * For NOMMU case, it's actively wrong: we'd change ->fd
  7181. * fields in memory for the parent, but parent's fds
  7182. * aren't moved, it would use wrong fd!
  7183. * Reproducer: "cmd 3>FILE" in script.
  7184. * If we would call move_HFILEs_on_redirect(), child would:
  7185. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7186. * close(3) = 0
  7187. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7188. */
  7189. //bb_error_msg("sqp == NULL: [v]forked child");
  7190. return 0;
  7191. }
  7192. /* If this one of script's fds? */
  7193. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7194. return 1; /* yes. "we closed fd" (actually moved it) */
  7195. /* Are we called for "exec 3>FILE"? Came through
  7196. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7197. * This case used to fail for this script:
  7198. * exec 3>FILE
  7199. * echo Ok
  7200. * ...100000 more lines...
  7201. * echo Ok
  7202. * as follows:
  7203. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7204. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7205. * dup2(4, 3) = 3
  7206. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7207. * close(4) = 0
  7208. * write(1, "Ok\n", 3) = 3
  7209. * ... = 3
  7210. * write(1, "Ok\n", 3) = 3
  7211. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7212. * ^^^^^^^^ oops, wrong fd!!!
  7213. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7214. * it now works:
  7215. */
  7216. if (sqp == ERR_PTR) {
  7217. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7218. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7219. return 0;
  7220. }
  7221. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7222. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7223. return 0; /* "we did not close fd" */
  7224. }
  7225. static void restore_redirects(struct squirrel *sq)
  7226. {
  7227. if (sq) {
  7228. int i;
  7229. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7230. if (sq[i].moved_to >= 0) {
  7231. /* We simply die on error */
  7232. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7233. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7234. } else {
  7235. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7236. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7237. close(sq[i].orig_fd);
  7238. }
  7239. }
  7240. free(sq);
  7241. }
  7242. if (G.HFILE_stdin
  7243. && G.HFILE_stdin->fd != STDIN_FILENO
  7244. ) {
  7245. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7246. * Redirect moves ->fd to e.g. 10,
  7247. * and it is not restored above (we do not restore script fds
  7248. * after redirects, we just use new, "moved" fds).
  7249. * However for stdin, get_user_input() -> read_line_input(),
  7250. * and read builtin, depend on fd == STDIN_FILENO.
  7251. */
  7252. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7253. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7254. G.HFILE_stdin->fd = STDIN_FILENO;
  7255. }
  7256. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7257. }
  7258. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7259. static void close_saved_fds_and_FILE_fds(void)
  7260. {
  7261. if (G_interactive_fd)
  7262. close(G_interactive_fd);
  7263. close_all_HFILE_list();
  7264. }
  7265. #endif
  7266. static int internally_opened_fd(int fd, struct squirrel *sq)
  7267. {
  7268. int i;
  7269. #if ENABLE_HUSH_INTERACTIVE
  7270. if (fd == G_interactive_fd)
  7271. return 1;
  7272. #endif
  7273. /* If this one of script's fds? */
  7274. if (fd_in_HFILEs(fd))
  7275. return 1;
  7276. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7277. if (fd == sq[i].moved_to)
  7278. return 1;
  7279. }
  7280. return 0;
  7281. }
  7282. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7283. * and stderr if they are redirected. */
  7284. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7285. {
  7286. struct redir_struct *redir;
  7287. for (redir = prog->redirects; redir; redir = redir->next) {
  7288. int newfd;
  7289. int closed;
  7290. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7291. /* "rd_fd<<HERE" case */
  7292. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7293. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7294. * of the heredoc */
  7295. debug_printf_redir("set heredoc '%s'\n",
  7296. redir->rd_filename);
  7297. setup_heredoc(redir);
  7298. continue;
  7299. }
  7300. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7301. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7302. char *p;
  7303. int mode;
  7304. if (redir->rd_filename == NULL) {
  7305. /* Examples:
  7306. * "cmd >" (no filename)
  7307. * "cmd > <file" (2nd redirect starts too early)
  7308. */
  7309. syntax_error("invalid redirect");
  7310. continue;
  7311. }
  7312. mode = redir_table[redir->rd_type].mode;
  7313. p = expand_string_to_string(redir->rd_filename,
  7314. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7315. newfd = open_or_warn(p, mode);
  7316. free(p);
  7317. if (newfd < 0) {
  7318. /* Error message from open_or_warn can be lost
  7319. * if stderr has been redirected, but bash
  7320. * and ash both lose it as well
  7321. * (though zsh doesn't!)
  7322. */
  7323. return 1;
  7324. }
  7325. if (newfd == redir->rd_fd && sqp) {
  7326. /* open() gave us precisely the fd we wanted.
  7327. * This means that this fd was not busy
  7328. * (not opened to anywhere).
  7329. * Remember to close it on restore:
  7330. */
  7331. *sqp = add_squirrel_closed(*sqp, newfd);
  7332. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7333. }
  7334. } else {
  7335. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7336. newfd = redir->rd_dup;
  7337. }
  7338. if (newfd == redir->rd_fd)
  7339. continue;
  7340. /* if "N>FILE": move newfd to redir->rd_fd */
  7341. /* if "N>&M": dup newfd to redir->rd_fd */
  7342. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7343. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7344. if (newfd == REDIRFD_CLOSE) {
  7345. /* "N>&-" means "close me" */
  7346. if (!closed) {
  7347. /* ^^^ optimization: saving may already
  7348. * have closed it. If not... */
  7349. close(redir->rd_fd);
  7350. }
  7351. /* Sometimes we do another close on restore, getting EBADF.
  7352. * Consider "echo 3>FILE 3>&-"
  7353. * first redirect remembers "need to close 3",
  7354. * and second redirect closes 3! Restore code then closes 3 again.
  7355. */
  7356. } else {
  7357. /* if newfd is a script fd or saved fd, simulate EBADF */
  7358. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7359. //errno = EBADF;
  7360. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7361. newfd = -1; /* same effect as code above */
  7362. }
  7363. xdup2(newfd, redir->rd_fd);
  7364. if (redir->rd_dup == REDIRFD_TO_FILE)
  7365. /* "rd_fd > FILE" */
  7366. close(newfd);
  7367. /* else: "rd_fd > rd_dup" */
  7368. }
  7369. }
  7370. return 0;
  7371. }
  7372. static char *find_in_path(const char *arg)
  7373. {
  7374. char *ret = NULL;
  7375. const char *PATH = get_local_var_value("PATH");
  7376. if (!PATH)
  7377. return NULL;
  7378. while (1) {
  7379. const char *end = strchrnul(PATH, ':');
  7380. int sz = end - PATH; /* must be int! */
  7381. free(ret);
  7382. if (sz != 0) {
  7383. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7384. } else {
  7385. /* We have xxx::yyyy in $PATH,
  7386. * it means "use current dir" */
  7387. ret = xstrdup(arg);
  7388. }
  7389. if (access(ret, F_OK) == 0)
  7390. break;
  7391. if (*end == '\0') {
  7392. free(ret);
  7393. return NULL;
  7394. }
  7395. PATH = end + 1;
  7396. }
  7397. return ret;
  7398. }
  7399. static const struct built_in_command *find_builtin_helper(const char *name,
  7400. const struct built_in_command *x,
  7401. const struct built_in_command *end)
  7402. {
  7403. while (x != end) {
  7404. if (strcmp(name, x->b_cmd) != 0) {
  7405. x++;
  7406. continue;
  7407. }
  7408. debug_printf_exec("found builtin '%s'\n", name);
  7409. return x;
  7410. }
  7411. return NULL;
  7412. }
  7413. static const struct built_in_command *find_builtin1(const char *name)
  7414. {
  7415. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7416. }
  7417. static const struct built_in_command *find_builtin(const char *name)
  7418. {
  7419. const struct built_in_command *x = find_builtin1(name);
  7420. if (x)
  7421. return x;
  7422. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7423. }
  7424. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7425. static const char * FAST_FUNC get_builtin_name(int i)
  7426. {
  7427. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7428. return bltins1[i].b_cmd;
  7429. }
  7430. i -= ARRAY_SIZE(bltins1);
  7431. if (i < ARRAY_SIZE(bltins2)) {
  7432. return bltins2[i].b_cmd;
  7433. }
  7434. return NULL;
  7435. }
  7436. #endif
  7437. static void remove_nested_vars(void)
  7438. {
  7439. struct variable *cur;
  7440. struct variable **cur_pp;
  7441. cur_pp = &G.top_var;
  7442. while ((cur = *cur_pp) != NULL) {
  7443. if (cur->var_nest_level <= G.var_nest_level) {
  7444. cur_pp = &cur->next;
  7445. continue;
  7446. }
  7447. /* Unexport */
  7448. if (cur->flg_export) {
  7449. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7450. bb_unsetenv(cur->varstr);
  7451. }
  7452. /* Remove from global list */
  7453. *cur_pp = cur->next;
  7454. /* Free */
  7455. if (!cur->max_len) {
  7456. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7457. free(cur->varstr);
  7458. }
  7459. free(cur);
  7460. }
  7461. }
  7462. static void enter_var_nest_level(void)
  7463. {
  7464. G.var_nest_level++;
  7465. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7466. /* Try: f() { echo -n .; f; }; f
  7467. * struct variable::var_nest_level is uint16_t,
  7468. * thus limiting recursion to < 2^16.
  7469. * In any case, with 8 Mbyte stack SEGV happens
  7470. * not too long after 2^16 recursions anyway.
  7471. */
  7472. if (G.var_nest_level > 0xff00)
  7473. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7474. }
  7475. static void leave_var_nest_level(void)
  7476. {
  7477. G.var_nest_level--;
  7478. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7479. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7480. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7481. remove_nested_vars();
  7482. }
  7483. #if ENABLE_HUSH_FUNCTIONS
  7484. static struct function **find_function_slot(const char *name)
  7485. {
  7486. struct function *funcp;
  7487. struct function **funcpp = &G.top_func;
  7488. while ((funcp = *funcpp) != NULL) {
  7489. if (strcmp(name, funcp->name) == 0) {
  7490. debug_printf_exec("found function '%s'\n", name);
  7491. break;
  7492. }
  7493. funcpp = &funcp->next;
  7494. }
  7495. return funcpp;
  7496. }
  7497. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7498. {
  7499. const struct function *funcp = *find_function_slot(name);
  7500. return funcp;
  7501. }
  7502. /* Note: takes ownership on name ptr */
  7503. static struct function *new_function(char *name)
  7504. {
  7505. struct function **funcpp = find_function_slot(name);
  7506. struct function *funcp = *funcpp;
  7507. if (funcp != NULL) {
  7508. struct command *cmd = funcp->parent_cmd;
  7509. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7510. if (!cmd) {
  7511. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7512. free(funcp->name);
  7513. /* Note: if !funcp->body, do not free body_as_string!
  7514. * This is a special case of "-F name body" function:
  7515. * body_as_string was not malloced! */
  7516. if (funcp->body) {
  7517. free_pipe_list(funcp->body);
  7518. # if !BB_MMU
  7519. free(funcp->body_as_string);
  7520. # endif
  7521. }
  7522. } else {
  7523. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7524. cmd->argv[0] = funcp->name;
  7525. cmd->group = funcp->body;
  7526. # if !BB_MMU
  7527. cmd->group_as_string = funcp->body_as_string;
  7528. # endif
  7529. }
  7530. } else {
  7531. debug_printf_exec("remembering new function '%s'\n", name);
  7532. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7533. /*funcp->next = NULL;*/
  7534. }
  7535. funcp->name = name;
  7536. return funcp;
  7537. }
  7538. # if ENABLE_HUSH_UNSET
  7539. static void unset_func(const char *name)
  7540. {
  7541. struct function **funcpp = find_function_slot(name);
  7542. struct function *funcp = *funcpp;
  7543. if (funcp != NULL) {
  7544. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7545. *funcpp = funcp->next;
  7546. /* funcp is unlinked now, deleting it.
  7547. * Note: if !funcp->body, the function was created by
  7548. * "-F name body", do not free ->body_as_string
  7549. * and ->name as they were not malloced. */
  7550. if (funcp->body) {
  7551. free_pipe_list(funcp->body);
  7552. free(funcp->name);
  7553. # if !BB_MMU
  7554. free(funcp->body_as_string);
  7555. # endif
  7556. }
  7557. free(funcp);
  7558. }
  7559. }
  7560. # endif
  7561. # if BB_MMU
  7562. #define exec_function(to_free, funcp, argv) \
  7563. exec_function(funcp, argv)
  7564. # endif
  7565. static void exec_function(char ***to_free,
  7566. const struct function *funcp,
  7567. char **argv) NORETURN;
  7568. static void exec_function(char ***to_free,
  7569. const struct function *funcp,
  7570. char **argv)
  7571. {
  7572. # if BB_MMU
  7573. int n;
  7574. argv[0] = G.global_argv[0];
  7575. G.global_argv = argv;
  7576. G.global_argc = n = 1 + string_array_len(argv + 1);
  7577. // Example when we are here: "cmd | func"
  7578. // func will run with saved-redirect fds open.
  7579. // $ f() { echo /proc/self/fd/*; }
  7580. // $ true | f
  7581. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7582. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7583. // Same in script:
  7584. // $ . ./SCRIPT
  7585. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7586. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7587. // They are CLOEXEC so external programs won't see them, but
  7588. // for "more correctness" we might want to close those extra fds here:
  7589. //? close_saved_fds_and_FILE_fds();
  7590. /* "we are in a function, ok to use return" */
  7591. G_flag_return_in_progress = -1;
  7592. enter_var_nest_level();
  7593. IF_HUSH_LOCAL(G.func_nest_level++;)
  7594. /* On MMU, funcp->body is always non-NULL */
  7595. n = run_list(funcp->body);
  7596. fflush_all();
  7597. _exit(n);
  7598. # else
  7599. //? close_saved_fds_and_FILE_fds();
  7600. //TODO: check whether "true | func_with_return" works
  7601. re_execute_shell(to_free,
  7602. funcp->body_as_string,
  7603. G.global_argv[0],
  7604. argv + 1,
  7605. NULL);
  7606. # endif
  7607. }
  7608. static int run_function(const struct function *funcp, char **argv)
  7609. {
  7610. int rc;
  7611. save_arg_t sv;
  7612. smallint sv_flg;
  7613. save_and_replace_G_args(&sv, argv);
  7614. /* "We are in function, ok to use return" */
  7615. sv_flg = G_flag_return_in_progress;
  7616. G_flag_return_in_progress = -1;
  7617. /* Make "local" variables properly shadow previous ones */
  7618. IF_HUSH_LOCAL(enter_var_nest_level();)
  7619. IF_HUSH_LOCAL(G.func_nest_level++;)
  7620. /* On MMU, funcp->body is always non-NULL */
  7621. # if !BB_MMU
  7622. if (!funcp->body) {
  7623. /* Function defined by -F */
  7624. parse_and_run_string(funcp->body_as_string);
  7625. rc = G.last_exitcode;
  7626. } else
  7627. # endif
  7628. {
  7629. rc = run_list(funcp->body);
  7630. }
  7631. IF_HUSH_LOCAL(G.func_nest_level--;)
  7632. IF_HUSH_LOCAL(leave_var_nest_level();)
  7633. G_flag_return_in_progress = sv_flg;
  7634. # if ENABLE_HUSH_TRAP
  7635. debug_printf_exec("G.return_exitcode=-1\n");
  7636. G.return_exitcode = -1; /* invalidate stashed return value */
  7637. # endif
  7638. restore_G_args(&sv, argv);
  7639. return rc;
  7640. }
  7641. #endif /* ENABLE_HUSH_FUNCTIONS */
  7642. #if BB_MMU
  7643. #define exec_builtin(to_free, x, argv) \
  7644. exec_builtin(x, argv)
  7645. #else
  7646. #define exec_builtin(to_free, x, argv) \
  7647. exec_builtin(to_free, argv)
  7648. #endif
  7649. static void exec_builtin(char ***to_free,
  7650. const struct built_in_command *x,
  7651. char **argv) NORETURN;
  7652. static void exec_builtin(char ***to_free,
  7653. const struct built_in_command *x,
  7654. char **argv)
  7655. {
  7656. #if BB_MMU
  7657. int rcode;
  7658. fflush_all();
  7659. //? close_saved_fds_and_FILE_fds();
  7660. rcode = x->b_function(argv);
  7661. fflush_all();
  7662. _exit(rcode);
  7663. #else
  7664. fflush_all();
  7665. /* On NOMMU, we must never block!
  7666. * Example: { sleep 99 | read line; } & echo Ok
  7667. */
  7668. re_execute_shell(to_free,
  7669. argv[0],
  7670. G.global_argv[0],
  7671. G.global_argv + 1,
  7672. argv);
  7673. #endif
  7674. }
  7675. static void execvp_or_die(char **argv) NORETURN;
  7676. static void execvp_or_die(char **argv)
  7677. {
  7678. int e;
  7679. debug_printf_exec("execing '%s'\n", argv[0]);
  7680. /* Don't propagate SIG_IGN to the child */
  7681. if (SPECIAL_JOBSTOP_SIGS != 0)
  7682. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7683. execvp(argv[0], argv);
  7684. e = 2;
  7685. if (errno == EACCES) e = 126;
  7686. if (errno == ENOENT) e = 127;
  7687. bb_perror_msg("can't execute '%s'", argv[0]);
  7688. _exit(e);
  7689. }
  7690. #if ENABLE_HUSH_MODE_X
  7691. static void x_mode_print_optionally_squoted(const char *str)
  7692. {
  7693. unsigned len;
  7694. const char *cp;
  7695. cp = str;
  7696. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7697. /* test a char with: bash -c 'set -x; echo "CH"' */
  7698. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7699. " " "\001\002\003\004\005\006\007"
  7700. "\010\011\012\013\014\015\016\017"
  7701. "\020\021\022\023\024\025\026\027"
  7702. "\030\031\032\033\034\035\036\037"
  7703. )
  7704. ] == '\0'
  7705. ) {
  7706. /* string has no special chars */
  7707. x_mode_addstr(str);
  7708. return;
  7709. }
  7710. cp = str;
  7711. for (;;) {
  7712. /* print '....' up to EOL or first squote */
  7713. len = (int)(strchrnul(cp, '\'') - cp);
  7714. if (len != 0) {
  7715. x_mode_addchr('\'');
  7716. x_mode_addblock(cp, len);
  7717. x_mode_addchr('\'');
  7718. cp += len;
  7719. }
  7720. if (*cp == '\0')
  7721. break;
  7722. /* string contains squote(s), print them as \' */
  7723. x_mode_addchr('\\');
  7724. x_mode_addchr('\'');
  7725. cp++;
  7726. }
  7727. }
  7728. static void dump_cmd_in_x_mode(char **argv)
  7729. {
  7730. if (G_x_mode && argv) {
  7731. unsigned n;
  7732. /* "+[+++...][ cmd...]\n\0" */
  7733. x_mode_prefix();
  7734. n = 0;
  7735. while (argv[n]) {
  7736. x_mode_addchr(' ');
  7737. if (argv[n][0] == '\0') {
  7738. x_mode_addchr('\'');
  7739. x_mode_addchr('\'');
  7740. } else {
  7741. x_mode_print_optionally_squoted(argv[n]);
  7742. }
  7743. n++;
  7744. }
  7745. x_mode_flush();
  7746. }
  7747. }
  7748. #else
  7749. # define dump_cmd_in_x_mode(argv) ((void)0)
  7750. #endif
  7751. #if ENABLE_HUSH_COMMAND
  7752. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7753. {
  7754. char *to_free;
  7755. if (!opt_vV)
  7756. return;
  7757. to_free = NULL;
  7758. if (!explanation) {
  7759. char *path = getenv("PATH");
  7760. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7761. if (!explanation)
  7762. _exit(1); /* PROG was not found */
  7763. if (opt_vV != 'V')
  7764. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7765. }
  7766. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7767. free(to_free);
  7768. fflush_all();
  7769. _exit(0);
  7770. }
  7771. #else
  7772. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7773. #endif
  7774. #if BB_MMU
  7775. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7776. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7777. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7778. pseudo_exec(command, argv_expanded)
  7779. #endif
  7780. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7781. * Never returns.
  7782. * Don't exit() here. If you don't exec, use _exit instead.
  7783. * The at_exit handlers apparently confuse the calling process,
  7784. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7785. */
  7786. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7787. char **argv, int assignment_cnt,
  7788. char **argv_expanded) NORETURN;
  7789. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7790. char **argv, int assignment_cnt,
  7791. char **argv_expanded)
  7792. {
  7793. const struct built_in_command *x;
  7794. struct variable **sv_shadowed;
  7795. char **new_env;
  7796. IF_HUSH_COMMAND(char opt_vV = 0;)
  7797. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7798. new_env = expand_assignments(argv, assignment_cnt);
  7799. dump_cmd_in_x_mode(new_env);
  7800. if (!argv[assignment_cnt]) {
  7801. /* Case when we are here: ... | var=val | ...
  7802. * (note that we do not exit early, i.e., do not optimize out
  7803. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7804. */
  7805. free_strings(new_env);
  7806. _exit(EXIT_SUCCESS);
  7807. }
  7808. sv_shadowed = G.shadowed_vars_pp;
  7809. #if BB_MMU
  7810. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7811. #else
  7812. G.shadowed_vars_pp = &nommu_save->old_vars;
  7813. G.var_nest_level++;
  7814. #endif
  7815. set_vars_and_save_old(new_env);
  7816. G.shadowed_vars_pp = sv_shadowed;
  7817. if (argv_expanded) {
  7818. argv = argv_expanded;
  7819. } else {
  7820. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7821. #if !BB_MMU
  7822. nommu_save->argv = argv;
  7823. #endif
  7824. }
  7825. dump_cmd_in_x_mode(argv);
  7826. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7827. if (strchr(argv[0], '/') != NULL)
  7828. goto skip;
  7829. #endif
  7830. #if ENABLE_HUSH_FUNCTIONS
  7831. /* Check if the command matches any functions (this goes before bltins) */
  7832. funcp = find_function(argv[0]);
  7833. if (funcp)
  7834. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7835. #endif
  7836. #if ENABLE_HUSH_COMMAND
  7837. /* "command BAR": run BAR without looking it up among functions
  7838. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7839. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7840. */
  7841. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7842. char *p;
  7843. argv++;
  7844. p = *argv;
  7845. if (p[0] != '-' || !p[1])
  7846. continue; /* bash allows "command command command [-OPT] BAR" */
  7847. for (;;) {
  7848. p++;
  7849. switch (*p) {
  7850. case '\0':
  7851. argv++;
  7852. p = *argv;
  7853. if (p[0] != '-' || !p[1])
  7854. goto after_opts;
  7855. continue; /* next arg is also -opts, process it too */
  7856. case 'v':
  7857. case 'V':
  7858. opt_vV = *p;
  7859. continue;
  7860. default:
  7861. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7862. }
  7863. }
  7864. }
  7865. after_opts:
  7866. # if ENABLE_HUSH_FUNCTIONS
  7867. if (opt_vV && find_function(argv[0]))
  7868. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7869. # endif
  7870. #endif
  7871. /* Check if the command matches any of the builtins.
  7872. * Depending on context, this might be redundant. But it's
  7873. * easier to waste a few CPU cycles than it is to figure out
  7874. * if this is one of those cases.
  7875. */
  7876. /* Why "BB_MMU ? :" difference in logic? -
  7877. * On NOMMU, it is more expensive to re-execute shell
  7878. * just in order to run echo or test builtin.
  7879. * It's better to skip it here and run corresponding
  7880. * non-builtin later. */
  7881. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7882. if (x) {
  7883. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7884. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7885. }
  7886. #if ENABLE_FEATURE_SH_STANDALONE
  7887. /* Check if the command matches any busybox applets */
  7888. {
  7889. int a = find_applet_by_name(argv[0]);
  7890. if (a >= 0) {
  7891. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7892. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7893. if (APPLET_IS_NOEXEC(a)) {
  7894. /* Do not leak open fds from opened script files etc.
  7895. * Testcase: interactive "ls -l /proc/self/fd"
  7896. * should not show tty fd open.
  7897. */
  7898. close_saved_fds_and_FILE_fds();
  7899. //FIXME: should also close saved redir fds
  7900. //This casuses test failures in
  7901. //redir_children_should_not_see_saved_fd_2.tests
  7902. //redir_children_should_not_see_saved_fd_3.tests
  7903. //if you replace "busybox find" with just "find" in them
  7904. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7905. switch_off_special_sigs(G.special_sig_mask);
  7906. debug_printf_exec("running applet '%s'\n", argv[0]);
  7907. run_noexec_applet_and_exit(a, argv[0], argv);
  7908. }
  7909. # endif
  7910. /* Re-exec ourselves */
  7911. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7912. /* Don't propagate SIG_IGN to the child */
  7913. if (SPECIAL_JOBSTOP_SIGS != 0)
  7914. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7915. execv(bb_busybox_exec_path, argv);
  7916. /* If they called chroot or otherwise made the binary no longer
  7917. * executable, fall through */
  7918. }
  7919. }
  7920. #endif
  7921. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7922. skip:
  7923. #endif
  7924. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7925. execvp_or_die(argv);
  7926. }
  7927. /* Called after [v]fork() in run_pipe
  7928. */
  7929. static void pseudo_exec(nommu_save_t *nommu_save,
  7930. struct command *command,
  7931. char **argv_expanded) NORETURN;
  7932. static void pseudo_exec(nommu_save_t *nommu_save,
  7933. struct command *command,
  7934. char **argv_expanded)
  7935. {
  7936. #if ENABLE_HUSH_FUNCTIONS
  7937. if (command->cmd_type == CMD_FUNCDEF) {
  7938. /* Ignore funcdefs in pipes:
  7939. * true | f() { cmd }
  7940. */
  7941. _exit(0);
  7942. }
  7943. #endif
  7944. if (command->argv) {
  7945. pseudo_exec_argv(nommu_save, command->argv,
  7946. command->assignment_cnt, argv_expanded);
  7947. }
  7948. if (command->group) {
  7949. /* Cases when we are here:
  7950. * ( list )
  7951. * { list } &
  7952. * ... | ( list ) | ...
  7953. * ... | { list } | ...
  7954. */
  7955. #if BB_MMU
  7956. int rcode;
  7957. debug_printf_exec("pseudo_exec: run_list\n");
  7958. reset_traps_to_defaults();
  7959. rcode = run_list(command->group);
  7960. /* OK to leak memory by not calling free_pipe_list,
  7961. * since this process is about to exit */
  7962. _exit(rcode);
  7963. #else
  7964. re_execute_shell(&nommu_save->argv_from_re_execing,
  7965. command->group_as_string,
  7966. G.global_argv[0],
  7967. G.global_argv + 1,
  7968. NULL);
  7969. #endif
  7970. }
  7971. /* Case when we are here: ... | >file */
  7972. debug_printf_exec("pseudo_exec'ed null command\n");
  7973. _exit(EXIT_SUCCESS);
  7974. }
  7975. #if ENABLE_HUSH_JOB
  7976. static const char *get_cmdtext(struct pipe *pi)
  7977. {
  7978. char **argv;
  7979. char *p;
  7980. int len;
  7981. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7982. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7983. * On subsequent bg argv is trashed, but we won't use it */
  7984. if (pi->cmdtext)
  7985. return pi->cmdtext;
  7986. argv = pi->cmds[0].argv;
  7987. if (!argv) {
  7988. pi->cmdtext = xzalloc(1);
  7989. return pi->cmdtext;
  7990. }
  7991. len = 0;
  7992. do {
  7993. len += strlen(*argv) + 1;
  7994. } while (*++argv);
  7995. p = xmalloc(len);
  7996. pi->cmdtext = p;
  7997. argv = pi->cmds[0].argv;
  7998. do {
  7999. p = stpcpy(p, *argv);
  8000. *p++ = ' ';
  8001. } while (*++argv);
  8002. p[-1] = '\0';
  8003. return pi->cmdtext;
  8004. }
  8005. static void remove_job_from_table(struct pipe *pi)
  8006. {
  8007. struct pipe *prev_pipe;
  8008. if (pi == G.job_list) {
  8009. G.job_list = pi->next;
  8010. } else {
  8011. prev_pipe = G.job_list;
  8012. while (prev_pipe->next != pi)
  8013. prev_pipe = prev_pipe->next;
  8014. prev_pipe->next = pi->next;
  8015. }
  8016. G.last_jobid = 0;
  8017. if (G.job_list)
  8018. G.last_jobid = G.job_list->jobid;
  8019. }
  8020. static void delete_finished_job(struct pipe *pi)
  8021. {
  8022. remove_job_from_table(pi);
  8023. free_pipe(pi);
  8024. }
  8025. static void clean_up_last_dead_job(void)
  8026. {
  8027. if (G.job_list && !G.job_list->alive_cmds)
  8028. delete_finished_job(G.job_list);
  8029. }
  8030. static void insert_job_into_table(struct pipe *pi)
  8031. {
  8032. struct pipe *job, **jobp;
  8033. int i;
  8034. clean_up_last_dead_job();
  8035. /* Find the end of the list, and find next job ID to use */
  8036. i = 0;
  8037. jobp = &G.job_list;
  8038. while ((job = *jobp) != NULL) {
  8039. if (job->jobid > i)
  8040. i = job->jobid;
  8041. jobp = &job->next;
  8042. }
  8043. pi->jobid = i + 1;
  8044. /* Create a new job struct at the end */
  8045. job = *jobp = xmemdup(pi, sizeof(*pi));
  8046. job->next = NULL;
  8047. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8048. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8049. for (i = 0; i < pi->num_cmds; i++) {
  8050. job->cmds[i].pid = pi->cmds[i].pid;
  8051. /* all other fields are not used and stay zero */
  8052. }
  8053. job->cmdtext = xstrdup(get_cmdtext(pi));
  8054. if (G_interactive_fd)
  8055. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8056. G.last_jobid = job->jobid;
  8057. }
  8058. #endif /* JOB */
  8059. static int job_exited_or_stopped(struct pipe *pi)
  8060. {
  8061. int rcode, i;
  8062. if (pi->alive_cmds != pi->stopped_cmds)
  8063. return -1;
  8064. /* All processes in fg pipe have exited or stopped */
  8065. rcode = 0;
  8066. i = pi->num_cmds;
  8067. while (--i >= 0) {
  8068. rcode = pi->cmds[i].cmd_exitcode;
  8069. /* usually last process gives overall exitstatus,
  8070. * but with "set -o pipefail", last *failed* process does */
  8071. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8072. break;
  8073. }
  8074. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8075. return rcode;
  8076. }
  8077. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8078. {
  8079. #if ENABLE_HUSH_JOB
  8080. struct pipe *pi;
  8081. #endif
  8082. int i, dead;
  8083. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8084. #if DEBUG_JOBS
  8085. if (WIFSTOPPED(status))
  8086. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8087. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8088. if (WIFSIGNALED(status))
  8089. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8090. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8091. if (WIFEXITED(status))
  8092. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8093. childpid, WEXITSTATUS(status));
  8094. #endif
  8095. /* Were we asked to wait for a fg pipe? */
  8096. if (fg_pipe) {
  8097. i = fg_pipe->num_cmds;
  8098. while (--i >= 0) {
  8099. int rcode;
  8100. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8101. if (fg_pipe->cmds[i].pid != childpid)
  8102. continue;
  8103. if (dead) {
  8104. int ex;
  8105. fg_pipe->cmds[i].pid = 0;
  8106. fg_pipe->alive_cmds--;
  8107. ex = WEXITSTATUS(status);
  8108. /* bash prints killer signal's name for *last*
  8109. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8110. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8111. */
  8112. if (WIFSIGNALED(status)) {
  8113. int sig = WTERMSIG(status);
  8114. if (G.run_list_level == 1
  8115. /* ^^^^^ Do not print in nested contexts, example:
  8116. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8117. */
  8118. && i == fg_pipe->num_cmds-1
  8119. ) {
  8120. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8121. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8122. }
  8123. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8124. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8125. * Maybe we need to use sig | 128? */
  8126. ex = sig + 128;
  8127. }
  8128. fg_pipe->cmds[i].cmd_exitcode = ex;
  8129. } else {
  8130. fg_pipe->stopped_cmds++;
  8131. }
  8132. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8133. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8134. rcode = job_exited_or_stopped(fg_pipe);
  8135. if (rcode >= 0) {
  8136. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8137. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8138. * and "killall -STOP cat" */
  8139. if (G_interactive_fd) {
  8140. #if ENABLE_HUSH_JOB
  8141. if (fg_pipe->alive_cmds != 0)
  8142. insert_job_into_table(fg_pipe);
  8143. #endif
  8144. return rcode;
  8145. }
  8146. if (fg_pipe->alive_cmds == 0)
  8147. return rcode;
  8148. }
  8149. /* There are still running processes in the fg_pipe */
  8150. return -1;
  8151. }
  8152. /* It wasn't in fg_pipe, look for process in bg pipes */
  8153. }
  8154. #if ENABLE_HUSH_JOB
  8155. /* We were asked to wait for bg or orphaned children */
  8156. /* No need to remember exitcode in this case */
  8157. for (pi = G.job_list; pi; pi = pi->next) {
  8158. for (i = 0; i < pi->num_cmds; i++) {
  8159. if (pi->cmds[i].pid == childpid)
  8160. goto found_pi_and_prognum;
  8161. }
  8162. }
  8163. /* Happens when shell is used as init process (init=/bin/sh) */
  8164. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8165. return -1; /* this wasn't a process from fg_pipe */
  8166. found_pi_and_prognum:
  8167. if (dead) {
  8168. /* child exited */
  8169. int rcode = WEXITSTATUS(status);
  8170. if (WIFSIGNALED(status))
  8171. rcode = 128 + WTERMSIG(status);
  8172. pi->cmds[i].cmd_exitcode = rcode;
  8173. if (G.last_bg_pid == pi->cmds[i].pid)
  8174. G.last_bg_pid_exitcode = rcode;
  8175. pi->cmds[i].pid = 0;
  8176. pi->alive_cmds--;
  8177. if (!pi->alive_cmds) {
  8178. # if ENABLE_HUSH_BASH_COMPAT
  8179. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8180. # endif
  8181. if (G_interactive_fd) {
  8182. printf(JOB_STATUS_FORMAT, pi->jobid,
  8183. "Done", pi->cmdtext);
  8184. delete_finished_job(pi);
  8185. } else {
  8186. /*
  8187. * bash deletes finished jobs from job table only in interactive mode,
  8188. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8189. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8190. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8191. * We only retain one "dead" job, if it's the single job on the list.
  8192. * This covers most of real-world scenarios where this is useful.
  8193. */
  8194. if (pi != G.job_list)
  8195. delete_finished_job(pi);
  8196. }
  8197. }
  8198. } else {
  8199. /* child stopped */
  8200. pi->stopped_cmds++;
  8201. }
  8202. #endif
  8203. return -1; /* this wasn't a process from fg_pipe */
  8204. }
  8205. /* Check to see if any processes have exited -- if they have,
  8206. * figure out why and see if a job has completed.
  8207. *
  8208. * If non-NULL fg_pipe: wait for its completion or stop.
  8209. * Return its exitcode or zero if stopped.
  8210. *
  8211. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8212. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8213. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8214. * or 0 if no children changed status.
  8215. *
  8216. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8217. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8218. * or 0 if no children changed status.
  8219. */
  8220. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8221. {
  8222. int attributes;
  8223. int status;
  8224. int rcode = 0;
  8225. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8226. attributes = WUNTRACED;
  8227. if (fg_pipe == NULL)
  8228. attributes |= WNOHANG;
  8229. errno = 0;
  8230. #if ENABLE_HUSH_FAST
  8231. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8232. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8233. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8234. /* There was neither fork nor SIGCHLD since last waitpid */
  8235. /* Avoid doing waitpid syscall if possible */
  8236. if (!G.we_have_children) {
  8237. errno = ECHILD;
  8238. return -1;
  8239. }
  8240. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8241. /* We have children, but they did not exit
  8242. * or stop yet (we saw no SIGCHLD) */
  8243. return 0;
  8244. }
  8245. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8246. }
  8247. #endif
  8248. /* Do we do this right?
  8249. * bash-3.00# sleep 20 | false
  8250. * <ctrl-Z pressed>
  8251. * [3]+ Stopped sleep 20 | false
  8252. * bash-3.00# echo $?
  8253. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8254. * [hush 1.14.0: yes we do it right]
  8255. */
  8256. while (1) {
  8257. pid_t childpid;
  8258. #if ENABLE_HUSH_FAST
  8259. int i;
  8260. i = G.count_SIGCHLD;
  8261. #endif
  8262. childpid = waitpid(-1, &status, attributes);
  8263. if (childpid <= 0) {
  8264. if (childpid && errno != ECHILD)
  8265. bb_simple_perror_msg("waitpid");
  8266. #if ENABLE_HUSH_FAST
  8267. else { /* Until next SIGCHLD, waitpid's are useless */
  8268. G.we_have_children = (childpid == 0);
  8269. G.handled_SIGCHLD = i;
  8270. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8271. }
  8272. #endif
  8273. /* ECHILD (no children), or 0 (no change in children status) */
  8274. rcode = childpid;
  8275. break;
  8276. }
  8277. rcode = process_wait_result(fg_pipe, childpid, status);
  8278. if (rcode >= 0) {
  8279. /* fg_pipe exited or stopped */
  8280. break;
  8281. }
  8282. if (childpid == waitfor_pid) { /* "wait PID" */
  8283. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8284. rcode = WEXITSTATUS(status);
  8285. if (WIFSIGNALED(status))
  8286. rcode = 128 + WTERMSIG(status);
  8287. if (WIFSTOPPED(status))
  8288. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8289. rcode = 128 + WSTOPSIG(status);
  8290. rcode++;
  8291. break; /* "wait PID" called us, give it exitcode+1 */
  8292. }
  8293. #if ENABLE_HUSH_BASH_COMPAT
  8294. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8295. && G.dead_job_exitcode >= 0 /* some job did finish */
  8296. ) {
  8297. debug_printf_exec("waitfor_pid:-1\n");
  8298. rcode = G.dead_job_exitcode + 1;
  8299. break;
  8300. }
  8301. #endif
  8302. /* This wasn't one of our processes, or */
  8303. /* fg_pipe still has running processes, do waitpid again */
  8304. } /* while (waitpid succeeds)... */
  8305. return rcode;
  8306. }
  8307. #if ENABLE_HUSH_JOB
  8308. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8309. {
  8310. pid_t p;
  8311. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8312. if (G_saved_tty_pgrp) {
  8313. /* Job finished, move the shell to the foreground */
  8314. p = getpgrp(); /* our process group id */
  8315. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8316. tcsetpgrp(G_interactive_fd, p);
  8317. }
  8318. return rcode;
  8319. }
  8320. #endif
  8321. /* Start all the jobs, but don't wait for anything to finish.
  8322. * See checkjobs().
  8323. *
  8324. * Return code is normally -1, when the caller has to wait for children
  8325. * to finish to determine the exit status of the pipe. If the pipe
  8326. * is a simple builtin command, however, the action is done by the
  8327. * time run_pipe returns, and the exit code is provided as the
  8328. * return value.
  8329. *
  8330. * Returns -1 only if started some children. IOW: we have to
  8331. * mask out retvals of builtins etc with 0xff!
  8332. *
  8333. * The only case when we do not need to [v]fork is when the pipe
  8334. * is single, non-backgrounded, non-subshell command. Examples:
  8335. * cmd ; ... { list } ; ...
  8336. * cmd && ... { list } && ...
  8337. * cmd || ... { list } || ...
  8338. * If it is, then we can run cmd as a builtin, NOFORK,
  8339. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8340. * with run_list. If it isn't one of these, we fork and exec cmd.
  8341. *
  8342. * Cases when we must fork:
  8343. * non-single: cmd | cmd
  8344. * backgrounded: cmd & { list } &
  8345. * subshell: ( list ) [&]
  8346. */
  8347. #if !ENABLE_HUSH_MODE_X
  8348. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8349. redirect_and_varexp_helper(command, sqp)
  8350. #endif
  8351. static int redirect_and_varexp_helper(
  8352. struct command *command,
  8353. struct squirrel **sqp,
  8354. char **argv_expanded)
  8355. {
  8356. /* Assignments occur before redirects. Try:
  8357. * a=`sleep 1` sleep 2 3>/qwe/rty
  8358. */
  8359. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8360. dump_cmd_in_x_mode(new_env);
  8361. dump_cmd_in_x_mode(argv_expanded);
  8362. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8363. set_vars_and_save_old(new_env);
  8364. return setup_redirects(command, sqp);
  8365. }
  8366. static NOINLINE int run_pipe(struct pipe *pi)
  8367. {
  8368. static const char *const null_ptr = NULL;
  8369. int cmd_no;
  8370. int next_infd;
  8371. struct command *command;
  8372. char **argv_expanded;
  8373. char **argv;
  8374. struct squirrel *squirrel = NULL;
  8375. int rcode;
  8376. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8377. debug_enter();
  8378. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8379. * Result should be 3 lines: q w e, qwe, q w e
  8380. */
  8381. if (G.ifs_whitespace != G.ifs)
  8382. free(G.ifs_whitespace);
  8383. G.ifs = get_local_var_value("IFS");
  8384. if (G.ifs) {
  8385. char *p;
  8386. G.ifs_whitespace = (char*)G.ifs;
  8387. p = skip_whitespace(G.ifs);
  8388. if (*p) {
  8389. /* Not all $IFS is whitespace */
  8390. char *d;
  8391. int len = p - G.ifs;
  8392. p = skip_non_whitespace(p);
  8393. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8394. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8395. while (*p) {
  8396. if (isspace(*p))
  8397. *d++ = *p;
  8398. p++;
  8399. }
  8400. *d = '\0';
  8401. }
  8402. } else {
  8403. G.ifs = defifs;
  8404. G.ifs_whitespace = (char*)G.ifs;
  8405. }
  8406. IF_HUSH_JOB(pi->pgrp = -1;)
  8407. pi->stopped_cmds = 0;
  8408. command = &pi->cmds[0];
  8409. argv_expanded = NULL;
  8410. if (pi->num_cmds != 1
  8411. || pi->followup == PIPE_BG
  8412. || command->cmd_type == CMD_SUBSHELL
  8413. ) {
  8414. goto must_fork;
  8415. }
  8416. pi->alive_cmds = 1;
  8417. debug_printf_exec(": group:%p argv:'%s'\n",
  8418. command->group, command->argv ? command->argv[0] : "NONE");
  8419. if (command->group) {
  8420. #if ENABLE_HUSH_FUNCTIONS
  8421. if (command->cmd_type == CMD_FUNCDEF) {
  8422. /* "executing" func () { list } */
  8423. struct function *funcp;
  8424. funcp = new_function(command->argv[0]);
  8425. /* funcp->name is already set to argv[0] */
  8426. funcp->body = command->group;
  8427. # if !BB_MMU
  8428. funcp->body_as_string = command->group_as_string;
  8429. command->group_as_string = NULL;
  8430. # endif
  8431. command->group = NULL;
  8432. command->argv[0] = NULL;
  8433. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8434. funcp->parent_cmd = command;
  8435. command->child_func = funcp;
  8436. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8437. debug_leave();
  8438. return EXIT_SUCCESS;
  8439. }
  8440. #endif
  8441. /* { list } */
  8442. debug_printf_exec("non-subshell group\n");
  8443. rcode = 1; /* exitcode if redir failed */
  8444. if (setup_redirects(command, &squirrel) == 0) {
  8445. debug_printf_exec(": run_list\n");
  8446. //FIXME: we need to pass squirrel down into run_list()
  8447. //for SH_STANDALONE case, or else this construct:
  8448. // { find /proc/self/fd; true; } >FILE; cmd2
  8449. //has no way of closing saved fd#1 for "find",
  8450. //and in SH_STANDALONE mode, "find" is not execed,
  8451. //therefore CLOEXEC on saved fd does not help.
  8452. rcode = run_list(command->group) & 0xff;
  8453. }
  8454. restore_redirects(squirrel);
  8455. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8456. debug_leave();
  8457. debug_printf_exec("run_pipe: return %d\n", rcode);
  8458. return rcode;
  8459. }
  8460. argv = command->argv ? command->argv : (char **) &null_ptr;
  8461. {
  8462. const struct built_in_command *x;
  8463. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8464. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8465. struct variable **sv_shadowed;
  8466. struct variable *old_vars;
  8467. #if ENABLE_HUSH_LINENO_VAR
  8468. G.execute_lineno = command->lineno;
  8469. #endif
  8470. if (argv[command->assignment_cnt] == NULL) {
  8471. /* Assignments, but no command.
  8472. * Ensure redirects take effect (that is, create files).
  8473. * Try "a=t >file"
  8474. */
  8475. unsigned i;
  8476. G.expand_exitcode = 0;
  8477. only_assignments:
  8478. rcode = setup_redirects(command, &squirrel);
  8479. restore_redirects(squirrel);
  8480. /* Set shell variables */
  8481. i = 0;
  8482. while (i < command->assignment_cnt) {
  8483. char *p = expand_string_to_string(argv[i],
  8484. EXP_FLAG_ESC_GLOB_CHARS,
  8485. /*unbackslash:*/ 1
  8486. );
  8487. #if ENABLE_HUSH_MODE_X
  8488. if (G_x_mode) {
  8489. char *eq;
  8490. if (i == 0)
  8491. x_mode_prefix();
  8492. x_mode_addchr(' ');
  8493. eq = strchrnul(p, '=');
  8494. if (*eq) eq++;
  8495. x_mode_addblock(p, (eq - p));
  8496. x_mode_print_optionally_squoted(eq);
  8497. x_mode_flush();
  8498. }
  8499. #endif
  8500. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8501. if (set_local_var(p, /*flag:*/ 0)) {
  8502. /* assignment to readonly var / putenv error? */
  8503. rcode = 1;
  8504. }
  8505. i++;
  8506. }
  8507. /* Redirect error sets $? to 1. Otherwise,
  8508. * if evaluating assignment value set $?, retain it.
  8509. * Else, clear $?:
  8510. * false; q=`exit 2`; echo $? - should print 2
  8511. * false; x=1; echo $? - should print 0
  8512. * Because of the 2nd case, we can't just use G.last_exitcode.
  8513. */
  8514. if (rcode == 0)
  8515. rcode = G.expand_exitcode;
  8516. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8517. debug_leave();
  8518. debug_printf_exec("run_pipe: return %d\n", rcode);
  8519. return rcode;
  8520. }
  8521. /* Expand the rest into (possibly) many strings each */
  8522. #if defined(CMD_SINGLEWORD_NOGLOB)
  8523. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8524. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8525. else
  8526. #endif
  8527. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8528. /* If someone gives us an empty string: `cmd with empty output` */
  8529. if (!argv_expanded[0]) {
  8530. free(argv_expanded);
  8531. /* `false` still has to set exitcode 1 */
  8532. G.expand_exitcode = G.last_exitcode;
  8533. goto only_assignments;
  8534. }
  8535. old_vars = NULL;
  8536. sv_shadowed = G.shadowed_vars_pp;
  8537. /* Check if argv[0] matches any functions (this goes before bltins) */
  8538. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8539. IF_HUSH_FUNCTIONS(x = NULL;)
  8540. IF_HUSH_FUNCTIONS(if (!funcp))
  8541. x = find_builtin(argv_expanded[0]);
  8542. if (x || funcp) {
  8543. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8544. debug_printf("exec with redirects only\n");
  8545. /*
  8546. * Variable assignments are executed, but then "forgotten":
  8547. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8548. * sleeps, but prints nothing.
  8549. */
  8550. enter_var_nest_level();
  8551. G.shadowed_vars_pp = &old_vars;
  8552. rcode = redirect_and_varexp_helper(command,
  8553. /*squirrel:*/ ERR_PTR,
  8554. argv_expanded
  8555. );
  8556. G.shadowed_vars_pp = sv_shadowed;
  8557. /* rcode=1 can be if redir file can't be opened */
  8558. goto clean_up_and_ret1;
  8559. }
  8560. /* Bump var nesting, or this will leak exported $a:
  8561. * a=b true; env | grep ^a=
  8562. */
  8563. enter_var_nest_level();
  8564. /* Collect all variables "shadowed" by helper
  8565. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8566. * into old_vars list:
  8567. */
  8568. G.shadowed_vars_pp = &old_vars;
  8569. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8570. if (rcode == 0) {
  8571. if (!funcp) {
  8572. /* Do not collect *to old_vars list* vars shadowed
  8573. * by e.g. "local VAR" builtin (collect them
  8574. * in the previously nested list instead):
  8575. * don't want them to be restored immediately
  8576. * after "local" completes.
  8577. */
  8578. G.shadowed_vars_pp = sv_shadowed;
  8579. debug_printf_exec(": builtin '%s' '%s'...\n",
  8580. x->b_cmd, argv_expanded[1]);
  8581. fflush_all();
  8582. rcode = x->b_function(argv_expanded) & 0xff;
  8583. fflush_all();
  8584. }
  8585. #if ENABLE_HUSH_FUNCTIONS
  8586. else {
  8587. debug_printf_exec(": function '%s' '%s'...\n",
  8588. funcp->name, argv_expanded[1]);
  8589. rcode = run_function(funcp, argv_expanded) & 0xff;
  8590. /*
  8591. * But do collect *to old_vars list* vars shadowed
  8592. * within function execution. To that end, restore
  8593. * this pointer _after_ function run:
  8594. */
  8595. G.shadowed_vars_pp = sv_shadowed;
  8596. }
  8597. #endif
  8598. }
  8599. } else
  8600. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8601. int n = find_applet_by_name(argv_expanded[0]);
  8602. if (n < 0 || !APPLET_IS_NOFORK(n))
  8603. goto must_fork;
  8604. enter_var_nest_level();
  8605. /* Collect all variables "shadowed" by helper into old_vars list */
  8606. G.shadowed_vars_pp = &old_vars;
  8607. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8608. G.shadowed_vars_pp = sv_shadowed;
  8609. if (rcode == 0) {
  8610. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8611. argv_expanded[0], argv_expanded[1]);
  8612. /*
  8613. * Note: signals (^C) can't interrupt here.
  8614. * We remember them and they will be acted upon
  8615. * after applet returns.
  8616. * This makes applets which can run for a long time
  8617. * and/or wait for user input ineligible for NOFORK:
  8618. * for example, "yes" or "rm" (rm -i waits for input).
  8619. */
  8620. rcode = run_nofork_applet(n, argv_expanded);
  8621. }
  8622. } else
  8623. goto must_fork;
  8624. restore_redirects(squirrel);
  8625. clean_up_and_ret1:
  8626. leave_var_nest_level();
  8627. add_vars(old_vars);
  8628. /*
  8629. * Try "usleep 99999999" + ^C + "echo $?"
  8630. * with FEATURE_SH_NOFORK=y.
  8631. */
  8632. if (!funcp) {
  8633. /* It was builtin or nofork.
  8634. * if this would be a real fork/execed program,
  8635. * it should have died if a fatal sig was received.
  8636. * But OTOH, there was no separate process,
  8637. * the sig was sent to _shell_, not to non-existing
  8638. * child.
  8639. * Let's just handle ^C only, this one is obvious:
  8640. * we aren't ok with exitcode 0 when ^C was pressed
  8641. * during builtin/nofork.
  8642. */
  8643. if (sigismember(&G.pending_set, SIGINT))
  8644. rcode = 128 + SIGINT;
  8645. }
  8646. free(argv_expanded);
  8647. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8648. debug_leave();
  8649. debug_printf_exec("run_pipe return %d\n", rcode);
  8650. return rcode;
  8651. }
  8652. must_fork:
  8653. /* NB: argv_expanded may already be created, and that
  8654. * might include `cmd` runs! Do not rerun it! We *must*
  8655. * use argv_expanded if it's non-NULL */
  8656. /* Going to fork a child per each pipe member */
  8657. pi->alive_cmds = 0;
  8658. next_infd = 0;
  8659. cmd_no = 0;
  8660. while (cmd_no < pi->num_cmds) {
  8661. struct fd_pair pipefds;
  8662. #if !BB_MMU
  8663. int sv_var_nest_level = G.var_nest_level;
  8664. volatile nommu_save_t nommu_save;
  8665. nommu_save.old_vars = NULL;
  8666. nommu_save.argv = NULL;
  8667. nommu_save.argv_from_re_execing = NULL;
  8668. #endif
  8669. command = &pi->cmds[cmd_no];
  8670. cmd_no++;
  8671. if (command->argv) {
  8672. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8673. command->argv[0], command->argv[1]);
  8674. } else {
  8675. debug_printf_exec(": pipe member with no argv\n");
  8676. }
  8677. /* pipes are inserted between pairs of commands */
  8678. pipefds.rd = 0;
  8679. pipefds.wr = 1;
  8680. if (cmd_no < pi->num_cmds)
  8681. xpiped_pair(pipefds);
  8682. #if ENABLE_HUSH_LINENO_VAR
  8683. G.execute_lineno = command->lineno;
  8684. #endif
  8685. command->pid = BB_MMU ? fork() : vfork();
  8686. if (!command->pid) { /* child */
  8687. #if ENABLE_HUSH_JOB
  8688. disable_restore_tty_pgrp_on_exit();
  8689. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8690. /* Every child adds itself to new process group
  8691. * with pgid == pid_of_first_child_in_pipe */
  8692. if (G.run_list_level == 1 && G_interactive_fd) {
  8693. pid_t pgrp;
  8694. pgrp = pi->pgrp;
  8695. if (pgrp < 0) /* true for 1st process only */
  8696. pgrp = getpid();
  8697. if (setpgid(0, pgrp) == 0
  8698. && pi->followup != PIPE_BG
  8699. && G_saved_tty_pgrp /* we have ctty */
  8700. ) {
  8701. /* We do it in *every* child, not just first,
  8702. * to avoid races */
  8703. tcsetpgrp(G_interactive_fd, pgrp);
  8704. }
  8705. }
  8706. #endif
  8707. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8708. /* 1st cmd in backgrounded pipe
  8709. * should have its stdin /dev/null'ed */
  8710. close(0);
  8711. if (open(bb_dev_null, O_RDONLY))
  8712. xopen("/", O_RDONLY);
  8713. } else {
  8714. xmove_fd(next_infd, 0);
  8715. }
  8716. xmove_fd(pipefds.wr, 1);
  8717. if (pipefds.rd > 1)
  8718. close(pipefds.rd);
  8719. /* Like bash, explicit redirects override pipes,
  8720. * and the pipe fd (fd#1) is available for dup'ing:
  8721. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8722. * of cmd1 goes into pipe.
  8723. */
  8724. if (setup_redirects(command, NULL)) {
  8725. /* Happens when redir file can't be opened:
  8726. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8727. * FOO
  8728. * hush: can't open '/qwe/rty': No such file or directory
  8729. * BAZ
  8730. * (echo BAR is not executed, it hits _exit(1) below)
  8731. */
  8732. _exit(1);
  8733. }
  8734. /* Stores to nommu_save list of env vars putenv'ed
  8735. * (NOMMU, on MMU we don't need that) */
  8736. /* cast away volatility... */
  8737. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8738. /* pseudo_exec() does not return */
  8739. }
  8740. /* parent or error */
  8741. #if ENABLE_HUSH_FAST
  8742. G.count_SIGCHLD++;
  8743. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8744. #endif
  8745. enable_restore_tty_pgrp_on_exit();
  8746. #if !BB_MMU
  8747. /* Clean up after vforked child */
  8748. free(nommu_save.argv);
  8749. free(nommu_save.argv_from_re_execing);
  8750. G.var_nest_level = sv_var_nest_level;
  8751. remove_nested_vars();
  8752. add_vars(nommu_save.old_vars);
  8753. #endif
  8754. free(argv_expanded);
  8755. argv_expanded = NULL;
  8756. if (command->pid < 0) { /* [v]fork failed */
  8757. /* Clearly indicate, was it fork or vfork */
  8758. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8759. } else {
  8760. pi->alive_cmds++;
  8761. #if ENABLE_HUSH_JOB
  8762. /* Second and next children need to know pid of first one */
  8763. if (pi->pgrp < 0)
  8764. pi->pgrp = command->pid;
  8765. #endif
  8766. }
  8767. if (cmd_no > 1)
  8768. close(next_infd);
  8769. if (cmd_no < pi->num_cmds)
  8770. close(pipefds.wr);
  8771. /* Pass read (output) pipe end to next iteration */
  8772. next_infd = pipefds.rd;
  8773. }
  8774. if (!pi->alive_cmds) {
  8775. debug_leave();
  8776. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8777. return 1;
  8778. }
  8779. debug_leave();
  8780. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8781. return -1;
  8782. }
  8783. /* NB: called by pseudo_exec, and therefore must not modify any
  8784. * global data until exec/_exit (we can be a child after vfork!) */
  8785. static int run_list(struct pipe *pi)
  8786. {
  8787. #if ENABLE_HUSH_CASE
  8788. char *case_word = NULL;
  8789. #endif
  8790. #if ENABLE_HUSH_LOOPS
  8791. struct pipe *loop_top = NULL;
  8792. char **for_lcur = NULL;
  8793. char **for_list = NULL;
  8794. #endif
  8795. smallint last_followup;
  8796. smalluint rcode;
  8797. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8798. smalluint cond_code = 0;
  8799. #else
  8800. enum { cond_code = 0 };
  8801. #endif
  8802. #if HAS_KEYWORDS
  8803. smallint rword; /* RES_foo */
  8804. smallint last_rword; /* ditto */
  8805. #endif
  8806. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8807. debug_enter();
  8808. #if ENABLE_HUSH_LOOPS
  8809. /* Check syntax for "for" */
  8810. {
  8811. struct pipe *cpipe;
  8812. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8813. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8814. continue;
  8815. /* current word is FOR or IN (BOLD in comments below) */
  8816. if (cpipe->next == NULL) {
  8817. syntax_error("malformed for");
  8818. debug_leave();
  8819. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8820. return 1;
  8821. }
  8822. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8823. if (cpipe->next->res_word == RES_DO)
  8824. continue;
  8825. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8826. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8827. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8828. ) {
  8829. syntax_error("malformed for");
  8830. debug_leave();
  8831. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8832. return 1;
  8833. }
  8834. }
  8835. }
  8836. #endif
  8837. /* Past this point, all code paths should jump to ret: label
  8838. * in order to return, no direct "return" statements please.
  8839. * This helps to ensure that no memory is leaked. */
  8840. #if ENABLE_HUSH_JOB
  8841. G.run_list_level++;
  8842. #endif
  8843. #if HAS_KEYWORDS
  8844. rword = RES_NONE;
  8845. last_rword = RES_XXXX;
  8846. #endif
  8847. last_followup = PIPE_SEQ;
  8848. rcode = G.last_exitcode;
  8849. /* Go through list of pipes, (maybe) executing them. */
  8850. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8851. int r;
  8852. int sv_errexit_depth;
  8853. if (G.flag_SIGINT)
  8854. break;
  8855. if (G_flag_return_in_progress == 1)
  8856. break;
  8857. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8858. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8859. rword, cond_code, last_rword);
  8860. sv_errexit_depth = G.errexit_depth;
  8861. if (
  8862. #if ENABLE_HUSH_IF
  8863. rword == RES_IF || rword == RES_ELIF ||
  8864. #endif
  8865. pi->followup != PIPE_SEQ
  8866. ) {
  8867. G.errexit_depth++;
  8868. }
  8869. #if ENABLE_HUSH_LOOPS
  8870. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8871. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8872. ) {
  8873. /* start of a loop: remember where loop starts */
  8874. loop_top = pi;
  8875. G.depth_of_loop++;
  8876. }
  8877. #endif
  8878. /* Still in the same "if...", "then..." or "do..." branch? */
  8879. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8880. if ((rcode == 0 && last_followup == PIPE_OR)
  8881. || (rcode != 0 && last_followup == PIPE_AND)
  8882. ) {
  8883. /* It is "<true> || CMD" or "<false> && CMD"
  8884. * and we should not execute CMD */
  8885. debug_printf_exec("skipped cmd because of || or &&\n");
  8886. last_followup = pi->followup;
  8887. goto dont_check_jobs_but_continue;
  8888. }
  8889. }
  8890. last_followup = pi->followup;
  8891. IF_HAS_KEYWORDS(last_rword = rword;)
  8892. #if ENABLE_HUSH_IF
  8893. if (cond_code) {
  8894. if (rword == RES_THEN) {
  8895. /* if false; then ... fi has exitcode 0! */
  8896. G.last_exitcode = rcode = EXIT_SUCCESS;
  8897. /* "if <false> THEN cmd": skip cmd */
  8898. continue;
  8899. }
  8900. } else {
  8901. if (rword == RES_ELSE || rword == RES_ELIF) {
  8902. /* "if <true> then ... ELSE/ELIF cmd":
  8903. * skip cmd and all following ones */
  8904. break;
  8905. }
  8906. }
  8907. #endif
  8908. #if ENABLE_HUSH_LOOPS
  8909. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8910. if (!for_lcur) {
  8911. /* first loop through for */
  8912. static const char encoded_dollar_at[] ALIGN1 = {
  8913. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8914. }; /* encoded representation of "$@" */
  8915. static const char *const encoded_dollar_at_argv[] = {
  8916. encoded_dollar_at, NULL
  8917. }; /* argv list with one element: "$@" */
  8918. char **vals;
  8919. G.last_exitcode = rcode = EXIT_SUCCESS;
  8920. vals = (char**)encoded_dollar_at_argv;
  8921. if (pi->next->res_word == RES_IN) {
  8922. /* if no variable values after "in" we skip "for" */
  8923. if (!pi->next->cmds[0].argv) {
  8924. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8925. break;
  8926. }
  8927. vals = pi->next->cmds[0].argv;
  8928. } /* else: "for var; do..." -> assume "$@" list */
  8929. /* create list of variable values */
  8930. debug_print_strings("for_list made from", vals);
  8931. for_list = expand_strvec_to_strvec(vals);
  8932. for_lcur = for_list;
  8933. debug_print_strings("for_list", for_list);
  8934. }
  8935. if (!*for_lcur) {
  8936. /* "for" loop is over, clean up */
  8937. free(for_list);
  8938. for_list = NULL;
  8939. for_lcur = NULL;
  8940. break;
  8941. }
  8942. /* Insert next value from for_lcur */
  8943. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8944. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8945. continue;
  8946. }
  8947. if (rword == RES_IN) {
  8948. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8949. }
  8950. if (rword == RES_DONE) {
  8951. continue; /* "done" has no cmds too */
  8952. }
  8953. #endif
  8954. #if ENABLE_HUSH_CASE
  8955. if (rword == RES_CASE) {
  8956. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8957. case_word = expand_string_to_string(pi->cmds->argv[0],
  8958. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8959. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8960. //unbackslash(case_word);
  8961. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8962. continue;
  8963. }
  8964. if (rword == RES_MATCH) {
  8965. char **argv;
  8966. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8967. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8968. break;
  8969. /* all prev words didn't match, does this one match? */
  8970. argv = pi->cmds->argv;
  8971. while (*argv) {
  8972. char *pattern;
  8973. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8974. pattern = expand_string_to_string(*argv,
  8975. EXP_FLAG_ESC_GLOB_CHARS,
  8976. /*unbackslash:*/ 0
  8977. );
  8978. /* TODO: which FNM_xxx flags to use? */
  8979. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8980. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8981. pattern, case_word, cond_code);
  8982. free(pattern);
  8983. if (cond_code == 0) {
  8984. /* match! we will execute this branch */
  8985. free(case_word);
  8986. case_word = NULL; /* make future "word)" stop */
  8987. break;
  8988. }
  8989. argv++;
  8990. }
  8991. continue;
  8992. }
  8993. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8994. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8995. if (cond_code != 0)
  8996. continue; /* not matched yet, skip this pipe */
  8997. }
  8998. if (rword == RES_ESAC) {
  8999. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9000. if (case_word) {
  9001. /* "case" did not match anything: still set $? (to 0) */
  9002. G.last_exitcode = rcode = EXIT_SUCCESS;
  9003. }
  9004. }
  9005. #endif
  9006. /* Just pressing <enter> in shell should check for jobs.
  9007. * OTOH, in non-interactive shell this is useless
  9008. * and only leads to extra job checks */
  9009. if (pi->num_cmds == 0) {
  9010. if (G_interactive_fd)
  9011. goto check_jobs_and_continue;
  9012. continue;
  9013. }
  9014. /* After analyzing all keywords and conditions, we decided
  9015. * to execute this pipe. NB: have to do checkjobs(NULL)
  9016. * after run_pipe to collect any background children,
  9017. * even if list execution is to be stopped. */
  9018. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9019. #if ENABLE_HUSH_LOOPS
  9020. G.flag_break_continue = 0;
  9021. #endif
  9022. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9023. if (r != -1) {
  9024. /* We ran a builtin, function, or group.
  9025. * rcode is already known
  9026. * and we don't need to wait for anything. */
  9027. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9028. G.last_exitcode = rcode;
  9029. check_and_run_traps();
  9030. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9031. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9032. #endif
  9033. #if ENABLE_HUSH_LOOPS
  9034. /* Was it "break" or "continue"? */
  9035. if (G.flag_break_continue) {
  9036. smallint fbc = G.flag_break_continue;
  9037. /* We might fall into outer *loop*,
  9038. * don't want to break it too */
  9039. if (loop_top) {
  9040. G.depth_break_continue--;
  9041. if (G.depth_break_continue == 0)
  9042. G.flag_break_continue = 0;
  9043. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9044. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9045. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9046. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9047. break;
  9048. }
  9049. /* "continue": simulate end of loop */
  9050. rword = RES_DONE;
  9051. continue;
  9052. }
  9053. #endif
  9054. if (G_flag_return_in_progress == 1) {
  9055. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9056. break;
  9057. }
  9058. } else if (pi->followup == PIPE_BG) {
  9059. /* What does bash do with attempts to background builtins? */
  9060. /* even bash 3.2 doesn't do that well with nested bg:
  9061. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9062. * I'm NOT treating inner &'s as jobs */
  9063. #if ENABLE_HUSH_JOB
  9064. if (G.run_list_level == 1)
  9065. insert_job_into_table(pi);
  9066. #endif
  9067. /* Last command's pid goes to $! */
  9068. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9069. G.last_bg_pid_exitcode = 0;
  9070. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9071. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9072. rcode = EXIT_SUCCESS;
  9073. goto check_traps;
  9074. } else {
  9075. #if ENABLE_HUSH_JOB
  9076. if (G.run_list_level == 1 && G_interactive_fd) {
  9077. /* Waits for completion, then fg's main shell */
  9078. rcode = checkjobs_and_fg_shell(pi);
  9079. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9080. goto check_traps;
  9081. }
  9082. #endif
  9083. /* This one just waits for completion */
  9084. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9085. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9086. check_traps:
  9087. G.last_exitcode = rcode;
  9088. check_and_run_traps();
  9089. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9090. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9091. #endif
  9092. }
  9093. /* Handle "set -e" */
  9094. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9095. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9096. if (G.errexit_depth == 0)
  9097. hush_exit(rcode);
  9098. }
  9099. G.errexit_depth = sv_errexit_depth;
  9100. /* Analyze how result affects subsequent commands */
  9101. #if ENABLE_HUSH_IF
  9102. if (rword == RES_IF || rword == RES_ELIF)
  9103. cond_code = rcode;
  9104. #endif
  9105. check_jobs_and_continue:
  9106. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9107. dont_check_jobs_but_continue: ;
  9108. #if ENABLE_HUSH_LOOPS
  9109. /* Beware of "while false; true; do ..."! */
  9110. if (pi->next
  9111. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9112. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9113. ) {
  9114. if (rword == RES_WHILE) {
  9115. if (rcode) {
  9116. /* "while false; do...done" - exitcode 0 */
  9117. G.last_exitcode = rcode = EXIT_SUCCESS;
  9118. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9119. break;
  9120. }
  9121. }
  9122. if (rword == RES_UNTIL) {
  9123. if (!rcode) {
  9124. debug_printf_exec(": until expr is true: breaking\n");
  9125. break;
  9126. }
  9127. }
  9128. }
  9129. #endif
  9130. } /* for (pi) */
  9131. #if ENABLE_HUSH_JOB
  9132. G.run_list_level--;
  9133. #endif
  9134. #if ENABLE_HUSH_LOOPS
  9135. if (loop_top)
  9136. G.depth_of_loop--;
  9137. free(for_list);
  9138. #endif
  9139. #if ENABLE_HUSH_CASE
  9140. free(case_word);
  9141. #endif
  9142. debug_leave();
  9143. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9144. return rcode;
  9145. }
  9146. /* Select which version we will use */
  9147. static int run_and_free_list(struct pipe *pi)
  9148. {
  9149. int rcode = 0;
  9150. debug_printf_exec("run_and_free_list entered\n");
  9151. if (!G.o_opt[OPT_O_NOEXEC]) {
  9152. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9153. rcode = run_list(pi);
  9154. }
  9155. /* free_pipe_list has the side effect of clearing memory.
  9156. * In the long run that function can be merged with run_list,
  9157. * but doing that now would hobble the debugging effort. */
  9158. free_pipe_list(pi);
  9159. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9160. return rcode;
  9161. }
  9162. static void install_sighandlers(unsigned mask)
  9163. {
  9164. sighandler_t old_handler;
  9165. unsigned sig = 0;
  9166. while ((mask >>= 1) != 0) {
  9167. sig++;
  9168. if (!(mask & 1))
  9169. continue;
  9170. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9171. /* POSIX allows shell to re-enable SIGCHLD
  9172. * even if it was SIG_IGN on entry.
  9173. * Therefore we skip IGN check for it:
  9174. */
  9175. if (sig == SIGCHLD)
  9176. continue;
  9177. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9178. * Try:
  9179. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9180. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9181. */
  9182. if (sig == SIGHUP && G_interactive_fd)
  9183. continue;
  9184. /* Unless one of the above signals, is it SIG_IGN? */
  9185. if (old_handler == SIG_IGN) {
  9186. /* oops... restore back to IGN, and record this fact */
  9187. install_sighandler(sig, old_handler);
  9188. #if ENABLE_HUSH_TRAP
  9189. if (!G_traps)
  9190. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9191. free(G_traps[sig]);
  9192. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9193. #endif
  9194. }
  9195. }
  9196. }
  9197. /* Called a few times only (or even once if "sh -c") */
  9198. static void install_special_sighandlers(void)
  9199. {
  9200. unsigned mask;
  9201. /* Which signals are shell-special? */
  9202. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9203. if (G_interactive_fd) {
  9204. mask |= SPECIAL_INTERACTIVE_SIGS;
  9205. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9206. mask |= SPECIAL_JOBSTOP_SIGS;
  9207. }
  9208. /* Careful, do not re-install handlers we already installed */
  9209. if (G.special_sig_mask != mask) {
  9210. unsigned diff = mask & ~G.special_sig_mask;
  9211. G.special_sig_mask = mask;
  9212. install_sighandlers(diff);
  9213. }
  9214. }
  9215. #if ENABLE_HUSH_JOB
  9216. /* helper */
  9217. /* Set handlers to restore tty pgrp and exit */
  9218. static void install_fatal_sighandlers(void)
  9219. {
  9220. unsigned mask;
  9221. /* We will restore tty pgrp on these signals */
  9222. mask = 0
  9223. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9224. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9225. + (1 << SIGBUS ) * HUSH_DEBUG
  9226. + (1 << SIGSEGV) * HUSH_DEBUG
  9227. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9228. + (1 << SIGABRT)
  9229. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9230. + (1 << SIGPIPE)
  9231. + (1 << SIGALRM)
  9232. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9233. * if we aren't interactive... but in this case
  9234. * we never want to restore pgrp on exit, and this fn is not called
  9235. */
  9236. /*+ (1 << SIGHUP )*/
  9237. /*+ (1 << SIGTERM)*/
  9238. /*+ (1 << SIGINT )*/
  9239. ;
  9240. G_fatal_sig_mask = mask;
  9241. install_sighandlers(mask);
  9242. }
  9243. #endif
  9244. static int set_mode(int state, char mode, const char *o_opt)
  9245. {
  9246. int idx;
  9247. switch (mode) {
  9248. case 'n':
  9249. G.o_opt[OPT_O_NOEXEC] = state;
  9250. break;
  9251. case 'x':
  9252. IF_HUSH_MODE_X(G_x_mode = state;)
  9253. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9254. break;
  9255. case 'e':
  9256. G.o_opt[OPT_O_ERREXIT] = state;
  9257. break;
  9258. case 'o':
  9259. if (!o_opt) {
  9260. /* "set -o" or "set +o" without parameter.
  9261. * in bash, set -o produces this output:
  9262. * pipefail off
  9263. * and set +o:
  9264. * set +o pipefail
  9265. * We always use the second form.
  9266. */
  9267. const char *p = o_opt_strings;
  9268. idx = 0;
  9269. while (*p) {
  9270. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9271. idx++;
  9272. p += strlen(p) + 1;
  9273. }
  9274. break;
  9275. }
  9276. idx = index_in_strings(o_opt_strings, o_opt);
  9277. if (idx >= 0) {
  9278. G.o_opt[idx] = state;
  9279. break;
  9280. }
  9281. /* fall through to error */
  9282. default:
  9283. return EXIT_FAILURE;
  9284. }
  9285. return EXIT_SUCCESS;
  9286. }
  9287. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9288. int hush_main(int argc, char **argv)
  9289. {
  9290. enum {
  9291. OPT_login = (1 << 0),
  9292. };
  9293. unsigned flags;
  9294. unsigned builtin_argc;
  9295. char **e;
  9296. struct variable *cur_var;
  9297. struct variable *shell_ver;
  9298. INIT_G();
  9299. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9300. G.last_exitcode = EXIT_SUCCESS;
  9301. #if ENABLE_HUSH_TRAP
  9302. # if ENABLE_HUSH_FUNCTIONS
  9303. G.return_exitcode = -1;
  9304. # endif
  9305. G.pre_trap_exitcode = -1;
  9306. #endif
  9307. #if ENABLE_HUSH_FAST
  9308. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9309. #endif
  9310. #if !BB_MMU
  9311. G.argv0_for_re_execing = argv[0];
  9312. #endif
  9313. /* Deal with HUSH_VERSION */
  9314. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9315. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9316. shell_ver = xzalloc(sizeof(*shell_ver));
  9317. shell_ver->flg_export = 1;
  9318. shell_ver->flg_read_only = 1;
  9319. /* Code which handles ${var<op>...} needs writable values for all variables,
  9320. * therefore we xstrdup: */
  9321. shell_ver->varstr = xstrdup(hush_version_str);
  9322. /* Create shell local variables from the values
  9323. * currently living in the environment */
  9324. G.top_var = shell_ver;
  9325. cur_var = G.top_var;
  9326. e = environ;
  9327. if (e) while (*e) {
  9328. char *value = strchr(*e, '=');
  9329. if (value) { /* paranoia */
  9330. cur_var->next = xzalloc(sizeof(*cur_var));
  9331. cur_var = cur_var->next;
  9332. cur_var->varstr = *e;
  9333. cur_var->max_len = strlen(*e);
  9334. cur_var->flg_export = 1;
  9335. }
  9336. e++;
  9337. }
  9338. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9339. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9340. putenv(shell_ver->varstr);
  9341. /* Export PWD */
  9342. set_pwd_var(SETFLAG_EXPORT);
  9343. #if BASH_HOSTNAME_VAR
  9344. /* Set (but not export) HOSTNAME unless already set */
  9345. if (!get_local_var_value("HOSTNAME")) {
  9346. struct utsname uts;
  9347. uname(&uts);
  9348. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9349. }
  9350. #endif
  9351. /* IFS is not inherited from the parent environment */
  9352. set_local_var_from_halves("IFS", defifs);
  9353. if (!get_local_var_value("PATH"))
  9354. set_local_var_from_halves("PATH", bb_default_root_path);
  9355. /* PS1/PS2 are set later, if we determine that we are interactive */
  9356. /* bash also exports SHLVL and _,
  9357. * and sets (but doesn't export) the following variables:
  9358. * BASH=/bin/bash
  9359. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9360. * BASH_VERSION='3.2.0(1)-release'
  9361. * HOSTTYPE=i386
  9362. * MACHTYPE=i386-pc-linux-gnu
  9363. * OSTYPE=linux-gnu
  9364. * PPID=<NNNNN> - we also do it elsewhere
  9365. * EUID=<NNNNN>
  9366. * UID=<NNNNN>
  9367. * GROUPS=()
  9368. * LINES=<NNN>
  9369. * COLUMNS=<NNN>
  9370. * BASH_ARGC=()
  9371. * BASH_ARGV=()
  9372. * BASH_LINENO=()
  9373. * BASH_SOURCE=()
  9374. * DIRSTACK=()
  9375. * PIPESTATUS=([0]="0")
  9376. * HISTFILE=/<xxx>/.bash_history
  9377. * HISTFILESIZE=500
  9378. * HISTSIZE=500
  9379. * MAILCHECK=60
  9380. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9381. * SHELL=/bin/bash
  9382. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9383. * TERM=dumb
  9384. * OPTERR=1
  9385. * OPTIND=1
  9386. * PS4='+ '
  9387. */
  9388. /* Initialize some more globals to non-zero values */
  9389. die_func = restore_ttypgrp_and__exit;
  9390. /* Shell is non-interactive at first. We need to call
  9391. * install_special_sighandlers() if we are going to execute "sh <script>",
  9392. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9393. * If we later decide that we are interactive, we run install_special_sighandlers()
  9394. * in order to intercept (more) signals.
  9395. */
  9396. /* Parse options */
  9397. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9398. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9399. builtin_argc = 0;
  9400. #if NUM_SCRIPTS > 0
  9401. if (argc < 0) {
  9402. optarg = get_script_content(-argc - 1);
  9403. optind = 0;
  9404. argc = string_array_len(argv);
  9405. goto run_script;
  9406. }
  9407. #endif
  9408. while (1) {
  9409. int opt = getopt(argc, argv, "+c:exinsl"
  9410. #if !BB_MMU
  9411. "<:$:R:V:"
  9412. # if ENABLE_HUSH_FUNCTIONS
  9413. "F:"
  9414. # endif
  9415. #endif
  9416. );
  9417. if (opt <= 0)
  9418. break;
  9419. switch (opt) {
  9420. case 'c':
  9421. /* Possibilities:
  9422. * sh ... -c 'script'
  9423. * sh ... -c 'script' ARG0 [ARG1...]
  9424. * On NOMMU, if builtin_argc != 0,
  9425. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9426. * "" needs to be replaced with NULL
  9427. * and BARGV vector fed to builtin function.
  9428. * Note: the form without ARG0 never happens:
  9429. * sh ... -c 'builtin' BARGV... ""
  9430. */
  9431. #if NUM_SCRIPTS > 0
  9432. run_script:
  9433. #endif
  9434. if (!G.root_pid) {
  9435. G.root_pid = getpid();
  9436. G.root_ppid = getppid();
  9437. }
  9438. G.global_argv = argv + optind;
  9439. G.global_argc = argc - optind;
  9440. if (builtin_argc) {
  9441. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9442. const struct built_in_command *x;
  9443. install_special_sighandlers();
  9444. x = find_builtin(optarg);
  9445. if (x) { /* paranoia */
  9446. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9447. G.global_argv += builtin_argc;
  9448. G.global_argv[-1] = NULL; /* replace "" */
  9449. fflush_all();
  9450. G.last_exitcode = x->b_function(argv + optind - 1);
  9451. }
  9452. goto final_return;
  9453. }
  9454. G.opt_c = 1;
  9455. if (!G.global_argv[0]) {
  9456. /* -c 'script' (no params): prevent empty $0 */
  9457. G.global_argv--; /* points to argv[i] of 'script' */
  9458. G.global_argv[0] = argv[0];
  9459. G.global_argc++;
  9460. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9461. install_special_sighandlers();
  9462. parse_and_run_string(optarg);
  9463. goto final_return;
  9464. case 'i':
  9465. /* Well, we cannot just declare interactiveness,
  9466. * we have to have some stuff (ctty, etc) */
  9467. /* G_interactive_fd++; */
  9468. break;
  9469. case 's':
  9470. G.opt_s = 1;
  9471. break;
  9472. case 'l':
  9473. flags |= OPT_login;
  9474. break;
  9475. #if !BB_MMU
  9476. case '<': /* "big heredoc" support */
  9477. full_write1_str(optarg);
  9478. _exit(0);
  9479. case '$': {
  9480. unsigned long long empty_trap_mask;
  9481. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9482. optarg++;
  9483. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9484. optarg++;
  9485. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9486. optarg++;
  9487. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9488. optarg++;
  9489. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9490. optarg++;
  9491. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9492. if (empty_trap_mask != 0) {
  9493. IF_HUSH_TRAP(int sig;)
  9494. install_special_sighandlers();
  9495. # if ENABLE_HUSH_TRAP
  9496. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9497. for (sig = 1; sig < NSIG; sig++) {
  9498. if (empty_trap_mask & (1LL << sig)) {
  9499. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9500. install_sighandler(sig, SIG_IGN);
  9501. }
  9502. }
  9503. # endif
  9504. }
  9505. # if ENABLE_HUSH_LOOPS
  9506. optarg++;
  9507. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9508. # endif
  9509. # if ENABLE_HUSH_FUNCTIONS
  9510. /* nommu uses re-exec trick for "... | func | ...",
  9511. * should allow "return".
  9512. * This accidentally allows returns in subshells.
  9513. */
  9514. G_flag_return_in_progress = -1;
  9515. # endif
  9516. break;
  9517. }
  9518. case 'R':
  9519. case 'V':
  9520. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9521. break;
  9522. # if ENABLE_HUSH_FUNCTIONS
  9523. case 'F': {
  9524. struct function *funcp = new_function(optarg);
  9525. /* funcp->name is already set to optarg */
  9526. /* funcp->body is set to NULL. It's a special case. */
  9527. funcp->body_as_string = argv[optind];
  9528. optind++;
  9529. break;
  9530. }
  9531. # endif
  9532. #endif
  9533. case 'n':
  9534. case 'x':
  9535. case 'e':
  9536. if (set_mode(1, opt, NULL) == 0) /* no error */
  9537. break;
  9538. default:
  9539. #ifndef BB_VER
  9540. fprintf(stderr, "Usage: sh [FILE]...\n"
  9541. " or: sh -c command [args]...\n\n");
  9542. exit(EXIT_FAILURE);
  9543. #else
  9544. bb_show_usage();
  9545. #endif
  9546. }
  9547. } /* option parsing loop */
  9548. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9549. G.global_argc = argc - (optind - 1);
  9550. G.global_argv = argv + (optind - 1);
  9551. G.global_argv[0] = argv[0];
  9552. if (!G.root_pid) {
  9553. G.root_pid = getpid();
  9554. G.root_ppid = getppid();
  9555. }
  9556. /* If we are login shell... */
  9557. if (flags & OPT_login) {
  9558. HFILE *input;
  9559. debug_printf("sourcing /etc/profile\n");
  9560. input = hfopen("/etc/profile");
  9561. if (input != NULL) {
  9562. install_special_sighandlers();
  9563. parse_and_run_file(input);
  9564. hfclose(input);
  9565. }
  9566. /* bash: after sourcing /etc/profile,
  9567. * tries to source (in the given order):
  9568. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9569. * stopping on first found. --noprofile turns this off.
  9570. * bash also sources ~/.bash_logout on exit.
  9571. * If called as sh, skips .bash_XXX files.
  9572. */
  9573. }
  9574. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9575. if (!G.opt_s && G.global_argv[1]) {
  9576. HFILE *input;
  9577. /*
  9578. * "bash <script>" (which is never interactive (unless -i?))
  9579. * sources $BASH_ENV here (without scanning $PATH).
  9580. * If called as sh, does the same but with $ENV.
  9581. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9582. */
  9583. G.global_argc--;
  9584. G.global_argv++;
  9585. debug_printf("running script '%s'\n", G.global_argv[0]);
  9586. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9587. input = hfopen(G.global_argv[0]);
  9588. if (!input) {
  9589. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9590. }
  9591. xfunc_error_retval = 1;
  9592. install_special_sighandlers();
  9593. parse_and_run_file(input);
  9594. #if ENABLE_FEATURE_CLEAN_UP
  9595. hfclose(input);
  9596. #endif
  9597. goto final_return;
  9598. }
  9599. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9600. G.opt_s = 1;
  9601. /* Up to here, shell was non-interactive. Now it may become one.
  9602. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9603. */
  9604. /* A shell is interactive if the '-i' flag was given,
  9605. * or if all of the following conditions are met:
  9606. * no -c command
  9607. * no arguments remaining or the -s flag given
  9608. * standard input is a terminal
  9609. * standard output is a terminal
  9610. * Refer to Posix.2, the description of the 'sh' utility.
  9611. */
  9612. #if ENABLE_HUSH_JOB
  9613. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9614. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9615. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9616. if (G_saved_tty_pgrp < 0)
  9617. G_saved_tty_pgrp = 0;
  9618. /* try to dup stdin to high fd#, >= 255 */
  9619. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9620. if (G_interactive_fd < 0) {
  9621. /* try to dup to any fd */
  9622. G_interactive_fd = dup(STDIN_FILENO);
  9623. if (G_interactive_fd < 0) {
  9624. /* give up */
  9625. G_interactive_fd = 0;
  9626. G_saved_tty_pgrp = 0;
  9627. }
  9628. }
  9629. }
  9630. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9631. if (G_interactive_fd) {
  9632. close_on_exec_on(G_interactive_fd);
  9633. if (G_saved_tty_pgrp) {
  9634. /* If we were run as 'hush &', sleep until we are
  9635. * in the foreground (tty pgrp == our pgrp).
  9636. * If we get started under a job aware app (like bash),
  9637. * make sure we are now in charge so we don't fight over
  9638. * who gets the foreground */
  9639. while (1) {
  9640. pid_t shell_pgrp = getpgrp();
  9641. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9642. if (G_saved_tty_pgrp == shell_pgrp)
  9643. break;
  9644. /* send TTIN to ourself (should stop us) */
  9645. kill(- shell_pgrp, SIGTTIN);
  9646. }
  9647. }
  9648. /* Install more signal handlers */
  9649. install_special_sighandlers();
  9650. if (G_saved_tty_pgrp) {
  9651. /* Set other signals to restore saved_tty_pgrp */
  9652. install_fatal_sighandlers();
  9653. /* Put ourselves in our own process group
  9654. * (bash, too, does this only if ctty is available) */
  9655. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9656. /* Grab control of the terminal */
  9657. tcsetpgrp(G_interactive_fd, getpid());
  9658. }
  9659. enable_restore_tty_pgrp_on_exit();
  9660. # if ENABLE_FEATURE_EDITING
  9661. G.line_input_state = new_line_input_t(FOR_SHELL);
  9662. # if EDITING_HAS_get_exe_name
  9663. G.line_input_state->get_exe_name = get_builtin_name;
  9664. # endif
  9665. # endif
  9666. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9667. {
  9668. const char *hp = get_local_var_value("HISTFILE");
  9669. if (!hp) {
  9670. hp = get_local_var_value("HOME");
  9671. if (hp)
  9672. hp = concat_path_file(hp, ".hush_history");
  9673. } else {
  9674. hp = xstrdup(hp);
  9675. }
  9676. if (hp) {
  9677. G.line_input_state->hist_file = hp;
  9678. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9679. }
  9680. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9681. hp = get_local_var_value("HISTFILESIZE");
  9682. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9683. # endif
  9684. }
  9685. # endif
  9686. } else {
  9687. install_special_sighandlers();
  9688. }
  9689. #elif ENABLE_HUSH_INTERACTIVE
  9690. /* No job control compiled in, only prompt/line editing */
  9691. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9692. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9693. if (G_interactive_fd < 0) {
  9694. /* try to dup to any fd */
  9695. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9696. if (G_interactive_fd < 0)
  9697. /* give up */
  9698. G_interactive_fd = 0;
  9699. }
  9700. }
  9701. if (G_interactive_fd) {
  9702. close_on_exec_on(G_interactive_fd);
  9703. }
  9704. install_special_sighandlers();
  9705. #else
  9706. /* We have interactiveness code disabled */
  9707. install_special_sighandlers();
  9708. #endif
  9709. /* bash:
  9710. * if interactive but not a login shell, sources ~/.bashrc
  9711. * (--norc turns this off, --rcfile <file> overrides)
  9712. */
  9713. if (G_interactive_fd) {
  9714. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9715. /* Set (but not export) PS1/2 unless already set */
  9716. if (!get_local_var_value("PS1"))
  9717. set_local_var_from_halves("PS1", "\\w \\$ ");
  9718. if (!get_local_var_value("PS2"))
  9719. set_local_var_from_halves("PS2", "> ");
  9720. #endif
  9721. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9722. /* note: ash and hush share this string */
  9723. printf("\n\n%s %s\n"
  9724. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9725. "\n",
  9726. bb_banner,
  9727. "hush - the humble shell"
  9728. );
  9729. }
  9730. }
  9731. parse_and_run_file(hfopen(NULL)); /* stdin */
  9732. final_return:
  9733. hush_exit(G.last_exitcode);
  9734. }
  9735. /*
  9736. * Built-ins
  9737. */
  9738. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9739. {
  9740. return 0;
  9741. }
  9742. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9743. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9744. {
  9745. int argc = string_array_len(argv);
  9746. return applet_main_func(argc, argv);
  9747. }
  9748. #endif
  9749. #if ENABLE_HUSH_TEST || BASH_TEST2
  9750. static int FAST_FUNC builtin_test(char **argv)
  9751. {
  9752. return run_applet_main(argv, test_main);
  9753. }
  9754. #endif
  9755. #if ENABLE_HUSH_ECHO
  9756. static int FAST_FUNC builtin_echo(char **argv)
  9757. {
  9758. return run_applet_main(argv, echo_main);
  9759. }
  9760. #endif
  9761. #if ENABLE_HUSH_PRINTF
  9762. static int FAST_FUNC builtin_printf(char **argv)
  9763. {
  9764. return run_applet_main(argv, printf_main);
  9765. }
  9766. #endif
  9767. #if ENABLE_HUSH_HELP
  9768. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9769. {
  9770. const struct built_in_command *x;
  9771. printf(
  9772. "Built-in commands:\n"
  9773. "------------------\n");
  9774. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9775. if (x->b_descr)
  9776. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9777. }
  9778. return EXIT_SUCCESS;
  9779. }
  9780. #endif
  9781. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9782. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9783. {
  9784. show_history(G.line_input_state);
  9785. return EXIT_SUCCESS;
  9786. }
  9787. #endif
  9788. static char **skip_dash_dash(char **argv)
  9789. {
  9790. argv++;
  9791. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9792. argv++;
  9793. return argv;
  9794. }
  9795. static int FAST_FUNC builtin_cd(char **argv)
  9796. {
  9797. const char *newdir;
  9798. argv = skip_dash_dash(argv);
  9799. newdir = argv[0];
  9800. if (newdir == NULL) {
  9801. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9802. * bash says "bash: cd: HOME not set" and does nothing
  9803. * (exitcode 1)
  9804. */
  9805. const char *home = get_local_var_value("HOME");
  9806. newdir = home ? home : "/";
  9807. }
  9808. if (chdir(newdir)) {
  9809. /* Mimic bash message exactly */
  9810. bb_perror_msg("cd: %s", newdir);
  9811. return EXIT_FAILURE;
  9812. }
  9813. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9814. * Note: do not enforce exporting. If PWD was unset or unexported,
  9815. * set it again, but do not export. bash does the same.
  9816. */
  9817. set_pwd_var(/*flag:*/ 0);
  9818. return EXIT_SUCCESS;
  9819. }
  9820. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9821. {
  9822. puts(get_cwd(0));
  9823. return EXIT_SUCCESS;
  9824. }
  9825. static int FAST_FUNC builtin_eval(char **argv)
  9826. {
  9827. argv = skip_dash_dash(argv);
  9828. if (!argv[0])
  9829. return EXIT_SUCCESS;
  9830. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9831. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9832. if (!argv[1]) {
  9833. /* bash:
  9834. * eval "echo Hi; done" ("done" is syntax error):
  9835. * "echo Hi" will not execute too.
  9836. */
  9837. parse_and_run_string(argv[0]);
  9838. } else {
  9839. /* "The eval utility shall construct a command by
  9840. * concatenating arguments together, separating
  9841. * each with a <space> character."
  9842. */
  9843. char *str, *p;
  9844. unsigned len = 0;
  9845. char **pp = argv;
  9846. do
  9847. len += strlen(*pp) + 1;
  9848. while (*++pp);
  9849. str = p = xmalloc(len);
  9850. pp = argv;
  9851. for (;;) {
  9852. p = stpcpy(p, *pp);
  9853. pp++;
  9854. if (!*pp)
  9855. break;
  9856. *p++ = ' ';
  9857. }
  9858. parse_and_run_string(str);
  9859. free(str);
  9860. }
  9861. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9862. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9863. return G.last_exitcode;
  9864. }
  9865. static int FAST_FUNC builtin_exec(char **argv)
  9866. {
  9867. argv = skip_dash_dash(argv);
  9868. if (argv[0] == NULL)
  9869. return EXIT_SUCCESS; /* bash does this */
  9870. /* Careful: we can end up here after [v]fork. Do not restore
  9871. * tty pgrp then, only top-level shell process does that */
  9872. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9873. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9874. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9875. * open here. However, they are all CLOEXEC, and execv below
  9876. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9877. * it should show no extra open fds in the "ls" process.
  9878. * If we'd try to run builtins/NOEXECs, this would need improving.
  9879. */
  9880. //close_saved_fds_and_FILE_fds();
  9881. /* TODO: if exec fails, bash does NOT exit! We do.
  9882. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9883. * and tcsetpgrp, and this is inherently racy.
  9884. */
  9885. execvp_or_die(argv);
  9886. }
  9887. static int FAST_FUNC builtin_exit(char **argv)
  9888. {
  9889. debug_printf_exec("%s()\n", __func__);
  9890. /* interactive bash:
  9891. * # trap "echo EEE" EXIT
  9892. * # exit
  9893. * exit
  9894. * There are stopped jobs.
  9895. * (if there are _stopped_ jobs, running ones don't count)
  9896. * # exit
  9897. * exit
  9898. * EEE (then bash exits)
  9899. *
  9900. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9901. */
  9902. /* note: EXIT trap is run by hush_exit */
  9903. argv = skip_dash_dash(argv);
  9904. if (argv[0] == NULL) {
  9905. #if ENABLE_HUSH_TRAP
  9906. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  9907. hush_exit(G.pre_trap_exitcode);
  9908. #endif
  9909. hush_exit(G.last_exitcode);
  9910. }
  9911. /* mimic bash: exit 123abc == exit 255 + error msg */
  9912. xfunc_error_retval = 255;
  9913. /* bash: exit -2 == exit 254, no error msg */
  9914. hush_exit(xatoi(argv[0]) & 0xff);
  9915. }
  9916. #if ENABLE_HUSH_TYPE
  9917. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9918. static int FAST_FUNC builtin_type(char **argv)
  9919. {
  9920. int ret = EXIT_SUCCESS;
  9921. while (*++argv) {
  9922. const char *type;
  9923. char *path = NULL;
  9924. if (0) {} /* make conditional compile easier below */
  9925. /*else if (find_alias(*argv))
  9926. type = "an alias";*/
  9927. # if ENABLE_HUSH_FUNCTIONS
  9928. else if (find_function(*argv))
  9929. type = "a function";
  9930. # endif
  9931. else if (find_builtin(*argv))
  9932. type = "a shell builtin";
  9933. else if ((path = find_in_path(*argv)) != NULL)
  9934. type = path;
  9935. else {
  9936. bb_error_msg("type: %s: not found", *argv);
  9937. ret = EXIT_FAILURE;
  9938. continue;
  9939. }
  9940. printf("%s is %s\n", *argv, type);
  9941. free(path);
  9942. }
  9943. return ret;
  9944. }
  9945. #endif
  9946. #if ENABLE_HUSH_READ
  9947. /* Interruptibility of read builtin in bash
  9948. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9949. *
  9950. * Empty trap makes read ignore corresponding signal, for any signal.
  9951. *
  9952. * SIGINT:
  9953. * - terminates non-interactive shell;
  9954. * - interrupts read in interactive shell;
  9955. * if it has non-empty trap:
  9956. * - executes trap and returns to command prompt in interactive shell;
  9957. * - executes trap and returns to read in non-interactive shell;
  9958. * SIGTERM:
  9959. * - is ignored (does not interrupt) read in interactive shell;
  9960. * - terminates non-interactive shell;
  9961. * if it has non-empty trap:
  9962. * - executes trap and returns to read;
  9963. * SIGHUP:
  9964. * - terminates shell (regardless of interactivity);
  9965. * if it has non-empty trap:
  9966. * - executes trap and returns to read;
  9967. * SIGCHLD from children:
  9968. * - does not interrupt read regardless of interactivity:
  9969. * try: sleep 1 & read x; echo $x
  9970. */
  9971. static int FAST_FUNC builtin_read(char **argv)
  9972. {
  9973. const char *r;
  9974. struct builtin_read_params params;
  9975. memset(&params, 0, sizeof(params));
  9976. /* "!": do not abort on errors.
  9977. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9978. */
  9979. params.read_flags = getopt32(argv,
  9980. # if BASH_READ_D
  9981. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9982. # else
  9983. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9984. # endif
  9985. );
  9986. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9987. return EXIT_FAILURE;
  9988. argv += optind;
  9989. params.argv = argv;
  9990. params.setvar = set_local_var_from_halves;
  9991. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9992. again:
  9993. r = shell_builtin_read(&params);
  9994. if ((uintptr_t)r == 1 && errno == EINTR) {
  9995. unsigned sig = check_and_run_traps();
  9996. if (sig != SIGINT)
  9997. goto again;
  9998. }
  9999. if ((uintptr_t)r > 1) {
  10000. bb_simple_error_msg(r);
  10001. r = (char*)(uintptr_t)1;
  10002. }
  10003. return (uintptr_t)r;
  10004. }
  10005. #endif
  10006. #if ENABLE_HUSH_UMASK
  10007. static int FAST_FUNC builtin_umask(char **argv)
  10008. {
  10009. int rc;
  10010. mode_t mask;
  10011. rc = 1;
  10012. mask = umask(0);
  10013. argv = skip_dash_dash(argv);
  10014. if (argv[0]) {
  10015. mode_t old_mask = mask;
  10016. /* numeric umasks are taken as-is */
  10017. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10018. if (!isdigit(argv[0][0]))
  10019. mask ^= 0777;
  10020. mask = bb_parse_mode(argv[0], mask);
  10021. if (!isdigit(argv[0][0]))
  10022. mask ^= 0777;
  10023. if ((unsigned)mask > 0777) {
  10024. mask = old_mask;
  10025. /* bash messages:
  10026. * bash: umask: 'q': invalid symbolic mode operator
  10027. * bash: umask: 999: octal number out of range
  10028. */
  10029. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10030. rc = 0;
  10031. }
  10032. } else {
  10033. /* Mimic bash */
  10034. printf("%04o\n", (unsigned) mask);
  10035. /* fall through and restore mask which we set to 0 */
  10036. }
  10037. umask(mask);
  10038. return !rc; /* rc != 0 - success */
  10039. }
  10040. #endif
  10041. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10042. static void print_escaped(const char *s)
  10043. {
  10044. if (*s == '\'')
  10045. goto squote;
  10046. do {
  10047. const char *p = strchrnul(s, '\'');
  10048. /* print 'xxxx', possibly just '' */
  10049. printf("'%.*s'", (int)(p - s), s);
  10050. if (*p == '\0')
  10051. break;
  10052. s = p;
  10053. squote:
  10054. /* s points to '; print "'''...'''" */
  10055. putchar('"');
  10056. do putchar('\''); while (*++s == '\'');
  10057. putchar('"');
  10058. } while (*s);
  10059. }
  10060. #endif
  10061. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10062. static int helper_export_local(char **argv, unsigned flags)
  10063. {
  10064. do {
  10065. char *name = *argv;
  10066. const char *name_end = endofname(name);
  10067. if (*name_end == '\0') {
  10068. struct variable *var, **vpp;
  10069. vpp = get_ptr_to_local_var(name, name_end - name);
  10070. var = vpp ? *vpp : NULL;
  10071. if (flags & SETFLAG_UNEXPORT) {
  10072. /* export -n NAME (without =VALUE) */
  10073. if (var) {
  10074. var->flg_export = 0;
  10075. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10076. unsetenv(name);
  10077. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10078. continue;
  10079. }
  10080. if (flags & SETFLAG_EXPORT) {
  10081. /* export NAME (without =VALUE) */
  10082. if (var) {
  10083. var->flg_export = 1;
  10084. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10085. putenv(var->varstr);
  10086. continue;
  10087. }
  10088. }
  10089. if (flags & SETFLAG_MAKE_RO) {
  10090. /* readonly NAME (without =VALUE) */
  10091. if (var) {
  10092. var->flg_read_only = 1;
  10093. continue;
  10094. }
  10095. }
  10096. # if ENABLE_HUSH_LOCAL
  10097. /* Is this "local" bltin? */
  10098. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10099. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10100. if (var && var->var_nest_level == lvl) {
  10101. /* "local x=abc; ...; local x" - ignore second local decl */
  10102. continue;
  10103. }
  10104. }
  10105. # endif
  10106. /* Exporting non-existing variable.
  10107. * bash does not put it in environment,
  10108. * but remembers that it is exported,
  10109. * and does put it in env when it is set later.
  10110. * We just set it to "" and export.
  10111. */
  10112. /* Or, it's "local NAME" (without =VALUE).
  10113. * bash sets the value to "".
  10114. */
  10115. /* Or, it's "readonly NAME" (without =VALUE).
  10116. * bash remembers NAME and disallows its creation
  10117. * in the future.
  10118. */
  10119. name = xasprintf("%s=", name);
  10120. } else {
  10121. if (*name_end != '=') {
  10122. bb_error_msg("'%s': bad variable name", name);
  10123. /* do not parse following argv[]s: */
  10124. return 1;
  10125. }
  10126. /* (Un)exporting/making local NAME=VALUE */
  10127. name = xstrdup(name);
  10128. /* Testcase: export PS1='\w \$ ' */
  10129. unbackslash(name);
  10130. }
  10131. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10132. if (set_local_var(name, flags))
  10133. return EXIT_FAILURE;
  10134. } while (*++argv);
  10135. return EXIT_SUCCESS;
  10136. }
  10137. #endif
  10138. #if ENABLE_HUSH_EXPORT
  10139. static int FAST_FUNC builtin_export(char **argv)
  10140. {
  10141. unsigned opt_unexport;
  10142. # if ENABLE_HUSH_EXPORT_N
  10143. /* "!": do not abort on errors */
  10144. opt_unexport = getopt32(argv, "!n");
  10145. if (opt_unexport == (uint32_t)-1)
  10146. return EXIT_FAILURE;
  10147. argv += optind;
  10148. # else
  10149. opt_unexport = 0;
  10150. argv++;
  10151. # endif
  10152. if (argv[0] == NULL) {
  10153. char **e = environ;
  10154. if (e) {
  10155. while (*e) {
  10156. # if 0
  10157. puts(*e++);
  10158. # else
  10159. /* ash emits: export VAR='VAL'
  10160. * bash: declare -x VAR="VAL"
  10161. * we follow ash example */
  10162. const char *s = *e++;
  10163. const char *p = strchr(s, '=');
  10164. if (!p) /* wtf? take next variable */
  10165. continue;
  10166. /* export var= */
  10167. printf("export %.*s", (int)(p - s) + 1, s);
  10168. print_escaped(p + 1);
  10169. putchar('\n');
  10170. # endif
  10171. }
  10172. /*fflush_all(); - done after each builtin anyway */
  10173. }
  10174. return EXIT_SUCCESS;
  10175. }
  10176. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10177. }
  10178. #endif
  10179. #if ENABLE_HUSH_LOCAL
  10180. static int FAST_FUNC builtin_local(char **argv)
  10181. {
  10182. if (G.func_nest_level == 0) {
  10183. bb_error_msg("%s: not in a function", argv[0]);
  10184. return EXIT_FAILURE; /* bash compat */
  10185. }
  10186. argv++;
  10187. /* Since all builtins run in a nested variable level,
  10188. * need to use level - 1 here. Or else the variable will be removed at once
  10189. * after builtin returns.
  10190. */
  10191. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10192. }
  10193. #endif
  10194. #if ENABLE_HUSH_READONLY
  10195. static int FAST_FUNC builtin_readonly(char **argv)
  10196. {
  10197. argv++;
  10198. if (*argv == NULL) {
  10199. /* bash: readonly [-p]: list all readonly VARs
  10200. * (-p has no effect in bash)
  10201. */
  10202. struct variable *e;
  10203. for (e = G.top_var; e; e = e->next) {
  10204. if (e->flg_read_only) {
  10205. //TODO: quote value: readonly VAR='VAL'
  10206. printf("readonly %s\n", e->varstr);
  10207. }
  10208. }
  10209. return EXIT_SUCCESS;
  10210. }
  10211. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10212. }
  10213. #endif
  10214. #if ENABLE_HUSH_UNSET
  10215. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10216. static int FAST_FUNC builtin_unset(char **argv)
  10217. {
  10218. int ret;
  10219. unsigned opts;
  10220. /* "!": do not abort on errors */
  10221. /* "+": stop at 1st non-option */
  10222. opts = getopt32(argv, "!+vf");
  10223. if (opts == (unsigned)-1)
  10224. return EXIT_FAILURE;
  10225. if (opts == 3) {
  10226. bb_simple_error_msg("unset: -v and -f are exclusive");
  10227. return EXIT_FAILURE;
  10228. }
  10229. argv += optind;
  10230. ret = EXIT_SUCCESS;
  10231. while (*argv) {
  10232. if (!(opts & 2)) { /* not -f */
  10233. if (unset_local_var(*argv)) {
  10234. /* unset <nonexistent_var> doesn't fail.
  10235. * Error is when one tries to unset RO var.
  10236. * Message was printed by unset_local_var. */
  10237. ret = EXIT_FAILURE;
  10238. }
  10239. }
  10240. # if ENABLE_HUSH_FUNCTIONS
  10241. else {
  10242. unset_func(*argv);
  10243. }
  10244. # endif
  10245. argv++;
  10246. }
  10247. return ret;
  10248. }
  10249. #endif
  10250. #if ENABLE_HUSH_SET
  10251. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10252. * built-in 'set' handler
  10253. * SUSv3 says:
  10254. * set [-abCefhmnuvx] [-o option] [argument...]
  10255. * set [+abCefhmnuvx] [+o option] [argument...]
  10256. * set -- [argument...]
  10257. * set -o
  10258. * set +o
  10259. * Implementations shall support the options in both their hyphen and
  10260. * plus-sign forms. These options can also be specified as options to sh.
  10261. * Examples:
  10262. * Write out all variables and their values: set
  10263. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10264. * Turn on the -x and -v options: set -xv
  10265. * Unset all positional parameters: set --
  10266. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10267. * Set the positional parameters to the expansion of x, even if x expands
  10268. * with a leading '-' or '+': set -- $x
  10269. *
  10270. * So far, we only support "set -- [argument...]" and some of the short names.
  10271. */
  10272. static int FAST_FUNC builtin_set(char **argv)
  10273. {
  10274. int n;
  10275. char **pp, **g_argv;
  10276. char *arg = *++argv;
  10277. if (arg == NULL) {
  10278. struct variable *e;
  10279. for (e = G.top_var; e; e = e->next)
  10280. puts(e->varstr);
  10281. return EXIT_SUCCESS;
  10282. }
  10283. do {
  10284. if (strcmp(arg, "--") == 0) {
  10285. ++argv;
  10286. goto set_argv;
  10287. }
  10288. if (arg[0] != '+' && arg[0] != '-')
  10289. break;
  10290. for (n = 1; arg[n]; ++n) {
  10291. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10292. bb_error_msg("%s: %s: invalid option", "set", arg);
  10293. return EXIT_FAILURE;
  10294. }
  10295. if (arg[n] == 'o' && argv[1])
  10296. argv++;
  10297. }
  10298. } while ((arg = *++argv) != NULL);
  10299. /* Now argv[0] is 1st argument */
  10300. if (arg == NULL)
  10301. return EXIT_SUCCESS;
  10302. set_argv:
  10303. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10304. g_argv = G.global_argv;
  10305. if (G.global_args_malloced) {
  10306. pp = g_argv;
  10307. while (*++pp)
  10308. free(*pp);
  10309. g_argv[1] = NULL;
  10310. } else {
  10311. G.global_args_malloced = 1;
  10312. pp = xzalloc(sizeof(pp[0]) * 2);
  10313. pp[0] = g_argv[0]; /* retain $0 */
  10314. g_argv = pp;
  10315. }
  10316. /* This realloc's G.global_argv */
  10317. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10318. G.global_argc = 1 + string_array_len(pp + 1);
  10319. return EXIT_SUCCESS;
  10320. }
  10321. #endif
  10322. static int FAST_FUNC builtin_shift(char **argv)
  10323. {
  10324. int n = 1;
  10325. argv = skip_dash_dash(argv);
  10326. if (argv[0]) {
  10327. n = bb_strtou(argv[0], NULL, 10);
  10328. if (errno || n < 0) {
  10329. /* shared string with ash.c */
  10330. bb_error_msg("Illegal number: %s", argv[0]);
  10331. /*
  10332. * ash aborts in this case.
  10333. * bash prints error message and set $? to 1.
  10334. * Interestingly, for "shift 99999" bash does not
  10335. * print error message, but does set $? to 1
  10336. * (and does no shifting at all).
  10337. */
  10338. }
  10339. }
  10340. if (n >= 0 && n < G.global_argc) {
  10341. if (G_global_args_malloced) {
  10342. int m = 1;
  10343. while (m <= n)
  10344. free(G.global_argv[m++]);
  10345. }
  10346. G.global_argc -= n;
  10347. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10348. G.global_argc * sizeof(G.global_argv[0]));
  10349. return EXIT_SUCCESS;
  10350. }
  10351. return EXIT_FAILURE;
  10352. }
  10353. #if ENABLE_HUSH_GETOPTS
  10354. static int FAST_FUNC builtin_getopts(char **argv)
  10355. {
  10356. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10357. TODO:
  10358. If a required argument is not found, and getopts is not silent,
  10359. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10360. diagnostic message is printed. If getopts is silent, then a
  10361. colon (:) is placed in VAR and OPTARG is set to the option
  10362. character found.
  10363. Test that VAR is a valid variable name?
  10364. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10365. */
  10366. char cbuf[2];
  10367. const char *cp, *optstring, *var;
  10368. int c, n, exitcode, my_opterr;
  10369. unsigned count;
  10370. optstring = *++argv;
  10371. if (!optstring || !(var = *++argv)) {
  10372. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10373. return EXIT_FAILURE;
  10374. }
  10375. if (argv[1])
  10376. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10377. else
  10378. argv = G.global_argv;
  10379. cbuf[1] = '\0';
  10380. my_opterr = 0;
  10381. if (optstring[0] != ':') {
  10382. cp = get_local_var_value("OPTERR");
  10383. /* 0 if "OPTERR=0", 1 otherwise */
  10384. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10385. }
  10386. /* getopts stops on first non-option. Add "+" to force that */
  10387. /*if (optstring[0] != '+')*/ {
  10388. char *s = alloca(strlen(optstring) + 2);
  10389. sprintf(s, "+%s", optstring);
  10390. optstring = s;
  10391. }
  10392. /* Naively, now we should just
  10393. * cp = get_local_var_value("OPTIND");
  10394. * optind = cp ? atoi(cp) : 0;
  10395. * optarg = NULL;
  10396. * opterr = my_opterr;
  10397. * c = getopt(string_array_len(argv), argv, optstring);
  10398. * and be done? Not so fast...
  10399. * Unlike normal getopt() usage in C programs, here
  10400. * each successive call will (usually) have the same argv[] CONTENTS,
  10401. * but not the ADDRESSES. Worse yet, it's possible that between
  10402. * invocations of "getopts", there will be calls to shell builtins
  10403. * which use getopt() internally. Example:
  10404. * while getopts "abc" RES -a -bc -abc de; do
  10405. * unset -ff func
  10406. * done
  10407. * This would not work correctly: getopt() call inside "unset"
  10408. * modifies internal libc state which is tracking position in
  10409. * multi-option strings ("-abc"). At best, it can skip options
  10410. * or return the same option infinitely. With glibc implementation
  10411. * of getopt(), it would use outright invalid pointers and return
  10412. * garbage even _without_ "unset" mangling internal state.
  10413. *
  10414. * We resort to resetting getopt() state and calling it N times,
  10415. * until we get Nth result (or failure).
  10416. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10417. */
  10418. GETOPT_RESET();
  10419. count = 0;
  10420. n = string_array_len(argv);
  10421. do {
  10422. optarg = NULL;
  10423. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10424. c = getopt(n, argv, optstring);
  10425. if (c < 0)
  10426. break;
  10427. count++;
  10428. } while (count <= G.getopt_count);
  10429. /* Set OPTIND. Prevent resetting of the magic counter! */
  10430. set_local_var_from_halves("OPTIND", utoa(optind));
  10431. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10432. GETOPT_RESET(); /* just in case */
  10433. /* Set OPTARG */
  10434. /* Always set or unset, never left as-is, even on exit/error:
  10435. * "If no option was found, or if the option that was found
  10436. * does not have an option-argument, OPTARG shall be unset."
  10437. */
  10438. cp = optarg;
  10439. if (c == '?') {
  10440. /* If ":optstring" and unknown option is seen,
  10441. * it is stored to OPTARG.
  10442. */
  10443. if (optstring[1] == ':') {
  10444. cbuf[0] = optopt;
  10445. cp = cbuf;
  10446. }
  10447. }
  10448. if (cp)
  10449. set_local_var_from_halves("OPTARG", cp);
  10450. else
  10451. unset_local_var("OPTARG");
  10452. /* Convert -1 to "?" */
  10453. exitcode = EXIT_SUCCESS;
  10454. if (c < 0) { /* -1: end of options */
  10455. exitcode = EXIT_FAILURE;
  10456. c = '?';
  10457. }
  10458. /* Set VAR */
  10459. cbuf[0] = c;
  10460. set_local_var_from_halves(var, cbuf);
  10461. return exitcode;
  10462. }
  10463. #endif
  10464. static int FAST_FUNC builtin_source(char **argv)
  10465. {
  10466. char *arg_path, *filename;
  10467. HFILE *input;
  10468. save_arg_t sv;
  10469. char *args_need_save;
  10470. #if ENABLE_HUSH_FUNCTIONS
  10471. smallint sv_flg;
  10472. #endif
  10473. argv = skip_dash_dash(argv);
  10474. filename = argv[0];
  10475. if (!filename) {
  10476. /* bash says: "bash: .: filename argument required" */
  10477. return 2; /* bash compat */
  10478. }
  10479. arg_path = NULL;
  10480. if (!strchr(filename, '/')) {
  10481. arg_path = find_in_path(filename);
  10482. if (arg_path)
  10483. filename = arg_path;
  10484. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10485. errno = ENOENT;
  10486. bb_simple_perror_msg(filename);
  10487. return EXIT_FAILURE;
  10488. }
  10489. }
  10490. input = hfopen(filename);
  10491. free(arg_path);
  10492. if (!input) {
  10493. bb_perror_msg("%s", filename);
  10494. /* POSIX: non-interactive shell should abort here,
  10495. * not merely fail. So far no one complained :)
  10496. */
  10497. return EXIT_FAILURE;
  10498. }
  10499. #if ENABLE_HUSH_FUNCTIONS
  10500. sv_flg = G_flag_return_in_progress;
  10501. /* "we are inside sourced file, ok to use return" */
  10502. G_flag_return_in_progress = -1;
  10503. #endif
  10504. args_need_save = argv[1]; /* used as a boolean variable */
  10505. if (args_need_save)
  10506. save_and_replace_G_args(&sv, argv);
  10507. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10508. G.last_exitcode = 0;
  10509. parse_and_run_file(input);
  10510. hfclose(input);
  10511. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10512. restore_G_args(&sv, argv);
  10513. #if ENABLE_HUSH_FUNCTIONS
  10514. G_flag_return_in_progress = sv_flg;
  10515. #endif
  10516. return G.last_exitcode;
  10517. }
  10518. #if ENABLE_HUSH_TRAP
  10519. static int FAST_FUNC builtin_trap(char **argv)
  10520. {
  10521. int sig;
  10522. char *new_cmd;
  10523. if (!G_traps)
  10524. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10525. argv++;
  10526. if (!*argv) {
  10527. int i;
  10528. /* No args: print all trapped */
  10529. for (i = 0; i < NSIG; ++i) {
  10530. if (G_traps[i]) {
  10531. printf("trap -- ");
  10532. print_escaped(G_traps[i]);
  10533. /* note: bash adds "SIG", but only if invoked
  10534. * as "bash". If called as "sh", or if set -o posix,
  10535. * then it prints short signal names.
  10536. * We are printing short names: */
  10537. printf(" %s\n", get_signame(i));
  10538. }
  10539. }
  10540. /*fflush_all(); - done after each builtin anyway */
  10541. return EXIT_SUCCESS;
  10542. }
  10543. new_cmd = NULL;
  10544. /* If first arg is a number: reset all specified signals */
  10545. sig = bb_strtou(*argv, NULL, 10);
  10546. if (errno == 0) {
  10547. int ret;
  10548. process_sig_list:
  10549. ret = EXIT_SUCCESS;
  10550. while (*argv) {
  10551. sighandler_t handler;
  10552. sig = get_signum(*argv++);
  10553. if (sig < 0) {
  10554. ret = EXIT_FAILURE;
  10555. /* Mimic bash message exactly */
  10556. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10557. continue;
  10558. }
  10559. free(G_traps[sig]);
  10560. G_traps[sig] = xstrdup(new_cmd);
  10561. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10562. get_signame(sig), sig, G_traps[sig]);
  10563. /* There is no signal for 0 (EXIT) */
  10564. if (sig == 0)
  10565. continue;
  10566. if (new_cmd)
  10567. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10568. else
  10569. /* We are removing trap handler */
  10570. handler = pick_sighandler(sig);
  10571. install_sighandler(sig, handler);
  10572. }
  10573. return ret;
  10574. }
  10575. if (!argv[1]) { /* no second arg */
  10576. bb_simple_error_msg("trap: invalid arguments");
  10577. return EXIT_FAILURE;
  10578. }
  10579. /* First arg is "-": reset all specified to default */
  10580. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10581. /* Everything else: set arg as signal handler
  10582. * (includes "" case, which ignores signal) */
  10583. if (argv[0][0] == '-') {
  10584. if (argv[0][1] == '\0') { /* "-" */
  10585. /* new_cmd remains NULL: "reset these sigs" */
  10586. goto reset_traps;
  10587. }
  10588. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10589. argv++;
  10590. }
  10591. /* else: "-something", no special meaning */
  10592. }
  10593. new_cmd = *argv;
  10594. reset_traps:
  10595. argv++;
  10596. goto process_sig_list;
  10597. }
  10598. #endif
  10599. #if ENABLE_HUSH_JOB
  10600. static struct pipe *parse_jobspec(const char *str)
  10601. {
  10602. struct pipe *pi;
  10603. unsigned jobnum;
  10604. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10605. if (str[0] != '%'
  10606. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10607. ) {
  10608. bb_error_msg("bad argument '%s'", str);
  10609. return NULL;
  10610. }
  10611. /* It is "%%", "%+" or "%" - current job */
  10612. jobnum = G.last_jobid;
  10613. if (jobnum == 0) {
  10614. bb_simple_error_msg("no current job");
  10615. return NULL;
  10616. }
  10617. }
  10618. for (pi = G.job_list; pi; pi = pi->next) {
  10619. if (pi->jobid == jobnum) {
  10620. return pi;
  10621. }
  10622. }
  10623. bb_error_msg("%u: no such job", jobnum);
  10624. return NULL;
  10625. }
  10626. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10627. {
  10628. struct pipe *job;
  10629. const char *status_string;
  10630. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10631. for (job = G.job_list; job; job = job->next) {
  10632. if (job->alive_cmds == job->stopped_cmds)
  10633. status_string = "Stopped";
  10634. else
  10635. status_string = "Running";
  10636. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10637. }
  10638. clean_up_last_dead_job();
  10639. return EXIT_SUCCESS;
  10640. }
  10641. /* built-in 'fg' and 'bg' handler */
  10642. static int FAST_FUNC builtin_fg_bg(char **argv)
  10643. {
  10644. int i;
  10645. struct pipe *pi;
  10646. if (!G_interactive_fd)
  10647. return EXIT_FAILURE;
  10648. /* If they gave us no args, assume they want the last backgrounded task */
  10649. if (!argv[1]) {
  10650. for (pi = G.job_list; pi; pi = pi->next) {
  10651. if (pi->jobid == G.last_jobid) {
  10652. goto found;
  10653. }
  10654. }
  10655. bb_error_msg("%s: no current job", argv[0]);
  10656. return EXIT_FAILURE;
  10657. }
  10658. pi = parse_jobspec(argv[1]);
  10659. if (!pi)
  10660. return EXIT_FAILURE;
  10661. found:
  10662. /* TODO: bash prints a string representation
  10663. * of job being foregrounded (like "sleep 1 | cat") */
  10664. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10665. /* Put the job into the foreground. */
  10666. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10667. }
  10668. /* Restart the processes in the job */
  10669. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10670. for (i = 0; i < pi->num_cmds; i++) {
  10671. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10672. }
  10673. pi->stopped_cmds = 0;
  10674. i = kill(- pi->pgrp, SIGCONT);
  10675. if (i < 0) {
  10676. if (errno == ESRCH) {
  10677. delete_finished_job(pi);
  10678. return EXIT_SUCCESS;
  10679. }
  10680. bb_simple_perror_msg("kill (SIGCONT)");
  10681. }
  10682. if (argv[0][0] == 'f') {
  10683. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10684. return checkjobs_and_fg_shell(pi);
  10685. }
  10686. return EXIT_SUCCESS;
  10687. }
  10688. #endif
  10689. #if ENABLE_HUSH_KILL
  10690. static int FAST_FUNC builtin_kill(char **argv)
  10691. {
  10692. int ret = 0;
  10693. # if ENABLE_HUSH_JOB
  10694. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10695. int i = 1;
  10696. do {
  10697. struct pipe *pi;
  10698. char *dst;
  10699. int j, n;
  10700. if (argv[i][0] != '%')
  10701. continue;
  10702. /*
  10703. * "kill %N" - job kill
  10704. * Converting to pgrp / pid kill
  10705. */
  10706. pi = parse_jobspec(argv[i]);
  10707. if (!pi) {
  10708. /* Eat bad jobspec */
  10709. j = i;
  10710. do {
  10711. j++;
  10712. argv[j - 1] = argv[j];
  10713. } while (argv[j]);
  10714. ret = 1;
  10715. i--;
  10716. continue;
  10717. }
  10718. /*
  10719. * In jobs started under job control, we signal
  10720. * entire process group by kill -PGRP_ID.
  10721. * This happens, f.e., in interactive shell.
  10722. *
  10723. * Otherwise, we signal each child via
  10724. * kill PID1 PID2 PID3.
  10725. * Testcases:
  10726. * sh -c 'sleep 1|sleep 1 & kill %1'
  10727. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10728. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10729. */
  10730. n = G_interactive_fd ? 1 : pi->num_cmds;
  10731. dst = alloca(n * sizeof(int)*4);
  10732. argv[i] = dst;
  10733. if (G_interactive_fd)
  10734. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10735. else for (j = 0; j < n; j++) {
  10736. struct command *cmd = &pi->cmds[j];
  10737. /* Skip exited members of the job */
  10738. if (cmd->pid == 0)
  10739. continue;
  10740. /*
  10741. * kill_main has matching code to expect
  10742. * leading space. Needed to not confuse
  10743. * negative pids with "kill -SIGNAL_NO" syntax
  10744. */
  10745. dst += sprintf(dst, " %u", (int)cmd->pid);
  10746. }
  10747. *dst = '\0';
  10748. } while (argv[++i]);
  10749. }
  10750. # endif
  10751. if (argv[1] || ret == 0) {
  10752. ret = run_applet_main(argv, kill_main);
  10753. }
  10754. /* else: ret = 1, "kill %bad_jobspec" case */
  10755. return ret;
  10756. }
  10757. #endif
  10758. #if ENABLE_HUSH_WAIT
  10759. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10760. # if !ENABLE_HUSH_JOB
  10761. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10762. # endif
  10763. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10764. {
  10765. int ret = 0;
  10766. for (;;) {
  10767. int sig;
  10768. sigset_t oldset;
  10769. if (!sigisemptyset(&G.pending_set))
  10770. goto check_sig;
  10771. /* waitpid is not interruptible by SA_RESTARTed
  10772. * signals which we use. Thus, this ugly dance:
  10773. */
  10774. /* Make sure possible SIGCHLD is stored in kernel's
  10775. * pending signal mask before we call waitpid.
  10776. * Or else we may race with SIGCHLD, lose it,
  10777. * and get stuck in sigsuspend...
  10778. */
  10779. sigfillset(&oldset); /* block all signals, remember old set */
  10780. sigprocmask2(SIG_SETMASK, &oldset);
  10781. if (!sigisemptyset(&G.pending_set)) {
  10782. /* Crap! we raced with some signal! */
  10783. goto restore;
  10784. }
  10785. /*errno = 0; - checkjobs does this */
  10786. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10787. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10788. debug_printf_exec("checkjobs:%d\n", ret);
  10789. # if ENABLE_HUSH_JOB
  10790. if (waitfor_pipe) {
  10791. int rcode = job_exited_or_stopped(waitfor_pipe);
  10792. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10793. if (rcode >= 0) {
  10794. ret = rcode;
  10795. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10796. break;
  10797. }
  10798. }
  10799. # endif
  10800. /* if ECHILD, there are no children (ret is -1 or 0) */
  10801. /* if ret == 0, no children changed state */
  10802. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10803. if (errno == ECHILD || ret) {
  10804. ret--;
  10805. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10806. ret = 0;
  10807. # if ENABLE_HUSH_BASH_COMPAT
  10808. if (waitfor_pid == -1 && errno == ECHILD) {
  10809. /* exitcode of "wait -n" with no children is 127, not 0 */
  10810. ret = 127;
  10811. }
  10812. # endif
  10813. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10814. break;
  10815. }
  10816. /* Wait for SIGCHLD or any other signal */
  10817. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10818. /* Note: sigsuspend invokes signal handler */
  10819. sigsuspend(&oldset);
  10820. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  10821. * to make sure SIGCHLD is not masked off?
  10822. * It was reported that this:
  10823. * fn() { : | return; }
  10824. * shopt -s lastpipe
  10825. * fn
  10826. * exec hush SCRIPT
  10827. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  10828. * making "wait" commands in SCRIPT block forever.
  10829. */
  10830. restore:
  10831. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10832. check_sig:
  10833. /* So, did we get a signal? */
  10834. sig = check_and_run_traps();
  10835. if (sig /*&& sig != SIGCHLD - always true */) {
  10836. /* Do this for any (non-ignored) signal, not only for ^C */
  10837. ret = 128 + sig;
  10838. break;
  10839. }
  10840. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10841. }
  10842. return ret;
  10843. }
  10844. static int FAST_FUNC builtin_wait(char **argv)
  10845. {
  10846. int ret;
  10847. int status;
  10848. argv = skip_dash_dash(argv);
  10849. # if ENABLE_HUSH_BASH_COMPAT
  10850. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10851. /* wait -n */
  10852. /* (bash accepts "wait -n PID" too and ignores PID) */
  10853. G.dead_job_exitcode = -1;
  10854. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10855. }
  10856. # endif
  10857. if (argv[0] == NULL) {
  10858. /* Don't care about wait results */
  10859. /* Note 1: must wait until there are no more children */
  10860. /* Note 2: must be interruptible */
  10861. /* Examples:
  10862. * $ sleep 3 & sleep 6 & wait
  10863. * [1] 30934 sleep 3
  10864. * [2] 30935 sleep 6
  10865. * [1] Done sleep 3
  10866. * [2] Done sleep 6
  10867. * $ sleep 3 & sleep 6 & wait
  10868. * [1] 30936 sleep 3
  10869. * [2] 30937 sleep 6
  10870. * [1] Done sleep 3
  10871. * ^C <-- after ~4 sec from keyboard
  10872. * $
  10873. */
  10874. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10875. }
  10876. do {
  10877. pid_t pid = bb_strtou(*argv, NULL, 10);
  10878. if (errno || pid <= 0) {
  10879. # if ENABLE_HUSH_JOB
  10880. if (argv[0][0] == '%') {
  10881. struct pipe *wait_pipe;
  10882. ret = 127; /* bash compat for bad jobspecs */
  10883. wait_pipe = parse_jobspec(*argv);
  10884. if (wait_pipe) {
  10885. ret = job_exited_or_stopped(wait_pipe);
  10886. if (ret < 0) {
  10887. ret = wait_for_child_or_signal(wait_pipe, 0);
  10888. } else {
  10889. /* waiting on "last dead job" removes it */
  10890. clean_up_last_dead_job();
  10891. }
  10892. }
  10893. /* else: parse_jobspec() already emitted error msg */
  10894. continue;
  10895. }
  10896. # endif
  10897. /* mimic bash message */
  10898. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10899. ret = EXIT_FAILURE;
  10900. continue; /* bash checks all argv[] */
  10901. }
  10902. /* Do we have such child? */
  10903. ret = waitpid(pid, &status, WNOHANG);
  10904. if (ret < 0) {
  10905. /* No */
  10906. ret = 127;
  10907. if (errno == ECHILD) {
  10908. if (pid == G.last_bg_pid) {
  10909. /* "wait $!" but last bg task has already exited. Try:
  10910. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10911. * In bash it prints exitcode 0, then 3.
  10912. * In dash, it is 127.
  10913. */
  10914. ret = G.last_bg_pid_exitcode;
  10915. } else {
  10916. /* Example: "wait 1". mimic bash message */
  10917. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  10918. }
  10919. } else {
  10920. /* ??? */
  10921. bb_perror_msg("wait %s", *argv);
  10922. }
  10923. continue; /* bash checks all argv[] */
  10924. }
  10925. if (ret == 0) {
  10926. /* Yes, and it still runs */
  10927. ret = wait_for_child_or_signal(NULL, pid);
  10928. } else {
  10929. /* Yes, and it just exited */
  10930. process_wait_result(NULL, pid, status);
  10931. ret = WEXITSTATUS(status);
  10932. if (WIFSIGNALED(status))
  10933. ret = 128 + WTERMSIG(status);
  10934. }
  10935. } while (*++argv);
  10936. return ret;
  10937. }
  10938. #endif
  10939. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10940. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10941. {
  10942. if (argv[1]) {
  10943. def = bb_strtou(argv[1], NULL, 10);
  10944. if (errno || def < def_min || argv[2]) {
  10945. bb_error_msg("%s: bad arguments", argv[0]);
  10946. def = UINT_MAX;
  10947. }
  10948. }
  10949. return def;
  10950. }
  10951. #endif
  10952. #if ENABLE_HUSH_LOOPS
  10953. static int FAST_FUNC builtin_break(char **argv)
  10954. {
  10955. unsigned depth;
  10956. if (G.depth_of_loop == 0) {
  10957. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10958. /* if we came from builtin_continue(), need to undo "= 1" */
  10959. G.flag_break_continue = 0;
  10960. return EXIT_SUCCESS; /* bash compat */
  10961. }
  10962. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10963. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10964. if (depth == UINT_MAX)
  10965. G.flag_break_continue = BC_BREAK;
  10966. if (G.depth_of_loop < depth)
  10967. G.depth_break_continue = G.depth_of_loop;
  10968. return EXIT_SUCCESS;
  10969. }
  10970. static int FAST_FUNC builtin_continue(char **argv)
  10971. {
  10972. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10973. return builtin_break(argv);
  10974. }
  10975. #endif
  10976. #if ENABLE_HUSH_FUNCTIONS
  10977. static int FAST_FUNC builtin_return(char **argv)
  10978. {
  10979. int rc;
  10980. if (G_flag_return_in_progress != -1) {
  10981. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10982. return EXIT_FAILURE; /* bash compat */
  10983. }
  10984. G_flag_return_in_progress = 1;
  10985. /* bash:
  10986. * out of range: wraps around at 256, does not error out
  10987. * non-numeric param:
  10988. * f() { false; return qwe; }; f; echo $?
  10989. * bash: return: qwe: numeric argument required <== we do this
  10990. * 255 <== we also do this
  10991. */
  10992. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10993. # if ENABLE_HUSH_TRAP
  10994. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  10995. debug_printf_exec("G.return_exitcode=%d\n", rc);
  10996. G.return_exitcode = rc;
  10997. }
  10998. # endif
  10999. return rc;
  11000. }
  11001. #endif
  11002. #if ENABLE_HUSH_TIMES
  11003. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11004. {
  11005. static const uint8_t times_tbl[] ALIGN1 = {
  11006. ' ', offsetof(struct tms, tms_utime),
  11007. '\n', offsetof(struct tms, tms_stime),
  11008. ' ', offsetof(struct tms, tms_cutime),
  11009. '\n', offsetof(struct tms, tms_cstime),
  11010. 0
  11011. };
  11012. const uint8_t *p;
  11013. unsigned clk_tck;
  11014. struct tms buf;
  11015. clk_tck = bb_clk_tck();
  11016. times(&buf);
  11017. p = times_tbl;
  11018. do {
  11019. unsigned sec, frac;
  11020. unsigned long t;
  11021. t = *(clock_t *)(((char *) &buf) + p[1]);
  11022. sec = t / clk_tck;
  11023. frac = t % clk_tck;
  11024. printf("%um%u.%03us%c",
  11025. sec / 60, sec % 60,
  11026. (frac * 1000) / clk_tck,
  11027. p[0]);
  11028. p += 2;
  11029. } while (*p);
  11030. return EXIT_SUCCESS;
  11031. }
  11032. #endif
  11033. #if ENABLE_HUSH_MEMLEAK
  11034. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11035. {
  11036. void *p;
  11037. unsigned long l;
  11038. # ifdef M_TRIM_THRESHOLD
  11039. /* Optional. Reduces probability of false positives */
  11040. malloc_trim(0);
  11041. # endif
  11042. /* Crude attempt to find where "free memory" starts,
  11043. * sans fragmentation. */
  11044. p = malloc(240);
  11045. l = (unsigned long)p;
  11046. free(p);
  11047. p = malloc(3400);
  11048. if (l < (unsigned long)p) l = (unsigned long)p;
  11049. free(p);
  11050. # if 0 /* debug */
  11051. {
  11052. struct mallinfo mi = mallinfo();
  11053. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11054. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11055. }
  11056. # endif
  11057. if (!G.memleak_value)
  11058. G.memleak_value = l;
  11059. l -= G.memleak_value;
  11060. if ((long)l < 0)
  11061. l = 0;
  11062. l /= 1024;
  11063. if (l > 127)
  11064. l = 127;
  11065. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11066. return l;
  11067. }
  11068. #endif