3
0

hush.c 323 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (68 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support command substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef O_CLOEXEC
  356. # define O_CLOEXEC 0
  357. #endif
  358. #ifndef F_DUPFD_CLOEXEC
  359. # define F_DUPFD_CLOEXEC F_DUPFD
  360. #endif
  361. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  362. # include "embedded_scripts.h"
  363. #else
  364. # define NUM_SCRIPTS 0
  365. #endif
  366. /* So far, all bash compat is controlled by one config option */
  367. /* Separate defines document which part of code implements what */
  368. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  369. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  370. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  371. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  372. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  373. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  374. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  375. /* Build knobs */
  376. #define LEAK_HUNTING 0
  377. #define BUILD_AS_NOMMU 0
  378. /* Enable/disable sanity checks. Ok to enable in production,
  379. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  380. * Keeping 1 for now even in released versions.
  381. */
  382. #define HUSH_DEBUG 1
  383. /* Slightly bigger (+200 bytes), but faster hush.
  384. * So far it only enables a trick with counting SIGCHLDs and forks,
  385. * which allows us to do fewer waitpid's.
  386. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  387. * and therefore waitpid will return the same result as last time)
  388. */
  389. #define ENABLE_HUSH_FAST 0
  390. /* TODO: implement simplified code for users which do not need ${var%...} ops
  391. * So far ${var%...} ops are always enabled:
  392. */
  393. #define ENABLE_HUSH_DOLLAR_OPS 1
  394. #if BUILD_AS_NOMMU
  395. # undef BB_MMU
  396. # undef USE_FOR_NOMMU
  397. # undef USE_FOR_MMU
  398. # define BB_MMU 0
  399. # define USE_FOR_NOMMU(...) __VA_ARGS__
  400. # define USE_FOR_MMU(...)
  401. #endif
  402. #include "NUM_APPLETS.h"
  403. #if NUM_APPLETS == 1
  404. /* STANDALONE does not make sense, and won't compile */
  405. # undef CONFIG_FEATURE_SH_STANDALONE
  406. # undef ENABLE_FEATURE_SH_STANDALONE
  407. # undef IF_FEATURE_SH_STANDALONE
  408. # undef IF_NOT_FEATURE_SH_STANDALONE
  409. # define ENABLE_FEATURE_SH_STANDALONE 0
  410. # define IF_FEATURE_SH_STANDALONE(...)
  411. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  412. #endif
  413. #if !ENABLE_HUSH_INTERACTIVE
  414. # undef ENABLE_FEATURE_EDITING
  415. # define ENABLE_FEATURE_EDITING 0
  416. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  417. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  418. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  419. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  420. #endif
  421. /* Do we support ANY keywords? */
  422. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  423. # define HAS_KEYWORDS 1
  424. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  425. # define IF_HAS_NO_KEYWORDS(...)
  426. #else
  427. # define HAS_KEYWORDS 0
  428. # define IF_HAS_KEYWORDS(...)
  429. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  430. #endif
  431. /* If you comment out one of these below, it will be #defined later
  432. * to perform debug printfs to stderr: */
  433. #define debug_printf(...) do {} while (0)
  434. /* Finer-grained debug switches */
  435. #define debug_printf_parse(...) do {} while (0)
  436. #define debug_printf_heredoc(...) do {} while (0)
  437. #define debug_print_tree(a, b) do {} while (0)
  438. #define debug_printf_exec(...) do {} while (0)
  439. #define debug_printf_env(...) do {} while (0)
  440. #define debug_printf_jobs(...) do {} while (0)
  441. #define debug_printf_expand(...) do {} while (0)
  442. #define debug_printf_varexp(...) do {} while (0)
  443. #define debug_printf_glob(...) do {} while (0)
  444. #define debug_printf_redir(...) do {} while (0)
  445. #define debug_printf_list(...) do {} while (0)
  446. #define debug_printf_subst(...) do {} while (0)
  447. #define debug_printf_prompt(...) do {} while (0)
  448. #define debug_printf_clean(...) do {} while (0)
  449. #define ERR_PTR ((void*)(long)1)
  450. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  451. #define _SPECIAL_VARS_STR "_*@$!?#-"
  452. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  453. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  454. #if BASH_PATTERN_SUBST
  455. /* Support / and // replace ops */
  456. /* Note that // is stored as \ in "encoded" string representation */
  457. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  458. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  459. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  460. #else
  461. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  462. # define VAR_SUBST_OPS "%#:-=+?"
  463. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  464. #endif
  465. #define SPECIAL_VAR_SYMBOL_STR "\3"
  466. #define SPECIAL_VAR_SYMBOL 3
  467. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  468. #define SPECIAL_VAR_QUOTED_SVS 1
  469. struct variable;
  470. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  471. /* This supports saving pointers malloced in vfork child,
  472. * to be freed in the parent.
  473. */
  474. #if !BB_MMU
  475. typedef struct nommu_save_t {
  476. struct variable *old_vars;
  477. char **argv;
  478. char **argv_from_re_execing;
  479. } nommu_save_t;
  480. #endif
  481. enum {
  482. RES_NONE = 0,
  483. #if ENABLE_HUSH_IF
  484. RES_IF ,
  485. RES_THEN ,
  486. RES_ELIF ,
  487. RES_ELSE ,
  488. RES_FI ,
  489. #endif
  490. #if ENABLE_HUSH_LOOPS
  491. RES_FOR ,
  492. RES_WHILE ,
  493. RES_UNTIL ,
  494. RES_DO ,
  495. RES_DONE ,
  496. #endif
  497. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  498. RES_IN ,
  499. #endif
  500. #if ENABLE_HUSH_CASE
  501. RES_CASE ,
  502. /* three pseudo-keywords support contrived "case" syntax: */
  503. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  504. RES_MATCH , /* "word)" */
  505. RES_CASE_BODY, /* "this command is inside CASE" */
  506. RES_ESAC ,
  507. #endif
  508. RES_XXXX ,
  509. RES_SNTX
  510. };
  511. typedef struct o_string {
  512. char *data;
  513. int length; /* position where data is appended */
  514. int maxlen;
  515. int o_expflags;
  516. /* At least some part of the string was inside '' or "",
  517. * possibly empty one: word"", wo''rd etc. */
  518. smallint has_quoted_part;
  519. smallint has_empty_slot;
  520. smallint ended_in_ifs;
  521. } o_string;
  522. enum {
  523. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  524. EXP_FLAG_GLOB = 0x2,
  525. /* Protect newly added chars against globbing
  526. * by prepending \ to *, ?, [, \ */
  527. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  528. };
  529. /* Used for initialization: o_string foo = NULL_O_STRING; */
  530. #define NULL_O_STRING { NULL }
  531. #ifndef debug_printf_parse
  532. static const char *const assignment_flag[] = {
  533. "MAYBE_ASSIGNMENT",
  534. "DEFINITELY_ASSIGNMENT",
  535. "NOT_ASSIGNMENT",
  536. "WORD_IS_KEYWORD",
  537. };
  538. #endif
  539. /* We almost can use standard FILE api, but we need an ability to move
  540. * its fd when redirects coincide with it. No api exists for that
  541. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  542. * HFILE is our internal alternative. Only supports reading.
  543. * Since we now can, we incorporate linked list of all opened HFILEs
  544. * into the struct (used to be a separate mini-list).
  545. */
  546. typedef struct HFILE {
  547. char *cur;
  548. char *end;
  549. struct HFILE *next_hfile;
  550. int is_stdin;
  551. int fd;
  552. char buf[1024];
  553. } HFILE;
  554. typedef struct in_str {
  555. const char *p;
  556. int peek_buf[2];
  557. int last_char;
  558. HFILE *file;
  559. } in_str;
  560. /* The descrip member of this structure is only used to make
  561. * debugging output pretty */
  562. static const struct {
  563. int mode;
  564. signed char default_fd;
  565. char descrip[3];
  566. } redir_table[] = {
  567. { O_RDONLY, 0, "<" },
  568. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  569. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  570. { O_CREAT|O_RDWR, 1, "<>" },
  571. { O_RDONLY, 0, "<<" },
  572. /* Should not be needed. Bogus default_fd helps in debugging */
  573. /* { O_RDONLY, 77, "<<" }, */
  574. };
  575. struct redir_struct {
  576. struct redir_struct *next;
  577. char *rd_filename; /* filename */
  578. int rd_fd; /* fd to redirect */
  579. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  580. int rd_dup;
  581. smallint rd_type; /* (enum redir_type) */
  582. /* note: for heredocs, rd_filename contains heredoc delimiter,
  583. * and subsequently heredoc itself; and rd_dup is a bitmask:
  584. * bit 0: do we need to trim leading tabs?
  585. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  586. */
  587. };
  588. typedef enum redir_type {
  589. REDIRECT_INPUT = 0,
  590. REDIRECT_OVERWRITE = 1,
  591. REDIRECT_APPEND = 2,
  592. REDIRECT_IO = 3,
  593. REDIRECT_HEREDOC = 4,
  594. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  595. REDIRFD_CLOSE = -3,
  596. REDIRFD_SYNTAX_ERR = -2,
  597. REDIRFD_TO_FILE = -1,
  598. /* otherwise, rd_fd is redirected to rd_dup */
  599. HEREDOC_SKIPTABS = 1,
  600. HEREDOC_QUOTED = 2,
  601. } redir_type;
  602. struct command {
  603. pid_t pid; /* 0 if exited */
  604. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  605. #if ENABLE_HUSH_LINENO_VAR
  606. unsigned lineno;
  607. #endif
  608. smallint cmd_type; /* CMD_xxx */
  609. #define CMD_NORMAL 0
  610. #define CMD_SUBSHELL 1
  611. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  612. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  613. * "export v=t*"
  614. */
  615. # define CMD_SINGLEWORD_NOGLOB 2
  616. #endif
  617. #if ENABLE_HUSH_FUNCTIONS
  618. # define CMD_FUNCDEF 3
  619. #endif
  620. smalluint cmd_exitcode;
  621. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  622. struct pipe *group;
  623. #if !BB_MMU
  624. char *group_as_string;
  625. #endif
  626. #if ENABLE_HUSH_FUNCTIONS
  627. struct function *child_func;
  628. /* This field is used to prevent a bug here:
  629. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  630. * When we execute "f1() {a;}" cmd, we create new function and clear
  631. * cmd->group, cmd->group_as_string, cmd->argv[0].
  632. * When we execute "f1() {b;}", we notice that f1 exists,
  633. * and that its "parent cmd" struct is still "alive",
  634. * we put those fields back into cmd->xxx
  635. * (struct function has ->parent_cmd ptr to facilitate that).
  636. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  637. * Without this trick, loop would execute a;b;b;b;...
  638. * instead of correct sequence a;b;a;b;...
  639. * When command is freed, it severs the link
  640. * (sets ->child_func->parent_cmd to NULL).
  641. */
  642. #endif
  643. char **argv; /* command name and arguments */
  644. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  645. * and on execution these are substituted with their values.
  646. * Substitution can make _several_ words out of one argv[n]!
  647. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  648. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  649. */
  650. struct redir_struct *redirects; /* I/O redirections */
  651. };
  652. /* Is there anything in this command at all? */
  653. #define IS_NULL_CMD(cmd) \
  654. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  655. struct pipe {
  656. struct pipe *next;
  657. int num_cmds; /* total number of commands in pipe */
  658. int alive_cmds; /* number of commands running (not exited) */
  659. int stopped_cmds; /* number of commands alive, but stopped */
  660. #if ENABLE_HUSH_JOB
  661. unsigned jobid; /* job number */
  662. pid_t pgrp; /* process group ID for the job */
  663. char *cmdtext; /* name of job */
  664. #endif
  665. struct command *cmds; /* array of commands in pipe */
  666. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  667. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  668. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  669. };
  670. typedef enum pipe_style {
  671. PIPE_SEQ = 0,
  672. PIPE_AND = 1,
  673. PIPE_OR = 2,
  674. PIPE_BG = 3,
  675. } pipe_style;
  676. /* Is there anything in this pipe at all? */
  677. #define IS_NULL_PIPE(pi) \
  678. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  679. /* This holds pointers to the various results of parsing */
  680. struct parse_context {
  681. /* linked list of pipes */
  682. struct pipe *list_head;
  683. /* last pipe (being constructed right now) */
  684. struct pipe *pipe;
  685. /* last command in pipe (being constructed right now) */
  686. struct command *command;
  687. /* last redirect in command->redirects list */
  688. struct redir_struct *pending_redirect;
  689. o_string word;
  690. #if !BB_MMU
  691. o_string as_string;
  692. #endif
  693. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  694. #if HAS_KEYWORDS
  695. smallint ctx_res_w;
  696. smallint ctx_inverted; /* "! cmd | cmd" */
  697. #if ENABLE_HUSH_CASE
  698. smallint ctx_dsemicolon; /* ";;" seen */
  699. #endif
  700. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  701. int old_flag;
  702. /* group we are enclosed in:
  703. * example: "if pipe1; pipe2; then pipe3; fi"
  704. * when we see "if" or "then", we malloc and copy current context,
  705. * and make ->stack point to it. then we parse pipeN.
  706. * when closing "then" / fi" / whatever is found,
  707. * we move list_head into ->stack->command->group,
  708. * copy ->stack into current context, and delete ->stack.
  709. * (parsing of { list } and ( list ) doesn't use this method)
  710. */
  711. struct parse_context *stack;
  712. #endif
  713. };
  714. enum {
  715. MAYBE_ASSIGNMENT = 0,
  716. DEFINITELY_ASSIGNMENT = 1,
  717. NOT_ASSIGNMENT = 2,
  718. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  719. WORD_IS_KEYWORD = 3,
  720. };
  721. /* On program start, environ points to initial environment.
  722. * putenv adds new pointers into it, unsetenv removes them.
  723. * Neither of these (de)allocates the strings.
  724. * setenv allocates new strings in malloc space and does putenv,
  725. * and thus setenv is unusable (leaky) for shell's purposes */
  726. #define setenv(...) setenv_is_leaky_dont_use()
  727. struct variable {
  728. struct variable *next;
  729. char *varstr; /* points to "name=" portion */
  730. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  731. uint16_t var_nest_level;
  732. smallint flg_export; /* putenv should be done on this var */
  733. smallint flg_read_only;
  734. };
  735. enum {
  736. BC_BREAK = 1,
  737. BC_CONTINUE = 2,
  738. };
  739. #if ENABLE_HUSH_FUNCTIONS
  740. struct function {
  741. struct function *next;
  742. char *name;
  743. struct command *parent_cmd;
  744. struct pipe *body;
  745. # if !BB_MMU
  746. char *body_as_string;
  747. # endif
  748. };
  749. #endif
  750. /* set -/+o OPT support. (TODO: make it optional)
  751. * bash supports the following opts:
  752. * allexport off
  753. * braceexpand on
  754. * emacs on
  755. * errexit off
  756. * errtrace off
  757. * functrace off
  758. * hashall on
  759. * histexpand off
  760. * history on
  761. * ignoreeof off
  762. * interactive-comments on
  763. * keyword off
  764. * monitor on
  765. * noclobber off
  766. * noexec off
  767. * noglob off
  768. * nolog off
  769. * notify off
  770. * nounset off
  771. * onecmd off
  772. * physical off
  773. * pipefail off
  774. * posix off
  775. * privileged off
  776. * verbose off
  777. * vi off
  778. * xtrace off
  779. */
  780. static const char o_opt_strings[] ALIGN1 =
  781. "pipefail\0"
  782. "noexec\0"
  783. "errexit\0"
  784. #if ENABLE_HUSH_MODE_X
  785. "xtrace\0"
  786. #endif
  787. ;
  788. enum {
  789. OPT_O_PIPEFAIL,
  790. OPT_O_NOEXEC,
  791. OPT_O_ERREXIT,
  792. #if ENABLE_HUSH_MODE_X
  793. OPT_O_XTRACE,
  794. #endif
  795. NUM_OPT_O
  796. };
  797. /* "Globals" within this file */
  798. /* Sorted roughly by size (smaller offsets == smaller code) */
  799. struct globals {
  800. /* interactive_fd != 0 means we are an interactive shell.
  801. * If we are, then saved_tty_pgrp can also be != 0, meaning
  802. * that controlling tty is available. With saved_tty_pgrp == 0,
  803. * job control still works, but terminal signals
  804. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  805. * process groups can only be created with "cmd &".
  806. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  807. * to give tty to the foreground process group,
  808. * and will take it back when the group is stopped (^Z)
  809. * or killed (^C).
  810. */
  811. #if ENABLE_HUSH_INTERACTIVE
  812. /* 'interactive_fd' is a fd# open to ctty, if we have one
  813. * _AND_ if we decided to act interactively */
  814. int interactive_fd;
  815. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  816. # define G_interactive_fd (G.interactive_fd)
  817. #else
  818. # define G_interactive_fd 0
  819. #endif
  820. #if ENABLE_FEATURE_EDITING
  821. line_input_t *line_input_state;
  822. #endif
  823. pid_t root_pid;
  824. pid_t root_ppid;
  825. pid_t last_bg_pid;
  826. #if ENABLE_HUSH_RANDOM_SUPPORT
  827. random_t random_gen;
  828. #endif
  829. #if ENABLE_HUSH_JOB
  830. int run_list_level;
  831. unsigned last_jobid;
  832. pid_t saved_tty_pgrp;
  833. struct pipe *job_list;
  834. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  835. #else
  836. # define G_saved_tty_pgrp 0
  837. #endif
  838. /* How deeply are we in context where "set -e" is ignored */
  839. int errexit_depth;
  840. /* "set -e" rules (do we follow them correctly?):
  841. * Exit if pipe, list, or compound command exits with a non-zero status.
  842. * Shell does not exit if failed command is part of condition in
  843. * if/while, part of && or || list except the last command, any command
  844. * in a pipe but the last, or if the command's return value is being
  845. * inverted with !. If a compound command other than a subshell returns a
  846. * non-zero status because a command failed while -e was being ignored, the
  847. * shell does not exit. A trap on ERR, if set, is executed before the shell
  848. * exits [ERR is a bashism].
  849. *
  850. * If a compound command or function executes in a context where -e is
  851. * ignored, none of the commands executed within are affected by the -e
  852. * setting. If a compound command or function sets -e while executing in a
  853. * context where -e is ignored, that setting does not have any effect until
  854. * the compound command or the command containing the function call completes.
  855. */
  856. char o_opt[NUM_OPT_O];
  857. #if ENABLE_HUSH_MODE_X
  858. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  859. #else
  860. # define G_x_mode 0
  861. #endif
  862. char opt_s;
  863. char opt_c;
  864. #if ENABLE_HUSH_INTERACTIVE
  865. smallint promptmode; /* 0: PS1, 1: PS2 */
  866. #endif
  867. smallint flag_SIGINT;
  868. #if ENABLE_HUSH_LOOPS
  869. smallint flag_break_continue;
  870. #endif
  871. #if ENABLE_HUSH_FUNCTIONS
  872. /* 0: outside of a function (or sourced file)
  873. * -1: inside of a function, ok to use return builtin
  874. * 1: return is invoked, skip all till end of func
  875. */
  876. smallint flag_return_in_progress;
  877. # define G_flag_return_in_progress (G.flag_return_in_progress)
  878. #else
  879. # define G_flag_return_in_progress 0
  880. #endif
  881. smallint exiting; /* used to prevent EXIT trap recursion */
  882. /* These support $? */
  883. smalluint last_exitcode;
  884. smalluint expand_exitcode;
  885. smalluint last_bg_pid_exitcode;
  886. #if ENABLE_HUSH_SET
  887. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  888. smalluint global_args_malloced;
  889. # define G_global_args_malloced (G.global_args_malloced)
  890. #else
  891. # define G_global_args_malloced 0
  892. #endif
  893. #if ENABLE_HUSH_BASH_COMPAT
  894. int dead_job_exitcode; /* for "wait -n" */
  895. #endif
  896. /* how many non-NULL argv's we have. NB: $# + 1 */
  897. int global_argc;
  898. char **global_argv;
  899. #if !BB_MMU
  900. char *argv0_for_re_execing;
  901. #endif
  902. #if ENABLE_HUSH_LOOPS
  903. unsigned depth_break_continue;
  904. unsigned depth_of_loop;
  905. #endif
  906. #if ENABLE_HUSH_GETOPTS
  907. unsigned getopt_count;
  908. #endif
  909. const char *ifs;
  910. char *ifs_whitespace; /* = G.ifs or malloced */
  911. const char *cwd;
  912. struct variable *top_var;
  913. char **expanded_assignments;
  914. struct variable **shadowed_vars_pp;
  915. unsigned var_nest_level;
  916. #if ENABLE_HUSH_FUNCTIONS
  917. # if ENABLE_HUSH_LOCAL
  918. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  919. # endif
  920. struct function *top_func;
  921. #endif
  922. /* Signal and trap handling */
  923. #if ENABLE_HUSH_FAST
  924. unsigned count_SIGCHLD;
  925. unsigned handled_SIGCHLD;
  926. smallint we_have_children;
  927. #endif
  928. #if ENABLE_HUSH_LINENO_VAR
  929. unsigned parse_lineno;
  930. unsigned execute_lineno;
  931. #endif
  932. HFILE *HFILE_list;
  933. /* Which signals have non-DFL handler (even with no traps set)?
  934. * Set at the start to:
  935. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  936. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  937. * The rest is cleared right before execv syscalls.
  938. * Other than these two times, never modified.
  939. */
  940. unsigned special_sig_mask;
  941. #if ENABLE_HUSH_JOB
  942. unsigned fatal_sig_mask;
  943. # define G_fatal_sig_mask (G.fatal_sig_mask)
  944. #else
  945. # define G_fatal_sig_mask 0
  946. #endif
  947. #if ENABLE_HUSH_TRAP
  948. char **traps; /* char *traps[NSIG] */
  949. # define G_traps G.traps
  950. #else
  951. # define G_traps ((char**)NULL)
  952. #endif
  953. sigset_t pending_set;
  954. #if ENABLE_HUSH_MEMLEAK
  955. unsigned long memleak_value;
  956. #endif
  957. #if ENABLE_HUSH_MODE_X
  958. unsigned x_mode_depth;
  959. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  960. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  961. * for all subsequent output.
  962. */
  963. int x_mode_fd;
  964. o_string x_mode_buf;
  965. #endif
  966. #if HUSH_DEBUG >= 2
  967. int debug_indent;
  968. #endif
  969. struct sigaction sa;
  970. char optstring_buf[sizeof("eixcs")];
  971. #if BASH_EPOCH_VARS
  972. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  973. #endif
  974. #if ENABLE_FEATURE_EDITING
  975. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  976. #endif
  977. };
  978. #define G (*ptr_to_globals)
  979. /* Not #defining name to G.name - this quickly gets unwieldy
  980. * (too many defines). Also, I actually prefer to see when a variable
  981. * is global, thus "G." prefix is a useful hint */
  982. #define INIT_G() do { \
  983. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  984. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  985. sigfillset(&G.sa.sa_mask); \
  986. G.sa.sa_flags = SA_RESTART; \
  987. } while (0)
  988. /* Function prototypes for builtins */
  989. static int builtin_cd(char **argv) FAST_FUNC;
  990. #if ENABLE_HUSH_ECHO
  991. static int builtin_echo(char **argv) FAST_FUNC;
  992. #endif
  993. static int builtin_eval(char **argv) FAST_FUNC;
  994. static int builtin_exec(char **argv) FAST_FUNC;
  995. static int builtin_exit(char **argv) FAST_FUNC;
  996. #if ENABLE_HUSH_EXPORT
  997. static int builtin_export(char **argv) FAST_FUNC;
  998. #endif
  999. #if ENABLE_HUSH_READONLY
  1000. static int builtin_readonly(char **argv) FAST_FUNC;
  1001. #endif
  1002. #if ENABLE_HUSH_JOB
  1003. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1004. static int builtin_jobs(char **argv) FAST_FUNC;
  1005. #endif
  1006. #if ENABLE_HUSH_GETOPTS
  1007. static int builtin_getopts(char **argv) FAST_FUNC;
  1008. #endif
  1009. #if ENABLE_HUSH_HELP
  1010. static int builtin_help(char **argv) FAST_FUNC;
  1011. #endif
  1012. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1013. static int builtin_history(char **argv) FAST_FUNC;
  1014. #endif
  1015. #if ENABLE_HUSH_LOCAL
  1016. static int builtin_local(char **argv) FAST_FUNC;
  1017. #endif
  1018. #if ENABLE_HUSH_MEMLEAK
  1019. static int builtin_memleak(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_PRINTF
  1022. static int builtin_printf(char **argv) FAST_FUNC;
  1023. #endif
  1024. static int builtin_pwd(char **argv) FAST_FUNC;
  1025. #if ENABLE_HUSH_READ
  1026. static int builtin_read(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if ENABLE_HUSH_SET
  1029. static int builtin_set(char **argv) FAST_FUNC;
  1030. #endif
  1031. static int builtin_shift(char **argv) FAST_FUNC;
  1032. static int builtin_source(char **argv) FAST_FUNC;
  1033. #if ENABLE_HUSH_TEST || BASH_TEST2
  1034. static int builtin_test(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_TRAP
  1037. static int builtin_trap(char **argv) FAST_FUNC;
  1038. #endif
  1039. #if ENABLE_HUSH_TYPE
  1040. static int builtin_type(char **argv) FAST_FUNC;
  1041. #endif
  1042. #if ENABLE_HUSH_TIMES
  1043. static int builtin_times(char **argv) FAST_FUNC;
  1044. #endif
  1045. static int builtin_true(char **argv) FAST_FUNC;
  1046. #if ENABLE_HUSH_UMASK
  1047. static int builtin_umask(char **argv) FAST_FUNC;
  1048. #endif
  1049. #if ENABLE_HUSH_UNSET
  1050. static int builtin_unset(char **argv) FAST_FUNC;
  1051. #endif
  1052. #if ENABLE_HUSH_KILL
  1053. static int builtin_kill(char **argv) FAST_FUNC;
  1054. #endif
  1055. #if ENABLE_HUSH_WAIT
  1056. static int builtin_wait(char **argv) FAST_FUNC;
  1057. #endif
  1058. #if ENABLE_HUSH_LOOPS
  1059. static int builtin_break(char **argv) FAST_FUNC;
  1060. static int builtin_continue(char **argv) FAST_FUNC;
  1061. #endif
  1062. #if ENABLE_HUSH_FUNCTIONS
  1063. static int builtin_return(char **argv) FAST_FUNC;
  1064. #endif
  1065. /* Table of built-in functions. They can be forked or not, depending on
  1066. * context: within pipes, they fork. As simple commands, they do not.
  1067. * When used in non-forking context, they can change global variables
  1068. * in the parent shell process. If forked, of course they cannot.
  1069. * For example, 'unset foo | whatever' will parse and run, but foo will
  1070. * still be set at the end. */
  1071. struct built_in_command {
  1072. const char *b_cmd;
  1073. int (*b_function)(char **argv) FAST_FUNC;
  1074. #if ENABLE_HUSH_HELP
  1075. const char *b_descr;
  1076. # define BLTIN(cmd, func, help) { cmd, func, help }
  1077. #else
  1078. # define BLTIN(cmd, func, help) { cmd, func }
  1079. #endif
  1080. };
  1081. static const struct built_in_command bltins1[] = {
  1082. BLTIN("." , builtin_source , "Run commands in file"),
  1083. BLTIN(":" , builtin_true , NULL),
  1084. #if ENABLE_HUSH_JOB
  1085. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1086. #endif
  1087. #if ENABLE_HUSH_LOOPS
  1088. BLTIN("break" , builtin_break , "Exit loop"),
  1089. #endif
  1090. BLTIN("cd" , builtin_cd , "Change directory"),
  1091. #if ENABLE_HUSH_LOOPS
  1092. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1093. #endif
  1094. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1095. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1096. BLTIN("exit" , builtin_exit , NULL),
  1097. #if ENABLE_HUSH_EXPORT
  1098. BLTIN("export" , builtin_export , "Set environment variables"),
  1099. #endif
  1100. #if ENABLE_HUSH_JOB
  1101. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1102. #endif
  1103. #if ENABLE_HUSH_GETOPTS
  1104. BLTIN("getopts" , builtin_getopts , NULL),
  1105. #endif
  1106. #if ENABLE_HUSH_HELP
  1107. BLTIN("help" , builtin_help , NULL),
  1108. #endif
  1109. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1110. BLTIN("history" , builtin_history , "Show history"),
  1111. #endif
  1112. #if ENABLE_HUSH_JOB
  1113. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1114. #endif
  1115. #if ENABLE_HUSH_KILL
  1116. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1117. #endif
  1118. #if ENABLE_HUSH_LOCAL
  1119. BLTIN("local" , builtin_local , "Set local variables"),
  1120. #endif
  1121. #if ENABLE_HUSH_MEMLEAK
  1122. BLTIN("memleak" , builtin_memleak , NULL),
  1123. #endif
  1124. #if ENABLE_HUSH_READ
  1125. BLTIN("read" , builtin_read , "Input into variable"),
  1126. #endif
  1127. #if ENABLE_HUSH_READONLY
  1128. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1129. #endif
  1130. #if ENABLE_HUSH_FUNCTIONS
  1131. BLTIN("return" , builtin_return , "Return from function"),
  1132. #endif
  1133. #if ENABLE_HUSH_SET
  1134. BLTIN("set" , builtin_set , "Set positional parameters"),
  1135. #endif
  1136. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1137. #if BASH_SOURCE
  1138. BLTIN("source" , builtin_source , NULL),
  1139. #endif
  1140. #if ENABLE_HUSH_TIMES
  1141. BLTIN("times" , builtin_times , NULL),
  1142. #endif
  1143. #if ENABLE_HUSH_TRAP
  1144. BLTIN("trap" , builtin_trap , "Trap signals"),
  1145. #endif
  1146. BLTIN("true" , builtin_true , NULL),
  1147. #if ENABLE_HUSH_TYPE
  1148. BLTIN("type" , builtin_type , "Show command type"),
  1149. #endif
  1150. #if ENABLE_HUSH_ULIMIT
  1151. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1152. #endif
  1153. #if ENABLE_HUSH_UMASK
  1154. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1155. #endif
  1156. #if ENABLE_HUSH_UNSET
  1157. BLTIN("unset" , builtin_unset , "Unset variables"),
  1158. #endif
  1159. #if ENABLE_HUSH_WAIT
  1160. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1161. #endif
  1162. };
  1163. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1164. * (it's cheaper to run an external program in this case):
  1165. */
  1166. static const struct built_in_command bltins2[] = {
  1167. #if ENABLE_HUSH_TEST
  1168. BLTIN("[" , builtin_test , NULL),
  1169. #endif
  1170. #if BASH_TEST2
  1171. BLTIN("[[" , builtin_test , NULL),
  1172. #endif
  1173. #if ENABLE_HUSH_ECHO
  1174. BLTIN("echo" , builtin_echo , NULL),
  1175. #endif
  1176. #if ENABLE_HUSH_PRINTF
  1177. BLTIN("printf" , builtin_printf , NULL),
  1178. #endif
  1179. BLTIN("pwd" , builtin_pwd , NULL),
  1180. #if ENABLE_HUSH_TEST
  1181. BLTIN("test" , builtin_test , NULL),
  1182. #endif
  1183. };
  1184. /* Debug printouts.
  1185. */
  1186. #if HUSH_DEBUG >= 2
  1187. /* prevent disasters with G.debug_indent < 0 */
  1188. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1189. # define debug_enter() (G.debug_indent++)
  1190. # define debug_leave() (G.debug_indent--)
  1191. #else
  1192. # define indent() ((void)0)
  1193. # define debug_enter() ((void)0)
  1194. # define debug_leave() ((void)0)
  1195. #endif
  1196. #ifndef debug_printf
  1197. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1198. #endif
  1199. #ifndef debug_printf_parse
  1200. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1201. #endif
  1202. #ifndef debug_printf_heredoc
  1203. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1204. #endif
  1205. #ifndef debug_printf_exec
  1206. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1207. #endif
  1208. #ifndef debug_printf_env
  1209. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1210. #endif
  1211. #ifndef debug_printf_jobs
  1212. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. # define DEBUG_JOBS 1
  1214. #else
  1215. # define DEBUG_JOBS 0
  1216. #endif
  1217. #ifndef debug_printf_expand
  1218. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. # define DEBUG_EXPAND 1
  1220. #else
  1221. # define DEBUG_EXPAND 0
  1222. #endif
  1223. #ifndef debug_printf_varexp
  1224. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_glob
  1227. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_GLOB 1
  1229. #else
  1230. # define DEBUG_GLOB 0
  1231. #endif
  1232. #ifndef debug_printf_redir
  1233. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. #endif
  1235. #ifndef debug_printf_list
  1236. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1237. #endif
  1238. #ifndef debug_printf_subst
  1239. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_prompt
  1242. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. #endif
  1244. #ifndef debug_printf_clean
  1245. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1246. # define DEBUG_CLEAN 1
  1247. #else
  1248. # define DEBUG_CLEAN 0
  1249. #endif
  1250. #if DEBUG_EXPAND
  1251. static void debug_print_strings(const char *prefix, char **vv)
  1252. {
  1253. indent();
  1254. fdprintf(2, "%s:\n", prefix);
  1255. while (*vv)
  1256. fdprintf(2, " '%s'\n", *vv++);
  1257. }
  1258. #else
  1259. # define debug_print_strings(prefix, vv) ((void)0)
  1260. #endif
  1261. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1262. */
  1263. #if LEAK_HUNTING
  1264. static void *xxmalloc(int lineno, size_t size)
  1265. {
  1266. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1267. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1268. return ptr;
  1269. }
  1270. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1271. {
  1272. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1273. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1274. return ptr;
  1275. }
  1276. static char *xxstrdup(int lineno, const char *str)
  1277. {
  1278. char *ptr = xstrdup(str);
  1279. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1280. return ptr;
  1281. }
  1282. static void xxfree(void *ptr)
  1283. {
  1284. fdprintf(2, "free %p\n", ptr);
  1285. free(ptr);
  1286. }
  1287. # define xmalloc(s) xxmalloc(__LINE__, s)
  1288. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1289. # define xstrdup(s) xxstrdup(__LINE__, s)
  1290. # define free(p) xxfree(p)
  1291. #endif
  1292. /* Syntax and runtime errors. They always abort scripts.
  1293. * In interactive use they usually discard unparsed and/or unexecuted commands
  1294. * and return to the prompt.
  1295. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1296. */
  1297. #if HUSH_DEBUG < 2
  1298. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1299. # define syntax_error(lineno, msg) syntax_error(msg)
  1300. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1301. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1302. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1303. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1304. #endif
  1305. static void die_if_script(void)
  1306. {
  1307. if (!G_interactive_fd) {
  1308. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1309. xfunc_error_retval = G.last_exitcode;
  1310. xfunc_die();
  1311. }
  1312. }
  1313. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1314. {
  1315. va_list p;
  1316. #if HUSH_DEBUG >= 2
  1317. bb_error_msg("hush.c:%u", lineno);
  1318. #endif
  1319. va_start(p, fmt);
  1320. bb_verror_msg(fmt, p, NULL);
  1321. va_end(p);
  1322. die_if_script();
  1323. }
  1324. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1325. {
  1326. if (msg)
  1327. bb_error_msg("syntax error: %s", msg);
  1328. else
  1329. bb_error_msg("syntax error");
  1330. die_if_script();
  1331. }
  1332. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1333. {
  1334. bb_error_msg("syntax error at '%s'", msg);
  1335. die_if_script();
  1336. }
  1337. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1338. {
  1339. bb_error_msg("syntax error: unterminated %s", s);
  1340. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1341. // die_if_script();
  1342. }
  1343. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1344. {
  1345. char msg[2] = { ch, '\0' };
  1346. syntax_error_unterm_str(lineno, msg);
  1347. }
  1348. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1349. {
  1350. char msg[2];
  1351. msg[0] = ch;
  1352. msg[1] = '\0';
  1353. #if HUSH_DEBUG >= 2
  1354. bb_error_msg("hush.c:%u", lineno);
  1355. #endif
  1356. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1357. die_if_script();
  1358. }
  1359. #if HUSH_DEBUG < 2
  1360. # undef msg_and_die_if_script
  1361. # undef syntax_error
  1362. # undef syntax_error_at
  1363. # undef syntax_error_unterm_ch
  1364. # undef syntax_error_unterm_str
  1365. # undef syntax_error_unexpected_ch
  1366. #else
  1367. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1368. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1369. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1370. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1371. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1372. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1373. #endif
  1374. /* Utility functions
  1375. */
  1376. /* Replace each \x with x in place, return ptr past NUL. */
  1377. static char *unbackslash(char *src)
  1378. {
  1379. char *dst = src = strchrnul(src, '\\');
  1380. while (1) {
  1381. if (*src == '\\') {
  1382. src++;
  1383. if (*src != '\0') {
  1384. /* \x -> x */
  1385. *dst++ = *src++;
  1386. continue;
  1387. }
  1388. /* else: "\<nul>". Do not delete this backslash.
  1389. * Testcase: eval 'echo ok\'
  1390. */
  1391. *dst++ = '\\';
  1392. /* fallthrough */
  1393. }
  1394. if ((*dst++ = *src++) == '\0')
  1395. break;
  1396. }
  1397. return dst;
  1398. }
  1399. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1400. {
  1401. int i;
  1402. unsigned count1;
  1403. unsigned count2;
  1404. char **v;
  1405. v = strings;
  1406. count1 = 0;
  1407. if (v) {
  1408. while (*v) {
  1409. count1++;
  1410. v++;
  1411. }
  1412. }
  1413. count2 = 0;
  1414. v = add;
  1415. while (*v) {
  1416. count2++;
  1417. v++;
  1418. }
  1419. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1420. v[count1 + count2] = NULL;
  1421. i = count2;
  1422. while (--i >= 0)
  1423. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1424. return v;
  1425. }
  1426. #if LEAK_HUNTING
  1427. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1428. {
  1429. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1430. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1431. return ptr;
  1432. }
  1433. #define add_strings_to_strings(strings, add, need_to_dup) \
  1434. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1435. #endif
  1436. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1437. static char **add_string_to_strings(char **strings, char *add)
  1438. {
  1439. char *v[2];
  1440. v[0] = add;
  1441. v[1] = NULL;
  1442. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1443. }
  1444. #if LEAK_HUNTING
  1445. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1446. {
  1447. char **ptr = add_string_to_strings(strings, add);
  1448. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1449. return ptr;
  1450. }
  1451. #define add_string_to_strings(strings, add) \
  1452. xx_add_string_to_strings(__LINE__, strings, add)
  1453. #endif
  1454. static void free_strings(char **strings)
  1455. {
  1456. char **v;
  1457. if (!strings)
  1458. return;
  1459. v = strings;
  1460. while (*v) {
  1461. free(*v);
  1462. v++;
  1463. }
  1464. free(strings);
  1465. }
  1466. static int dup_CLOEXEC(int fd, int avoid_fd)
  1467. {
  1468. int newfd;
  1469. repeat:
  1470. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1471. if (newfd >= 0) {
  1472. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1473. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1474. } else { /* newfd < 0 */
  1475. if (errno == EBUSY)
  1476. goto repeat;
  1477. if (errno == EINTR)
  1478. goto repeat;
  1479. }
  1480. return newfd;
  1481. }
  1482. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1483. {
  1484. int newfd;
  1485. repeat:
  1486. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1487. if (newfd < 0) {
  1488. if (errno == EBUSY)
  1489. goto repeat;
  1490. if (errno == EINTR)
  1491. goto repeat;
  1492. /* fd was not open? */
  1493. if (errno == EBADF)
  1494. return fd;
  1495. xfunc_die();
  1496. }
  1497. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1498. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1499. close(fd);
  1500. return newfd;
  1501. }
  1502. /* Manipulating HFILEs */
  1503. static HFILE *hfopen(const char *name)
  1504. {
  1505. HFILE *fp;
  1506. int fd;
  1507. fd = STDIN_FILENO;
  1508. if (name) {
  1509. fd = open(name, O_RDONLY | O_CLOEXEC);
  1510. if (fd < 0)
  1511. return NULL;
  1512. if (O_CLOEXEC == 0) /* ancient libc */
  1513. close_on_exec_on(fd);
  1514. }
  1515. fp = xmalloc(sizeof(*fp));
  1516. fp->is_stdin = (name == NULL);
  1517. fp->fd = fd;
  1518. fp->cur = fp->end = fp->buf;
  1519. fp->next_hfile = G.HFILE_list;
  1520. G.HFILE_list = fp;
  1521. return fp;
  1522. }
  1523. static void hfclose(HFILE *fp)
  1524. {
  1525. HFILE **pp = &G.HFILE_list;
  1526. while (*pp) {
  1527. HFILE *cur = *pp;
  1528. if (cur == fp) {
  1529. *pp = cur->next_hfile;
  1530. break;
  1531. }
  1532. pp = &cur->next_hfile;
  1533. }
  1534. if (fp->fd >= 0)
  1535. close(fp->fd);
  1536. free(fp);
  1537. }
  1538. static int refill_HFILE_and_getc(HFILE *fp)
  1539. {
  1540. int n;
  1541. if (fp->fd < 0) {
  1542. /* Already saw EOF */
  1543. return EOF;
  1544. }
  1545. /* Try to buffer more input */
  1546. fp->cur = fp->buf;
  1547. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1548. if (n < 0) {
  1549. bb_perror_msg("read error");
  1550. n = 0;
  1551. }
  1552. fp->end = fp->buf + n;
  1553. if (n == 0) {
  1554. /* EOF/error */
  1555. close(fp->fd);
  1556. fp->fd = -1;
  1557. return EOF;
  1558. }
  1559. return (unsigned char)(*fp->cur++);
  1560. }
  1561. /* Inlined for common case of non-empty buffer.
  1562. */
  1563. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1564. {
  1565. if (fp->cur < fp->end)
  1566. return (unsigned char)(*fp->cur++);
  1567. /* Buffer empty */
  1568. return refill_HFILE_and_getc(fp);
  1569. }
  1570. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1571. {
  1572. HFILE *fl = G.HFILE_list;
  1573. while (fl) {
  1574. if (fd == fl->fd) {
  1575. /* We use it only on script files, they are all CLOEXEC */
  1576. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1577. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1578. return 1; /* "found and moved" */
  1579. }
  1580. fl = fl->next_hfile;
  1581. }
  1582. #if ENABLE_HUSH_MODE_X
  1583. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1584. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1585. return 1; /* "found and moved" */
  1586. }
  1587. #endif
  1588. return 0; /* "not in the list" */
  1589. }
  1590. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1591. static void close_all_HFILE_list(void)
  1592. {
  1593. HFILE *fl = G.HFILE_list;
  1594. while (fl) {
  1595. /* hfclose would also free HFILE object.
  1596. * It is disastrous if we share memory with a vforked parent.
  1597. * I'm not sure we never come here after vfork.
  1598. * Therefore just close fd, nothing more.
  1599. *
  1600. * ">" instead of ">=": we don't close fd#0,
  1601. * interactive shell uses hfopen(NULL) as stdin input
  1602. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1603. * If we'd close it here, then e.g. interactive "set | sort"
  1604. * with NOFORKed sort, would have sort's input fd closed.
  1605. */
  1606. if (fl->fd > 0)
  1607. /*hfclose(fl); - unsafe */
  1608. close(fl->fd);
  1609. fl = fl->next_hfile;
  1610. }
  1611. }
  1612. #endif
  1613. static int fd_in_HFILEs(int fd)
  1614. {
  1615. HFILE *fl = G.HFILE_list;
  1616. while (fl) {
  1617. if (fl->fd == fd)
  1618. return 1;
  1619. fl = fl->next_hfile;
  1620. }
  1621. return 0;
  1622. }
  1623. /* Helpers for setting new $n and restoring them back
  1624. */
  1625. typedef struct save_arg_t {
  1626. char *sv_argv0;
  1627. char **sv_g_argv;
  1628. int sv_g_argc;
  1629. IF_HUSH_SET(smallint sv_g_malloced;)
  1630. } save_arg_t;
  1631. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1632. {
  1633. sv->sv_argv0 = argv[0];
  1634. sv->sv_g_argv = G.global_argv;
  1635. sv->sv_g_argc = G.global_argc;
  1636. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1637. argv[0] = G.global_argv[0]; /* retain $0 */
  1638. G.global_argv = argv;
  1639. IF_HUSH_SET(G.global_args_malloced = 0;)
  1640. G.global_argc = 1 + string_array_len(argv + 1);
  1641. }
  1642. static void restore_G_args(save_arg_t *sv, char **argv)
  1643. {
  1644. #if ENABLE_HUSH_SET
  1645. if (G.global_args_malloced) {
  1646. /* someone ran "set -- arg1 arg2 ...", undo */
  1647. char **pp = G.global_argv;
  1648. while (*++pp) /* note: does not free $0 */
  1649. free(*pp);
  1650. free(G.global_argv);
  1651. }
  1652. #endif
  1653. argv[0] = sv->sv_argv0;
  1654. G.global_argv = sv->sv_g_argv;
  1655. G.global_argc = sv->sv_g_argc;
  1656. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1657. }
  1658. /* Basic theory of signal handling in shell
  1659. * ========================================
  1660. * This does not describe what hush does, rather, it is current understanding
  1661. * what it _should_ do. If it doesn't, it's a bug.
  1662. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1663. *
  1664. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1665. * is finished or backgrounded. It is the same in interactive and
  1666. * non-interactive shells, and is the same regardless of whether
  1667. * a user trap handler is installed or a shell special one is in effect.
  1668. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1669. * backgrounds (i.e. stops) or kills all members of currently running
  1670. * pipe.
  1671. *
  1672. * Wait builtin is interruptible by signals for which user trap is set
  1673. * or by SIGINT in interactive shell.
  1674. *
  1675. * Trap handlers will execute even within trap handlers. (right?)
  1676. *
  1677. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1678. * except for handlers set to '' (empty string).
  1679. *
  1680. * If job control is off, backgrounded commands ("cmd &")
  1681. * have SIGINT, SIGQUIT set to SIG_IGN.
  1682. *
  1683. * Commands which are run in command substitution ("`cmd`")
  1684. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1685. *
  1686. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1687. * by the shell from its parent.
  1688. *
  1689. * Signals which differ from SIG_DFL action
  1690. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1691. *
  1692. * SIGQUIT: ignore
  1693. * SIGTERM (interactive): ignore
  1694. * SIGHUP (interactive):
  1695. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1696. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1697. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1698. * that all pipe members are stopped. Try this in bash:
  1699. * while :; do :; done - ^Z does not background it
  1700. * (while :; do :; done) - ^Z backgrounds it
  1701. * SIGINT (interactive): wait for last pipe, ignore the rest
  1702. * of the command line, show prompt. NB: ^C does not send SIGINT
  1703. * to interactive shell while shell is waiting for a pipe,
  1704. * since shell is bg'ed (is not in foreground process group).
  1705. * Example 1: this waits 5 sec, but does not execute ls:
  1706. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1707. * Example 2: this does not wait and does not execute ls:
  1708. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1709. * Example 3: this does not wait 5 sec, but executes ls:
  1710. * "sleep 5; ls -l" + press ^C
  1711. * Example 4: this does not wait and does not execute ls:
  1712. * "sleep 5 & wait; ls -l" + press ^C
  1713. *
  1714. * (What happens to signals which are IGN on shell start?)
  1715. * (What happens with signal mask on shell start?)
  1716. *
  1717. * Old implementation
  1718. * ==================
  1719. * We use in-kernel pending signal mask to determine which signals were sent.
  1720. * We block all signals which we don't want to take action immediately,
  1721. * i.e. we block all signals which need to have special handling as described
  1722. * above, and all signals which have traps set.
  1723. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1724. * and act on them.
  1725. *
  1726. * unsigned special_sig_mask: a mask of such "special" signals
  1727. * sigset_t blocked_set: current blocked signal set
  1728. *
  1729. * "trap - SIGxxx":
  1730. * clear bit in blocked_set unless it is also in special_sig_mask
  1731. * "trap 'cmd' SIGxxx":
  1732. * set bit in blocked_set (even if 'cmd' is '')
  1733. * after [v]fork, if we plan to be a shell:
  1734. * unblock signals with special interactive handling
  1735. * (child shell is not interactive),
  1736. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1737. * after [v]fork, if we plan to exec:
  1738. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1739. * Restore blocked signal set to one inherited by shell just prior to exec.
  1740. *
  1741. * Note: as a result, we do not use signal handlers much. The only uses
  1742. * are to count SIGCHLDs
  1743. * and to restore tty pgrp on signal-induced exit.
  1744. *
  1745. * Note 2 (compat):
  1746. * Standard says "When a subshell is entered, traps that are not being ignored
  1747. * are set to the default actions". bash interprets it so that traps which
  1748. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1749. *
  1750. * Problem: the above approach makes it unwieldy to catch signals while
  1751. * we are in read builtin, or while we read commands from stdin:
  1752. * masked signals are not visible!
  1753. *
  1754. * New implementation
  1755. * ==================
  1756. * We record each signal we are interested in by installing signal handler
  1757. * for them - a bit like emulating kernel pending signal mask in userspace.
  1758. * We are interested in: signals which need to have special handling
  1759. * as described above, and all signals which have traps set.
  1760. * Signals are recorded in pending_set.
  1761. * After each pipe execution, we extract any pending signals
  1762. * and act on them.
  1763. *
  1764. * unsigned special_sig_mask: a mask of shell-special signals.
  1765. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1766. * char *traps[sig] if trap for sig is set (even if it's '').
  1767. * sigset_t pending_set: set of sigs we received.
  1768. *
  1769. * "trap - SIGxxx":
  1770. * if sig is in special_sig_mask, set handler back to:
  1771. * record_pending_signo, or to IGN if it's a tty stop signal
  1772. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1773. * else: set handler back to SIG_DFL
  1774. * "trap 'cmd' SIGxxx":
  1775. * set handler to record_pending_signo.
  1776. * "trap '' SIGxxx":
  1777. * set handler to SIG_IGN.
  1778. * after [v]fork, if we plan to be a shell:
  1779. * set signals with special interactive handling to SIG_DFL
  1780. * (because child shell is not interactive),
  1781. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1782. * after [v]fork, if we plan to exec:
  1783. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1784. *
  1785. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1786. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1787. *
  1788. * Note (compat):
  1789. * Standard says "When a subshell is entered, traps that are not being ignored
  1790. * are set to the default actions". bash interprets it so that traps which
  1791. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1792. */
  1793. enum {
  1794. SPECIAL_INTERACTIVE_SIGS = 0
  1795. | (1 << SIGTERM)
  1796. | (1 << SIGINT)
  1797. | (1 << SIGHUP)
  1798. ,
  1799. SPECIAL_JOBSTOP_SIGS = 0
  1800. #if ENABLE_HUSH_JOB
  1801. | (1 << SIGTTIN)
  1802. | (1 << SIGTTOU)
  1803. | (1 << SIGTSTP)
  1804. #endif
  1805. ,
  1806. };
  1807. static void record_pending_signo(int sig)
  1808. {
  1809. sigaddset(&G.pending_set, sig);
  1810. #if ENABLE_HUSH_FAST
  1811. if (sig == SIGCHLD) {
  1812. G.count_SIGCHLD++;
  1813. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1814. }
  1815. #endif
  1816. }
  1817. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1818. {
  1819. struct sigaction old_sa;
  1820. /* We could use signal() to install handlers... almost:
  1821. * except that we need to mask ALL signals while handlers run.
  1822. * I saw signal nesting in strace, race window isn't small.
  1823. * SA_RESTART is also needed, but in Linux, signal()
  1824. * sets SA_RESTART too.
  1825. */
  1826. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1827. /* sigfillset(&G.sa.sa_mask); - already done */
  1828. /* G.sa.sa_flags = SA_RESTART; - already done */
  1829. G.sa.sa_handler = handler;
  1830. sigaction(sig, &G.sa, &old_sa);
  1831. return old_sa.sa_handler;
  1832. }
  1833. static void hush_exit(int exitcode) NORETURN;
  1834. static void restore_ttypgrp_and__exit(void) NORETURN;
  1835. static void restore_ttypgrp_and__exit(void)
  1836. {
  1837. /* xfunc has failed! die die die */
  1838. /* no EXIT traps, this is an escape hatch! */
  1839. G.exiting = 1;
  1840. hush_exit(xfunc_error_retval);
  1841. }
  1842. #if ENABLE_HUSH_JOB
  1843. /* Needed only on some libc:
  1844. * It was observed that on exit(), fgetc'ed buffered data
  1845. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1846. * With the net effect that even after fork(), not vfork(),
  1847. * exit() in NOEXECed applet in "sh SCRIPT":
  1848. * noexec_applet_here
  1849. * echo END_OF_SCRIPT
  1850. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1851. * This makes "echo END_OF_SCRIPT" executed twice.
  1852. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1853. * and in `cmd` handling.
  1854. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1855. */
  1856. static void fflush_and__exit(void) NORETURN;
  1857. static void fflush_and__exit(void)
  1858. {
  1859. fflush_all();
  1860. _exit(xfunc_error_retval);
  1861. }
  1862. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1863. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1864. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1865. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1866. /* Restores tty foreground process group, and exits.
  1867. * May be called as signal handler for fatal signal
  1868. * (will resend signal to itself, producing correct exit state)
  1869. * or called directly with -EXITCODE.
  1870. * We also call it if xfunc is exiting.
  1871. */
  1872. static void sigexit(int sig) NORETURN;
  1873. static void sigexit(int sig)
  1874. {
  1875. /* Careful: we can end up here after [v]fork. Do not restore
  1876. * tty pgrp then, only top-level shell process does that */
  1877. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1878. /* Disable all signals: job control, SIGPIPE, etc.
  1879. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1880. */
  1881. sigprocmask_allsigs(SIG_BLOCK);
  1882. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1883. }
  1884. /* Not a signal, just exit */
  1885. if (sig <= 0)
  1886. _exit(- sig);
  1887. kill_myself_with_sig(sig); /* does not return */
  1888. }
  1889. #else
  1890. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1891. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1892. #endif
  1893. static sighandler_t pick_sighandler(unsigned sig)
  1894. {
  1895. sighandler_t handler = SIG_DFL;
  1896. if (sig < sizeof(unsigned)*8) {
  1897. unsigned sigmask = (1 << sig);
  1898. #if ENABLE_HUSH_JOB
  1899. /* is sig fatal? */
  1900. if (G_fatal_sig_mask & sigmask)
  1901. handler = sigexit;
  1902. else
  1903. #endif
  1904. /* sig has special handling? */
  1905. if (G.special_sig_mask & sigmask) {
  1906. handler = record_pending_signo;
  1907. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1908. * in order to ignore them: they will be raised
  1909. * in an endless loop when we try to do some
  1910. * terminal ioctls! We do have to _ignore_ these.
  1911. */
  1912. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1913. handler = SIG_IGN;
  1914. }
  1915. }
  1916. return handler;
  1917. }
  1918. /* Restores tty foreground process group, and exits. */
  1919. static void hush_exit(int exitcode)
  1920. {
  1921. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1922. if (G.line_input_state)
  1923. save_history(G.line_input_state);
  1924. #endif
  1925. fflush_all();
  1926. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1927. char *argv[3];
  1928. /* argv[0] is unused */
  1929. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1930. argv[2] = NULL;
  1931. G.exiting = 1; /* prevent EXIT trap recursion */
  1932. /* Note: G_traps[0] is not cleared!
  1933. * "trap" will still show it, if executed
  1934. * in the handler */
  1935. builtin_eval(argv);
  1936. }
  1937. #if ENABLE_FEATURE_CLEAN_UP
  1938. {
  1939. struct variable *cur_var;
  1940. if (G.cwd != bb_msg_unknown)
  1941. free((char*)G.cwd);
  1942. cur_var = G.top_var;
  1943. while (cur_var) {
  1944. struct variable *tmp = cur_var;
  1945. if (!cur_var->max_len)
  1946. free(cur_var->varstr);
  1947. cur_var = cur_var->next;
  1948. free(tmp);
  1949. }
  1950. }
  1951. #endif
  1952. fflush_all();
  1953. #if ENABLE_HUSH_JOB
  1954. sigexit(- (exitcode & 0xff));
  1955. #else
  1956. _exit(exitcode);
  1957. #endif
  1958. }
  1959. //TODO: return a mask of ALL handled sigs?
  1960. static int check_and_run_traps(void)
  1961. {
  1962. int last_sig = 0;
  1963. while (1) {
  1964. int sig;
  1965. if (sigisemptyset(&G.pending_set))
  1966. break;
  1967. sig = 0;
  1968. do {
  1969. sig++;
  1970. if (sigismember(&G.pending_set, sig)) {
  1971. sigdelset(&G.pending_set, sig);
  1972. goto got_sig;
  1973. }
  1974. } while (sig < NSIG);
  1975. break;
  1976. got_sig:
  1977. if (G_traps && G_traps[sig]) {
  1978. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1979. if (G_traps[sig][0]) {
  1980. /* We have user-defined handler */
  1981. smalluint save_rcode;
  1982. char *argv[3];
  1983. /* argv[0] is unused */
  1984. argv[1] = xstrdup(G_traps[sig]);
  1985. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1986. argv[2] = NULL;
  1987. save_rcode = G.last_exitcode;
  1988. builtin_eval(argv);
  1989. free(argv[1]);
  1990. //FIXME: shouldn't it be set to 128 + sig instead?
  1991. G.last_exitcode = save_rcode;
  1992. last_sig = sig;
  1993. } /* else: "" trap, ignoring signal */
  1994. continue;
  1995. }
  1996. /* not a trap: special action */
  1997. switch (sig) {
  1998. case SIGINT:
  1999. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2000. G.flag_SIGINT = 1;
  2001. last_sig = sig;
  2002. break;
  2003. #if ENABLE_HUSH_JOB
  2004. case SIGHUP: {
  2005. //TODO: why are we doing this? ash and dash don't do this,
  2006. //they have no handler for SIGHUP at all,
  2007. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2008. struct pipe *job;
  2009. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2010. /* bash is observed to signal whole process groups,
  2011. * not individual processes */
  2012. for (job = G.job_list; job; job = job->next) {
  2013. if (job->pgrp <= 0)
  2014. continue;
  2015. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2016. if (kill(- job->pgrp, SIGHUP) == 0)
  2017. kill(- job->pgrp, SIGCONT);
  2018. }
  2019. sigexit(SIGHUP);
  2020. }
  2021. #endif
  2022. #if ENABLE_HUSH_FAST
  2023. case SIGCHLD:
  2024. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2025. G.count_SIGCHLD++;
  2026. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2027. /* Note:
  2028. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2029. * This simplifies wait builtin a bit.
  2030. */
  2031. break;
  2032. #endif
  2033. default: /* ignored: */
  2034. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2035. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2036. /* Note:
  2037. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2038. * Example: wait is not interrupted by TERM
  2039. * in interactive shell, because TERM is ignored.
  2040. */
  2041. break;
  2042. }
  2043. }
  2044. return last_sig;
  2045. }
  2046. static const char *get_cwd(int force)
  2047. {
  2048. if (force || G.cwd == NULL) {
  2049. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2050. * we must not try to free(bb_msg_unknown) */
  2051. if (G.cwd == bb_msg_unknown)
  2052. G.cwd = NULL;
  2053. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2054. if (!G.cwd)
  2055. G.cwd = bb_msg_unknown;
  2056. }
  2057. return G.cwd;
  2058. }
  2059. /*
  2060. * Shell and environment variable support
  2061. */
  2062. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2063. {
  2064. struct variable **pp;
  2065. struct variable *cur;
  2066. pp = &G.top_var;
  2067. while ((cur = *pp) != NULL) {
  2068. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2069. return pp;
  2070. pp = &cur->next;
  2071. }
  2072. return NULL;
  2073. }
  2074. static const char* FAST_FUNC get_local_var_value(const char *name)
  2075. {
  2076. struct variable **vpp;
  2077. unsigned len = strlen(name);
  2078. if (G.expanded_assignments) {
  2079. char **cpp = G.expanded_assignments;
  2080. while (*cpp) {
  2081. char *cp = *cpp;
  2082. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2083. return cp + len + 1;
  2084. cpp++;
  2085. }
  2086. }
  2087. vpp = get_ptr_to_local_var(name, len);
  2088. if (vpp)
  2089. return (*vpp)->varstr + len + 1;
  2090. if (strcmp(name, "PPID") == 0)
  2091. return utoa(G.root_ppid);
  2092. // bash compat: UID? EUID?
  2093. #if ENABLE_HUSH_RANDOM_SUPPORT
  2094. if (strcmp(name, "RANDOM") == 0)
  2095. return utoa(next_random(&G.random_gen));
  2096. #endif
  2097. #if ENABLE_HUSH_LINENO_VAR
  2098. if (strcmp(name, "LINENO") == 0)
  2099. return utoa(G.execute_lineno);
  2100. #endif
  2101. #if BASH_EPOCH_VARS
  2102. {
  2103. const char *fmt = NULL;
  2104. if (strcmp(name, "EPOCHSECONDS") == 0)
  2105. fmt = "%lu";
  2106. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2107. fmt = "%lu.%06u";
  2108. if (fmt) {
  2109. struct timeval tv;
  2110. gettimeofday(&tv, NULL);
  2111. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2112. (unsigned)tv.tv_usec);
  2113. return G.epoch_buf;
  2114. }
  2115. }
  2116. #endif
  2117. return NULL;
  2118. }
  2119. #if ENABLE_HUSH_GETOPTS
  2120. static void handle_changed_special_names(const char *name, unsigned name_len)
  2121. {
  2122. if (name_len == 6) {
  2123. if (strncmp(name, "OPTIND", 6) == 0) {
  2124. G.getopt_count = 0;
  2125. return;
  2126. }
  2127. }
  2128. }
  2129. #else
  2130. /* Do not even bother evaluating arguments */
  2131. # define handle_changed_special_names(...) ((void)0)
  2132. #endif
  2133. /* str holds "NAME=VAL" and is expected to be malloced.
  2134. * We take ownership of it.
  2135. */
  2136. #define SETFLAG_EXPORT (1 << 0)
  2137. #define SETFLAG_UNEXPORT (1 << 1)
  2138. #define SETFLAG_MAKE_RO (1 << 2)
  2139. #define SETFLAG_VARLVL_SHIFT 3
  2140. static int set_local_var(char *str, unsigned flags)
  2141. {
  2142. struct variable **cur_pp;
  2143. struct variable *cur;
  2144. char *free_me = NULL;
  2145. char *eq_sign;
  2146. int name_len;
  2147. int retval;
  2148. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2149. eq_sign = strchr(str, '=');
  2150. if (HUSH_DEBUG && !eq_sign)
  2151. bb_error_msg_and_die("BUG in setvar");
  2152. name_len = eq_sign - str + 1; /* including '=' */
  2153. cur_pp = &G.top_var;
  2154. while ((cur = *cur_pp) != NULL) {
  2155. if (strncmp(cur->varstr, str, name_len) != 0) {
  2156. cur_pp = &cur->next;
  2157. continue;
  2158. }
  2159. /* We found an existing var with this name */
  2160. if (cur->flg_read_only) {
  2161. bb_error_msg("%s: readonly variable", str);
  2162. free(str);
  2163. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2164. //but export per se succeeds (does put the var in env). We don't mimic that.
  2165. return -1;
  2166. }
  2167. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2168. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2169. *eq_sign = '\0';
  2170. unsetenv(str);
  2171. *eq_sign = '=';
  2172. }
  2173. if (cur->var_nest_level < local_lvl) {
  2174. /* bash 3.2.33(1) and exported vars:
  2175. * # export z=z
  2176. * # f() { local z=a; env | grep ^z; }
  2177. * # f
  2178. * z=a
  2179. * # env | grep ^z
  2180. * z=z
  2181. */
  2182. if (cur->flg_export)
  2183. flags |= SETFLAG_EXPORT;
  2184. /* New variable is local ("local VAR=VAL" or
  2185. * "VAR=VAL cmd")
  2186. * and existing one is global, or local
  2187. * on a lower level that new one.
  2188. * Remove it from global variable list:
  2189. */
  2190. *cur_pp = cur->next;
  2191. if (G.shadowed_vars_pp) {
  2192. /* Save in "shadowed" list */
  2193. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2194. cur->flg_export ? "exported " : "",
  2195. cur->varstr, cur->var_nest_level, str, local_lvl
  2196. );
  2197. cur->next = *G.shadowed_vars_pp;
  2198. *G.shadowed_vars_pp = cur;
  2199. } else {
  2200. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2201. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2202. cur->flg_export ? "exported " : "",
  2203. cur->varstr, cur->var_nest_level, str, local_lvl
  2204. );
  2205. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2206. free_me = cur->varstr; /* then free it later */
  2207. free(cur);
  2208. }
  2209. break;
  2210. }
  2211. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2212. debug_printf_env("assignement '%s' does not change anything\n", str);
  2213. free_and_exp:
  2214. free(str);
  2215. goto exp;
  2216. }
  2217. /* Replace the value in the found "struct variable" */
  2218. if (cur->max_len != 0) {
  2219. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2220. /* This one is from startup env, reuse space */
  2221. debug_printf_env("reusing startup env for '%s'\n", str);
  2222. strcpy(cur->varstr, str);
  2223. goto free_and_exp;
  2224. }
  2225. /* Can't reuse */
  2226. cur->max_len = 0;
  2227. goto set_str_and_exp;
  2228. }
  2229. /* max_len == 0 signifies "malloced" var, which we can
  2230. * (and have to) free. But we can't free(cur->varstr) here:
  2231. * if cur->flg_export is 1, it is in the environment.
  2232. * We should either unsetenv+free, or wait until putenv,
  2233. * then putenv(new)+free(old).
  2234. */
  2235. free_me = cur->varstr;
  2236. goto set_str_and_exp;
  2237. }
  2238. /* Not found or shadowed - create new variable struct */
  2239. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2240. cur = xzalloc(sizeof(*cur));
  2241. cur->var_nest_level = local_lvl;
  2242. cur->next = *cur_pp;
  2243. *cur_pp = cur;
  2244. set_str_and_exp:
  2245. cur->varstr = str;
  2246. exp:
  2247. #if !BB_MMU || ENABLE_HUSH_READONLY
  2248. if (flags & SETFLAG_MAKE_RO) {
  2249. cur->flg_read_only = 1;
  2250. }
  2251. #endif
  2252. if (flags & SETFLAG_EXPORT)
  2253. cur->flg_export = 1;
  2254. retval = 0;
  2255. if (cur->flg_export) {
  2256. if (flags & SETFLAG_UNEXPORT) {
  2257. cur->flg_export = 0;
  2258. /* unsetenv was already done */
  2259. } else {
  2260. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2261. retval = putenv(cur->varstr);
  2262. /* fall through to "free(free_me)" -
  2263. * only now we can free old exported malloced string
  2264. */
  2265. }
  2266. }
  2267. free(free_me);
  2268. handle_changed_special_names(cur->varstr, name_len - 1);
  2269. return retval;
  2270. }
  2271. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2272. {
  2273. char *var = xasprintf("%s=%s", name, val);
  2274. set_local_var(var, /*flag:*/ 0);
  2275. }
  2276. /* Used at startup and after each cd */
  2277. static void set_pwd_var(unsigned flag)
  2278. {
  2279. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2280. }
  2281. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2282. static int unset_local_var_len(const char *name, int name_len)
  2283. {
  2284. struct variable *cur;
  2285. struct variable **cur_pp;
  2286. cur_pp = &G.top_var;
  2287. while ((cur = *cur_pp) != NULL) {
  2288. if (strncmp(cur->varstr, name, name_len) == 0
  2289. && cur->varstr[name_len] == '='
  2290. ) {
  2291. if (cur->flg_read_only) {
  2292. bb_error_msg("%s: readonly variable", name);
  2293. return EXIT_FAILURE;
  2294. }
  2295. *cur_pp = cur->next;
  2296. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2297. bb_unsetenv(cur->varstr);
  2298. if (!cur->max_len)
  2299. free(cur->varstr);
  2300. free(cur);
  2301. break;
  2302. }
  2303. cur_pp = &cur->next;
  2304. }
  2305. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2306. handle_changed_special_names(name, name_len);
  2307. return EXIT_SUCCESS;
  2308. }
  2309. static int unset_local_var(const char *name)
  2310. {
  2311. return unset_local_var_len(name, strlen(name));
  2312. }
  2313. #endif
  2314. /*
  2315. * Helpers for "var1=val1 var2=val2 cmd" feature
  2316. */
  2317. static void add_vars(struct variable *var)
  2318. {
  2319. struct variable *next;
  2320. while (var) {
  2321. next = var->next;
  2322. var->next = G.top_var;
  2323. G.top_var = var;
  2324. if (var->flg_export) {
  2325. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2326. putenv(var->varstr);
  2327. } else {
  2328. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2329. }
  2330. var = next;
  2331. }
  2332. }
  2333. /* We put strings[i] into variable table and possibly putenv them.
  2334. * If variable is read only, we can free the strings[i]
  2335. * which attempts to overwrite it.
  2336. * The strings[] vector itself is freed.
  2337. */
  2338. static void set_vars_and_save_old(char **strings)
  2339. {
  2340. char **s;
  2341. if (!strings)
  2342. return;
  2343. s = strings;
  2344. while (*s) {
  2345. struct variable *var_p;
  2346. struct variable **var_pp;
  2347. char *eq;
  2348. eq = strchr(*s, '=');
  2349. if (HUSH_DEBUG && !eq)
  2350. bb_error_msg_and_die("BUG in varexp4");
  2351. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2352. if (var_pp) {
  2353. var_p = *var_pp;
  2354. if (var_p->flg_read_only) {
  2355. char **p;
  2356. bb_error_msg("%s: readonly variable", *s);
  2357. /*
  2358. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2359. * If VAR is readonly, leaving it in the list
  2360. * after asssignment error (msg above)
  2361. * causes doubled error message later, on unset.
  2362. */
  2363. debug_printf_env("removing/freeing '%s' element\n", *s);
  2364. free(*s);
  2365. p = s;
  2366. do { *p = p[1]; p++; } while (*p);
  2367. goto next;
  2368. }
  2369. /* below, set_local_var() with nest level will
  2370. * "shadow" (remove) this variable from
  2371. * global linked list.
  2372. */
  2373. }
  2374. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2375. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2376. s++;
  2377. next: ;
  2378. }
  2379. free(strings);
  2380. }
  2381. /*
  2382. * Unicode helper
  2383. */
  2384. static void reinit_unicode_for_hush(void)
  2385. {
  2386. /* Unicode support should be activated even if LANG is set
  2387. * _during_ shell execution, not only if it was set when
  2388. * shell was started. Therefore, re-check LANG every time:
  2389. */
  2390. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2391. || ENABLE_UNICODE_USING_LOCALE
  2392. ) {
  2393. const char *s = get_local_var_value("LC_ALL");
  2394. if (!s) s = get_local_var_value("LC_CTYPE");
  2395. if (!s) s = get_local_var_value("LANG");
  2396. reinit_unicode(s);
  2397. }
  2398. }
  2399. /*
  2400. * in_str support (strings, and "strings" read from files).
  2401. */
  2402. #if ENABLE_HUSH_INTERACTIVE
  2403. /* To test correct lineedit/interactive behavior, type from command line:
  2404. * echo $P\
  2405. * \
  2406. * AT\
  2407. * H\
  2408. * \
  2409. * It exercises a lot of corner cases.
  2410. */
  2411. static const char *setup_prompt_string(void)
  2412. {
  2413. const char *prompt_str;
  2414. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2415. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2416. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2417. if (!prompt_str)
  2418. prompt_str = "";
  2419. # else
  2420. prompt_str = "> "; /* if PS2, else... */
  2421. if (G.promptmode == 0) { /* PS1 */
  2422. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2423. free(G.PS1);
  2424. /* bash uses $PWD value, even if it is set by user.
  2425. * It uses current dir only if PWD is unset.
  2426. * We always use current dir. */
  2427. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2428. }
  2429. # endif
  2430. debug_printf("prompt_str '%s'\n", prompt_str);
  2431. return prompt_str;
  2432. }
  2433. static int get_user_input(struct in_str *i)
  2434. {
  2435. int r;
  2436. const char *prompt_str;
  2437. prompt_str = setup_prompt_string();
  2438. # if ENABLE_FEATURE_EDITING
  2439. for (;;) {
  2440. reinit_unicode_for_hush();
  2441. if (G.flag_SIGINT) {
  2442. /* There was ^C'ed, make it look prettier: */
  2443. bb_putchar('\n');
  2444. G.flag_SIGINT = 0;
  2445. }
  2446. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2447. * only after <Enter>. (^C works immediately) */
  2448. r = read_line_input(G.line_input_state, prompt_str,
  2449. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2450. );
  2451. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2452. if (r == 0)
  2453. raise(SIGINT);
  2454. check_and_run_traps();
  2455. if (r != 0 && !G.flag_SIGINT)
  2456. break;
  2457. /* ^C or SIGINT: repeat */
  2458. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2459. write(STDOUT_FILENO, "^C", 2);
  2460. G.last_exitcode = 128 + SIGINT;
  2461. }
  2462. if (r < 0) {
  2463. /* EOF/error detected */
  2464. i->p = NULL;
  2465. i->peek_buf[0] = r = EOF;
  2466. return r;
  2467. }
  2468. i->p = G.user_input_buf;
  2469. return (unsigned char)*i->p++;
  2470. # else
  2471. for (;;) {
  2472. G.flag_SIGINT = 0;
  2473. if (i->last_char == '\0' || i->last_char == '\n') {
  2474. /* Why check_and_run_traps here? Try this interactively:
  2475. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2476. * $ <[enter], repeatedly...>
  2477. * Without check_and_run_traps, handler never runs.
  2478. */
  2479. check_and_run_traps();
  2480. fputs(prompt_str, stdout);
  2481. }
  2482. fflush_all();
  2483. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2484. r = hfgetc(i->file);
  2485. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2486. * no ^C masking happens during fgetc, no special code for ^C:
  2487. * it generates SIGINT as usual.
  2488. */
  2489. check_and_run_traps();
  2490. if (G.flag_SIGINT)
  2491. G.last_exitcode = 128 + SIGINT;
  2492. if (r != '\0')
  2493. break;
  2494. }
  2495. return r;
  2496. # endif
  2497. }
  2498. /* This is the magic location that prints prompts
  2499. * and gets data back from the user */
  2500. static int fgetc_interactive(struct in_str *i)
  2501. {
  2502. int ch;
  2503. /* If it's interactive stdin, get new line. */
  2504. if (G_interactive_fd && i->file->is_stdin) {
  2505. /* Returns first char (or EOF), the rest is in i->p[] */
  2506. ch = get_user_input(i);
  2507. G.promptmode = 1; /* PS2 */
  2508. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2509. } else {
  2510. /* Not stdin: script file, sourced file, etc */
  2511. do ch = hfgetc(i->file); while (ch == '\0');
  2512. }
  2513. return ch;
  2514. }
  2515. #else
  2516. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2517. {
  2518. int ch;
  2519. do ch = hfgetc(i->file); while (ch == '\0');
  2520. return ch;
  2521. }
  2522. #endif /* INTERACTIVE */
  2523. static int i_getch(struct in_str *i)
  2524. {
  2525. int ch;
  2526. if (!i->file) {
  2527. /* string-based in_str */
  2528. ch = (unsigned char)*i->p;
  2529. if (ch != '\0') {
  2530. i->p++;
  2531. i->last_char = ch;
  2532. return ch;
  2533. }
  2534. return EOF;
  2535. }
  2536. /* FILE-based in_str */
  2537. #if ENABLE_FEATURE_EDITING
  2538. /* This can be stdin, check line editing char[] buffer */
  2539. if (i->p && *i->p != '\0') {
  2540. ch = (unsigned char)*i->p++;
  2541. goto out;
  2542. }
  2543. #endif
  2544. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2545. ch = i->peek_buf[0];
  2546. if (ch != 0) {
  2547. int ch2 = i->peek_buf[1];
  2548. i->peek_buf[0] = ch2;
  2549. if (ch2 == 0) /* very likely, avoid redundant write */
  2550. goto out;
  2551. i->peek_buf[1] = 0;
  2552. goto out;
  2553. }
  2554. ch = fgetc_interactive(i);
  2555. out:
  2556. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2557. i->last_char = ch;
  2558. #if ENABLE_HUSH_LINENO_VAR
  2559. if (ch == '\n') {
  2560. G.parse_lineno++;
  2561. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2562. }
  2563. #endif
  2564. return ch;
  2565. }
  2566. static int i_peek(struct in_str *i)
  2567. {
  2568. int ch;
  2569. if (!i->file) {
  2570. /* string-based in_str */
  2571. /* Doesn't report EOF on NUL. None of the callers care. */
  2572. return (unsigned char)*i->p;
  2573. }
  2574. /* FILE-based in_str */
  2575. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2576. /* This can be stdin, check line editing char[] buffer */
  2577. if (i->p && *i->p != '\0')
  2578. return (unsigned char)*i->p;
  2579. #endif
  2580. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2581. ch = i->peek_buf[0];
  2582. if (ch != 0)
  2583. return ch;
  2584. /* Need to get a new char */
  2585. ch = fgetc_interactive(i);
  2586. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2587. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2588. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2589. if (i->p) {
  2590. i->p -= 1;
  2591. return ch;
  2592. }
  2593. #endif
  2594. i->peek_buf[0] = ch;
  2595. /*i->peek_buf[1] = 0; - already is */
  2596. return ch;
  2597. }
  2598. /* Only ever called if i_peek() was called, and did not return EOF.
  2599. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2600. * not end-of-line. Therefore we never need to read a new editing line here.
  2601. */
  2602. static int i_peek2(struct in_str *i)
  2603. {
  2604. int ch;
  2605. /* There are two cases when i->p[] buffer exists.
  2606. * (1) it's a string in_str.
  2607. * (2) It's a file, and we have a saved line editing buffer.
  2608. * In both cases, we know that i->p[0] exists and not NUL, and
  2609. * the peek2 result is in i->p[1].
  2610. */
  2611. if (i->p)
  2612. return (unsigned char)i->p[1];
  2613. /* Now we know it is a file-based in_str. */
  2614. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2615. /* Is there 2nd char? */
  2616. ch = i->peek_buf[1];
  2617. if (ch == 0) {
  2618. /* We did not read it yet, get it now */
  2619. do ch = hfgetc(i->file); while (ch == '\0');
  2620. i->peek_buf[1] = ch;
  2621. }
  2622. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2623. return ch;
  2624. }
  2625. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2626. {
  2627. for (;;) {
  2628. int ch, ch2;
  2629. ch = i_getch(input);
  2630. if (ch != '\\')
  2631. return ch;
  2632. ch2 = i_peek(input);
  2633. if (ch2 != '\n')
  2634. return ch;
  2635. /* backslash+newline, skip it */
  2636. i_getch(input);
  2637. }
  2638. }
  2639. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2640. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2641. */
  2642. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2643. {
  2644. for (;;) {
  2645. int ch, ch2;
  2646. ch = i_peek(input);
  2647. if (ch != '\\')
  2648. return ch;
  2649. ch2 = i_peek2(input);
  2650. if (ch2 != '\n')
  2651. return ch;
  2652. /* backslash+newline, skip it */
  2653. i_getch(input);
  2654. i_getch(input);
  2655. }
  2656. }
  2657. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2658. {
  2659. memset(i, 0, sizeof(*i));
  2660. i->file = fp;
  2661. /* i->p = NULL; */
  2662. }
  2663. static void setup_string_in_str(struct in_str *i, const char *s)
  2664. {
  2665. memset(i, 0, sizeof(*i));
  2666. /*i->file = NULL */;
  2667. i->p = s;
  2668. }
  2669. /*
  2670. * o_string support
  2671. */
  2672. #define B_CHUNK (32 * sizeof(char*))
  2673. static void o_reset_to_empty_unquoted(o_string *o)
  2674. {
  2675. o->length = 0;
  2676. o->has_quoted_part = 0;
  2677. if (o->data)
  2678. o->data[0] = '\0';
  2679. }
  2680. static void o_free_and_set_NULL(o_string *o)
  2681. {
  2682. free(o->data);
  2683. memset(o, 0, sizeof(*o));
  2684. }
  2685. static ALWAYS_INLINE void o_free(o_string *o)
  2686. {
  2687. free(o->data);
  2688. }
  2689. static void o_grow_by(o_string *o, int len)
  2690. {
  2691. if (o->length + len > o->maxlen) {
  2692. o->maxlen += (2 * len) | (B_CHUNK-1);
  2693. o->data = xrealloc(o->data, 1 + o->maxlen);
  2694. }
  2695. }
  2696. static void o_addchr(o_string *o, int ch)
  2697. {
  2698. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2699. if (o->length < o->maxlen) {
  2700. /* likely. avoid o_grow_by() call */
  2701. add:
  2702. o->data[o->length] = ch;
  2703. o->length++;
  2704. o->data[o->length] = '\0';
  2705. return;
  2706. }
  2707. o_grow_by(o, 1);
  2708. goto add;
  2709. }
  2710. #if 0
  2711. /* Valid only if we know o_string is not empty */
  2712. static void o_delchr(o_string *o)
  2713. {
  2714. o->length--;
  2715. o->data[o->length] = '\0';
  2716. }
  2717. #endif
  2718. static void o_addblock(o_string *o, const char *str, int len)
  2719. {
  2720. o_grow_by(o, len);
  2721. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2722. o->length += len;
  2723. }
  2724. static void o_addstr(o_string *o, const char *str)
  2725. {
  2726. o_addblock(o, str, strlen(str));
  2727. }
  2728. static void o_addstr_with_NUL(o_string *o, const char *str)
  2729. {
  2730. o_addblock(o, str, strlen(str) + 1);
  2731. }
  2732. #if !BB_MMU
  2733. static void nommu_addchr(o_string *o, int ch)
  2734. {
  2735. if (o)
  2736. o_addchr(o, ch);
  2737. }
  2738. #else
  2739. # define nommu_addchr(o, str) ((void)0)
  2740. #endif
  2741. #if ENABLE_HUSH_MODE_X
  2742. static void x_mode_addchr(int ch)
  2743. {
  2744. o_addchr(&G.x_mode_buf, ch);
  2745. }
  2746. static void x_mode_addstr(const char *str)
  2747. {
  2748. o_addstr(&G.x_mode_buf, str);
  2749. }
  2750. static void x_mode_addblock(const char *str, int len)
  2751. {
  2752. o_addblock(&G.x_mode_buf, str, len);
  2753. }
  2754. static void x_mode_prefix(void)
  2755. {
  2756. int n = G.x_mode_depth;
  2757. do x_mode_addchr('+'); while (--n >= 0);
  2758. }
  2759. static void x_mode_flush(void)
  2760. {
  2761. int len = G.x_mode_buf.length;
  2762. if (len <= 0)
  2763. return;
  2764. if (G.x_mode_fd > 0) {
  2765. G.x_mode_buf.data[len] = '\n';
  2766. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2767. }
  2768. G.x_mode_buf.length = 0;
  2769. }
  2770. #endif
  2771. /*
  2772. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2773. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2774. * Apparently, on unquoted $v bash still does globbing
  2775. * ("v='*.txt'; echo $v" prints all .txt files),
  2776. * but NOT brace expansion! Thus, there should be TWO independent
  2777. * quoting mechanisms on $v expansion side: one protects
  2778. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2779. * We have only second one.
  2780. */
  2781. #if ENABLE_HUSH_BRACE_EXPANSION
  2782. # define MAYBE_BRACES "{}"
  2783. #else
  2784. # define MAYBE_BRACES ""
  2785. #endif
  2786. /* My analysis of quoting semantics tells me that state information
  2787. * is associated with a destination, not a source.
  2788. */
  2789. static void o_addqchr(o_string *o, int ch)
  2790. {
  2791. int sz = 1;
  2792. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2793. if (found)
  2794. sz++;
  2795. o_grow_by(o, sz);
  2796. if (found) {
  2797. o->data[o->length] = '\\';
  2798. o->length++;
  2799. }
  2800. o->data[o->length] = ch;
  2801. o->length++;
  2802. o->data[o->length] = '\0';
  2803. }
  2804. static void o_addQchr(o_string *o, int ch)
  2805. {
  2806. int sz = 1;
  2807. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2808. && strchr("*?[\\" MAYBE_BRACES, ch)
  2809. ) {
  2810. sz++;
  2811. o->data[o->length] = '\\';
  2812. o->length++;
  2813. }
  2814. o_grow_by(o, sz);
  2815. o->data[o->length] = ch;
  2816. o->length++;
  2817. o->data[o->length] = '\0';
  2818. }
  2819. static void o_addqblock(o_string *o, const char *str, int len)
  2820. {
  2821. while (len) {
  2822. char ch;
  2823. int sz;
  2824. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2825. if (ordinary_cnt > len) /* paranoia */
  2826. ordinary_cnt = len;
  2827. o_addblock(o, str, ordinary_cnt);
  2828. if (ordinary_cnt == len)
  2829. return; /* NUL is already added by o_addblock */
  2830. str += ordinary_cnt;
  2831. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2832. ch = *str++;
  2833. sz = 1;
  2834. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2835. sz++;
  2836. o->data[o->length] = '\\';
  2837. o->length++;
  2838. }
  2839. o_grow_by(o, sz);
  2840. o->data[o->length] = ch;
  2841. o->length++;
  2842. }
  2843. o->data[o->length] = '\0';
  2844. }
  2845. static void o_addQblock(o_string *o, const char *str, int len)
  2846. {
  2847. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2848. o_addblock(o, str, len);
  2849. return;
  2850. }
  2851. o_addqblock(o, str, len);
  2852. }
  2853. static void o_addQstr(o_string *o, const char *str)
  2854. {
  2855. o_addQblock(o, str, strlen(str));
  2856. }
  2857. /* A special kind of o_string for $VAR and `cmd` expansion.
  2858. * It contains char* list[] at the beginning, which is grown in 16 element
  2859. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2860. * list[i] contains an INDEX (int!) into this string data.
  2861. * It means that if list[] needs to grow, data needs to be moved higher up
  2862. * but list[i]'s need not be modified.
  2863. * NB: remembering how many list[i]'s you have there is crucial.
  2864. * o_finalize_list() operation post-processes this structure - calculates
  2865. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2866. */
  2867. #if DEBUG_EXPAND || DEBUG_GLOB
  2868. static void debug_print_list(const char *prefix, o_string *o, int n)
  2869. {
  2870. char **list = (char**)o->data;
  2871. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2872. int i = 0;
  2873. indent();
  2874. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2875. prefix, list, n, string_start, o->length, o->maxlen,
  2876. !!(o->o_expflags & EXP_FLAG_GLOB),
  2877. o->has_quoted_part,
  2878. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2879. while (i < n) {
  2880. indent();
  2881. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2882. o->data + (int)(uintptr_t)list[i] + string_start,
  2883. o->data + (int)(uintptr_t)list[i] + string_start);
  2884. i++;
  2885. }
  2886. if (n) {
  2887. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2888. indent();
  2889. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2890. }
  2891. }
  2892. #else
  2893. # define debug_print_list(prefix, o, n) ((void)0)
  2894. #endif
  2895. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2896. * in list[n] so that it points past last stored byte so far.
  2897. * It returns n+1. */
  2898. static int o_save_ptr_helper(o_string *o, int n)
  2899. {
  2900. char **list = (char**)o->data;
  2901. int string_start;
  2902. int string_len;
  2903. if (!o->has_empty_slot) {
  2904. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2905. string_len = o->length - string_start;
  2906. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2907. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2908. /* list[n] points to string_start, make space for 16 more pointers */
  2909. o->maxlen += 0x10 * sizeof(list[0]);
  2910. o->data = xrealloc(o->data, o->maxlen + 1);
  2911. list = (char**)o->data;
  2912. memmove(list + n + 0x10, list + n, string_len);
  2913. /*
  2914. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2915. * check. (grep for -prev-ifs-check-).
  2916. * Ensure that argv[-1][last] is not garbage
  2917. * but zero bytes, to save index check there.
  2918. */
  2919. list[n + 0x10 - 1] = 0;
  2920. o->length += 0x10 * sizeof(list[0]);
  2921. } else {
  2922. debug_printf_list("list[%d]=%d string_start=%d\n",
  2923. n, string_len, string_start);
  2924. }
  2925. } else {
  2926. /* We have empty slot at list[n], reuse without growth */
  2927. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2928. string_len = o->length - string_start;
  2929. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2930. n, string_len, string_start);
  2931. o->has_empty_slot = 0;
  2932. }
  2933. o->has_quoted_part = 0;
  2934. list[n] = (char*)(uintptr_t)string_len;
  2935. return n + 1;
  2936. }
  2937. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2938. static int o_get_last_ptr(o_string *o, int n)
  2939. {
  2940. char **list = (char**)o->data;
  2941. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2942. return ((int)(uintptr_t)list[n-1]) + string_start;
  2943. }
  2944. /*
  2945. * Globbing routines.
  2946. *
  2947. * Most words in commands need to be globbed, even ones which are
  2948. * (single or double) quoted. This stems from the possiblity of
  2949. * constructs like "abc"* and 'abc'* - these should be globbed.
  2950. * Having a different code path for fully-quoted strings ("abc",
  2951. * 'abc') would only help performance-wise, but we still need
  2952. * code for partially-quoted strings.
  2953. *
  2954. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2955. * the logic can't be "shell-syntax argument is first transformed
  2956. * to a string, then globbed, and if globbing does not match anything,
  2957. * it is used verbatim". Here are two examples where it fails:
  2958. *
  2959. * echo 'b\*'?
  2960. *
  2961. * The globbing can't be avoided (because of '?' at the end).
  2962. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2963. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2964. * - IOW: they "unbackslash" the glob pattern.
  2965. * Now, look at this:
  2966. *
  2967. * v='\\\*'; echo b$v?
  2968. *
  2969. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2970. * should be used as glob pattern with no changes. However, if glob
  2971. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2972. *
  2973. * ash implements this by having an encoded representation of the word
  2974. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2975. * Glob pattern is derived from it. If glob fails, the decision what result
  2976. * should be is made using that encoded representation. Not glob pattern.
  2977. */
  2978. #if ENABLE_HUSH_BRACE_EXPANSION
  2979. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2980. * first, it processes even {a} (no commas), second,
  2981. * I didn't manage to make it return strings when they don't match
  2982. * existing files. Need to re-implement it.
  2983. */
  2984. /* Helper */
  2985. static int glob_needed(const char *s)
  2986. {
  2987. while (*s) {
  2988. if (*s == '\\') {
  2989. if (!s[1])
  2990. return 0;
  2991. s += 2;
  2992. continue;
  2993. }
  2994. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2995. return 1;
  2996. s++;
  2997. }
  2998. return 0;
  2999. }
  3000. /* Return pointer to next closing brace or to comma */
  3001. static const char *next_brace_sub(const char *cp)
  3002. {
  3003. unsigned depth = 0;
  3004. cp++;
  3005. while (*cp != '\0') {
  3006. if (*cp == '\\') {
  3007. if (*++cp == '\0')
  3008. break;
  3009. cp++;
  3010. continue;
  3011. }
  3012. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3013. break;
  3014. if (*cp++ == '{')
  3015. depth++;
  3016. }
  3017. return *cp != '\0' ? cp : NULL;
  3018. }
  3019. /* Recursive brace globber. Note: may garble pattern[]. */
  3020. static int glob_brace(char *pattern, o_string *o, int n)
  3021. {
  3022. char *new_pattern_buf;
  3023. const char *begin;
  3024. const char *next;
  3025. const char *rest;
  3026. const char *p;
  3027. size_t rest_len;
  3028. debug_printf_glob("glob_brace('%s')\n", pattern);
  3029. begin = pattern;
  3030. while (1) {
  3031. if (*begin == '\0')
  3032. goto simple_glob;
  3033. if (*begin == '{') {
  3034. /* Find the first sub-pattern and at the same time
  3035. * find the rest after the closing brace */
  3036. next = next_brace_sub(begin);
  3037. if (next == NULL) {
  3038. /* An illegal expression */
  3039. goto simple_glob;
  3040. }
  3041. if (*next == '}') {
  3042. /* "{abc}" with no commas - illegal
  3043. * brace expr, disregard and skip it */
  3044. begin = next + 1;
  3045. continue;
  3046. }
  3047. break;
  3048. }
  3049. if (*begin == '\\' && begin[1] != '\0')
  3050. begin++;
  3051. begin++;
  3052. }
  3053. debug_printf_glob("begin:%s\n", begin);
  3054. debug_printf_glob("next:%s\n", next);
  3055. /* Now find the end of the whole brace expression */
  3056. rest = next;
  3057. while (*rest != '}') {
  3058. rest = next_brace_sub(rest);
  3059. if (rest == NULL) {
  3060. /* An illegal expression */
  3061. goto simple_glob;
  3062. }
  3063. debug_printf_glob("rest:%s\n", rest);
  3064. }
  3065. rest_len = strlen(++rest) + 1;
  3066. /* We are sure the brace expression is well-formed */
  3067. /* Allocate working buffer large enough for our work */
  3068. new_pattern_buf = xmalloc(strlen(pattern));
  3069. /* We have a brace expression. BEGIN points to the opening {,
  3070. * NEXT points past the terminator of the first element, and REST
  3071. * points past the final }. We will accumulate result names from
  3072. * recursive runs for each brace alternative in the buffer using
  3073. * GLOB_APPEND. */
  3074. p = begin + 1;
  3075. while (1) {
  3076. /* Construct the new glob expression */
  3077. memcpy(
  3078. mempcpy(
  3079. mempcpy(new_pattern_buf,
  3080. /* We know the prefix for all sub-patterns */
  3081. pattern, begin - pattern),
  3082. p, next - p),
  3083. rest, rest_len);
  3084. /* Note: glob_brace() may garble new_pattern_buf[].
  3085. * That's why we re-copy prefix every time (1st memcpy above).
  3086. */
  3087. n = glob_brace(new_pattern_buf, o, n);
  3088. if (*next == '}') {
  3089. /* We saw the last entry */
  3090. break;
  3091. }
  3092. p = next + 1;
  3093. next = next_brace_sub(next);
  3094. }
  3095. free(new_pattern_buf);
  3096. return n;
  3097. simple_glob:
  3098. {
  3099. int gr;
  3100. glob_t globdata;
  3101. memset(&globdata, 0, sizeof(globdata));
  3102. gr = glob(pattern, 0, NULL, &globdata);
  3103. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3104. if (gr != 0) {
  3105. if (gr == GLOB_NOMATCH) {
  3106. globfree(&globdata);
  3107. /* NB: garbles parameter */
  3108. unbackslash(pattern);
  3109. o_addstr_with_NUL(o, pattern);
  3110. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3111. return o_save_ptr_helper(o, n);
  3112. }
  3113. if (gr == GLOB_NOSPACE)
  3114. bb_die_memory_exhausted();
  3115. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3116. * but we didn't specify it. Paranoia again. */
  3117. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3118. }
  3119. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3120. char **argv = globdata.gl_pathv;
  3121. while (1) {
  3122. o_addstr_with_NUL(o, *argv);
  3123. n = o_save_ptr_helper(o, n);
  3124. argv++;
  3125. if (!*argv)
  3126. break;
  3127. }
  3128. }
  3129. globfree(&globdata);
  3130. }
  3131. return n;
  3132. }
  3133. /* Performs globbing on last list[],
  3134. * saving each result as a new list[].
  3135. */
  3136. static int perform_glob(o_string *o, int n)
  3137. {
  3138. char *pattern, *copy;
  3139. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3140. if (!o->data)
  3141. return o_save_ptr_helper(o, n);
  3142. pattern = o->data + o_get_last_ptr(o, n);
  3143. debug_printf_glob("glob pattern '%s'\n", pattern);
  3144. if (!glob_needed(pattern)) {
  3145. /* unbackslash last string in o in place, fix length */
  3146. o->length = unbackslash(pattern) - o->data;
  3147. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3148. return o_save_ptr_helper(o, n);
  3149. }
  3150. copy = xstrdup(pattern);
  3151. /* "forget" pattern in o */
  3152. o->length = pattern - o->data;
  3153. n = glob_brace(copy, o, n);
  3154. free(copy);
  3155. if (DEBUG_GLOB)
  3156. debug_print_list("perform_glob returning", o, n);
  3157. return n;
  3158. }
  3159. #else /* !HUSH_BRACE_EXPANSION */
  3160. /* Helper */
  3161. static int glob_needed(const char *s)
  3162. {
  3163. while (*s) {
  3164. if (*s == '\\') {
  3165. if (!s[1])
  3166. return 0;
  3167. s += 2;
  3168. continue;
  3169. }
  3170. if (*s == '*' || *s == '[' || *s == '?')
  3171. return 1;
  3172. s++;
  3173. }
  3174. return 0;
  3175. }
  3176. /* Performs globbing on last list[],
  3177. * saving each result as a new list[].
  3178. */
  3179. static int perform_glob(o_string *o, int n)
  3180. {
  3181. glob_t globdata;
  3182. int gr;
  3183. char *pattern;
  3184. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3185. if (!o->data)
  3186. return o_save_ptr_helper(o, n);
  3187. pattern = o->data + o_get_last_ptr(o, n);
  3188. debug_printf_glob("glob pattern '%s'\n", pattern);
  3189. if (!glob_needed(pattern)) {
  3190. literal:
  3191. /* unbackslash last string in o in place, fix length */
  3192. o->length = unbackslash(pattern) - o->data;
  3193. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3194. return o_save_ptr_helper(o, n);
  3195. }
  3196. memset(&globdata, 0, sizeof(globdata));
  3197. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3198. * If we glob "*.\*" and don't find anything, we need
  3199. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3200. * will return "*.\*"!
  3201. */
  3202. gr = glob(pattern, 0, NULL, &globdata);
  3203. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3204. if (gr != 0) {
  3205. if (gr == GLOB_NOMATCH) {
  3206. globfree(&globdata);
  3207. goto literal;
  3208. }
  3209. if (gr == GLOB_NOSPACE)
  3210. bb_die_memory_exhausted();
  3211. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3212. * but we didn't specify it. Paranoia again. */
  3213. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3214. }
  3215. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3216. char **argv = globdata.gl_pathv;
  3217. /* "forget" pattern in o */
  3218. o->length = pattern - o->data;
  3219. while (1) {
  3220. o_addstr_with_NUL(o, *argv);
  3221. n = o_save_ptr_helper(o, n);
  3222. argv++;
  3223. if (!*argv)
  3224. break;
  3225. }
  3226. }
  3227. globfree(&globdata);
  3228. if (DEBUG_GLOB)
  3229. debug_print_list("perform_glob returning", o, n);
  3230. return n;
  3231. }
  3232. #endif /* !HUSH_BRACE_EXPANSION */
  3233. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3234. * Otherwise, just finish current list[] and start new */
  3235. static int o_save_ptr(o_string *o, int n)
  3236. {
  3237. if (o->o_expflags & EXP_FLAG_GLOB) {
  3238. /* If o->has_empty_slot, list[n] was already globbed
  3239. * (if it was requested back then when it was filled)
  3240. * so don't do that again! */
  3241. if (!o->has_empty_slot)
  3242. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3243. }
  3244. return o_save_ptr_helper(o, n);
  3245. }
  3246. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3247. static char **o_finalize_list(o_string *o, int n)
  3248. {
  3249. char **list;
  3250. int string_start;
  3251. if (DEBUG_EXPAND)
  3252. debug_print_list("finalized", o, n);
  3253. debug_printf_expand("finalized n:%d\n", n);
  3254. list = (char**)o->data;
  3255. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3256. list[--n] = NULL;
  3257. while (n) {
  3258. n--;
  3259. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3260. }
  3261. return list;
  3262. }
  3263. static void free_pipe_list(struct pipe *pi);
  3264. /* Returns pi->next - next pipe in the list */
  3265. static struct pipe *free_pipe(struct pipe *pi)
  3266. {
  3267. struct pipe *next;
  3268. int i;
  3269. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3270. for (i = 0; i < pi->num_cmds; i++) {
  3271. struct command *command;
  3272. struct redir_struct *r, *rnext;
  3273. command = &pi->cmds[i];
  3274. debug_printf_clean(" command %d:\n", i);
  3275. if (command->argv) {
  3276. if (DEBUG_CLEAN) {
  3277. int a;
  3278. char **p;
  3279. for (a = 0, p = command->argv; *p; a++, p++) {
  3280. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3281. }
  3282. }
  3283. free_strings(command->argv);
  3284. //command->argv = NULL;
  3285. }
  3286. /* not "else if": on syntax error, we may have both! */
  3287. if (command->group) {
  3288. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3289. command->cmd_type);
  3290. free_pipe_list(command->group);
  3291. debug_printf_clean(" end group\n");
  3292. //command->group = NULL;
  3293. }
  3294. /* else is crucial here.
  3295. * If group != NULL, child_func is meaningless */
  3296. #if ENABLE_HUSH_FUNCTIONS
  3297. else if (command->child_func) {
  3298. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3299. command->child_func->parent_cmd = NULL;
  3300. }
  3301. #endif
  3302. #if !BB_MMU
  3303. free(command->group_as_string);
  3304. //command->group_as_string = NULL;
  3305. #endif
  3306. for (r = command->redirects; r; r = rnext) {
  3307. debug_printf_clean(" redirect %d%s",
  3308. r->rd_fd, redir_table[r->rd_type].descrip);
  3309. /* guard against the case >$FOO, where foo is unset or blank */
  3310. if (r->rd_filename) {
  3311. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3312. free(r->rd_filename);
  3313. //r->rd_filename = NULL;
  3314. }
  3315. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3316. rnext = r->next;
  3317. free(r);
  3318. }
  3319. //command->redirects = NULL;
  3320. }
  3321. free(pi->cmds); /* children are an array, they get freed all at once */
  3322. //pi->cmds = NULL;
  3323. #if ENABLE_HUSH_JOB
  3324. free(pi->cmdtext);
  3325. //pi->cmdtext = NULL;
  3326. #endif
  3327. next = pi->next;
  3328. free(pi);
  3329. return next;
  3330. }
  3331. static void free_pipe_list(struct pipe *pi)
  3332. {
  3333. while (pi) {
  3334. #if HAS_KEYWORDS
  3335. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3336. #endif
  3337. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3338. pi = free_pipe(pi);
  3339. }
  3340. }
  3341. /*** Parsing routines ***/
  3342. #ifndef debug_print_tree
  3343. static void debug_print_tree(struct pipe *pi, int lvl)
  3344. {
  3345. static const char *const PIPE[] = {
  3346. [PIPE_SEQ] = "SEQ",
  3347. [PIPE_AND] = "AND",
  3348. [PIPE_OR ] = "OR" ,
  3349. [PIPE_BG ] = "BG" ,
  3350. };
  3351. static const char *RES[] = {
  3352. [RES_NONE ] = "NONE" ,
  3353. # if ENABLE_HUSH_IF
  3354. [RES_IF ] = "IF" ,
  3355. [RES_THEN ] = "THEN" ,
  3356. [RES_ELIF ] = "ELIF" ,
  3357. [RES_ELSE ] = "ELSE" ,
  3358. [RES_FI ] = "FI" ,
  3359. # endif
  3360. # if ENABLE_HUSH_LOOPS
  3361. [RES_FOR ] = "FOR" ,
  3362. [RES_WHILE] = "WHILE",
  3363. [RES_UNTIL] = "UNTIL",
  3364. [RES_DO ] = "DO" ,
  3365. [RES_DONE ] = "DONE" ,
  3366. # endif
  3367. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3368. [RES_IN ] = "IN" ,
  3369. # endif
  3370. # if ENABLE_HUSH_CASE
  3371. [RES_CASE ] = "CASE" ,
  3372. [RES_CASE_IN ] = "CASE_IN" ,
  3373. [RES_MATCH] = "MATCH",
  3374. [RES_CASE_BODY] = "CASE_BODY",
  3375. [RES_ESAC ] = "ESAC" ,
  3376. # endif
  3377. [RES_XXXX ] = "XXXX" ,
  3378. [RES_SNTX ] = "SNTX" ,
  3379. };
  3380. static const char *const CMDTYPE[] = {
  3381. "{}",
  3382. "()",
  3383. "[noglob]",
  3384. # if ENABLE_HUSH_FUNCTIONS
  3385. "func()",
  3386. # endif
  3387. };
  3388. int pin, prn;
  3389. pin = 0;
  3390. while (pi) {
  3391. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3392. lvl*2, "",
  3393. pin,
  3394. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3395. RES[pi->res_word],
  3396. pi->followup, PIPE[pi->followup]
  3397. );
  3398. prn = 0;
  3399. while (prn < pi->num_cmds) {
  3400. struct command *command = &pi->cmds[prn];
  3401. char **argv = command->argv;
  3402. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3403. lvl*2, "", prn,
  3404. command->assignment_cnt);
  3405. #if ENABLE_HUSH_LINENO_VAR
  3406. fdprintf(2, " LINENO:%u", command->lineno);
  3407. #endif
  3408. if (command->group) {
  3409. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3410. CMDTYPE[command->cmd_type],
  3411. argv
  3412. # if !BB_MMU
  3413. , " group_as_string:", command->group_as_string
  3414. # else
  3415. , "", ""
  3416. # endif
  3417. );
  3418. debug_print_tree(command->group, lvl+1);
  3419. prn++;
  3420. continue;
  3421. }
  3422. if (argv) while (*argv) {
  3423. fdprintf(2, " '%s'", *argv);
  3424. argv++;
  3425. }
  3426. if (command->redirects)
  3427. fdprintf(2, " {redir}");
  3428. fdprintf(2, "\n");
  3429. prn++;
  3430. }
  3431. pi = pi->next;
  3432. pin++;
  3433. }
  3434. }
  3435. #endif /* debug_print_tree */
  3436. static struct pipe *new_pipe(void)
  3437. {
  3438. struct pipe *pi;
  3439. pi = xzalloc(sizeof(struct pipe));
  3440. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3441. return pi;
  3442. }
  3443. /* Command (member of a pipe) is complete, or we start a new pipe
  3444. * if ctx->command is NULL.
  3445. * No errors possible here.
  3446. */
  3447. static int done_command(struct parse_context *ctx)
  3448. {
  3449. /* The command is really already in the pipe structure, so
  3450. * advance the pipe counter and make a new, null command. */
  3451. struct pipe *pi = ctx->pipe;
  3452. struct command *command = ctx->command;
  3453. #if 0 /* Instead we emit error message at run time */
  3454. if (ctx->pending_redirect) {
  3455. /* For example, "cmd >" (no filename to redirect to) */
  3456. syntax_error("invalid redirect");
  3457. ctx->pending_redirect = NULL;
  3458. }
  3459. #endif
  3460. if (command) {
  3461. if (IS_NULL_CMD(command)) {
  3462. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3463. goto clear_and_ret;
  3464. }
  3465. pi->num_cmds++;
  3466. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3467. //debug_print_tree(ctx->list_head, 20);
  3468. } else {
  3469. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3470. }
  3471. /* Only real trickiness here is that the uncommitted
  3472. * command structure is not counted in pi->num_cmds. */
  3473. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3474. ctx->command = command = &pi->cmds[pi->num_cmds];
  3475. clear_and_ret:
  3476. memset(command, 0, sizeof(*command));
  3477. #if ENABLE_HUSH_LINENO_VAR
  3478. command->lineno = G.parse_lineno;
  3479. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3480. #endif
  3481. return pi->num_cmds; /* used only for 0/nonzero check */
  3482. }
  3483. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3484. {
  3485. int not_null;
  3486. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3487. /* Close previous command */
  3488. not_null = done_command(ctx);
  3489. #if HAS_KEYWORDS
  3490. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3491. ctx->ctx_inverted = 0;
  3492. ctx->pipe->res_word = ctx->ctx_res_w;
  3493. #endif
  3494. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3495. /* Necessary since && and || have precedence over &:
  3496. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3497. * in a backgrounded subshell.
  3498. */
  3499. struct pipe *pi;
  3500. struct command *command;
  3501. /* Is this actually this construct, all pipes end with && or ||? */
  3502. pi = ctx->list_head;
  3503. while (pi != ctx->pipe) {
  3504. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3505. goto no_conv;
  3506. pi = pi->next;
  3507. }
  3508. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3509. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3510. pi = xzalloc(sizeof(*pi));
  3511. pi->followup = PIPE_BG;
  3512. pi->num_cmds = 1;
  3513. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3514. command = &pi->cmds[0];
  3515. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3516. command->cmd_type = CMD_NORMAL;
  3517. command->group = ctx->list_head;
  3518. #if !BB_MMU
  3519. command->group_as_string = xstrndup(
  3520. ctx->as_string.data,
  3521. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3522. );
  3523. #endif
  3524. /* Replace all pipes in ctx with one newly created */
  3525. ctx->list_head = ctx->pipe = pi;
  3526. } else {
  3527. no_conv:
  3528. ctx->pipe->followup = type;
  3529. }
  3530. /* Without this check, even just <enter> on command line generates
  3531. * tree of three NOPs (!). Which is harmless but annoying.
  3532. * IOW: it is safe to do it unconditionally. */
  3533. if (not_null
  3534. #if ENABLE_HUSH_IF
  3535. || ctx->ctx_res_w == RES_FI
  3536. #endif
  3537. #if ENABLE_HUSH_LOOPS
  3538. || ctx->ctx_res_w == RES_DONE
  3539. || ctx->ctx_res_w == RES_FOR
  3540. || ctx->ctx_res_w == RES_IN
  3541. #endif
  3542. #if ENABLE_HUSH_CASE
  3543. || ctx->ctx_res_w == RES_ESAC
  3544. #endif
  3545. ) {
  3546. struct pipe *new_p;
  3547. debug_printf_parse("done_pipe: adding new pipe: "
  3548. "not_null:%d ctx->ctx_res_w:%d\n",
  3549. not_null, ctx->ctx_res_w);
  3550. new_p = new_pipe();
  3551. ctx->pipe->next = new_p;
  3552. ctx->pipe = new_p;
  3553. /* RES_THEN, RES_DO etc are "sticky" -
  3554. * they remain set for pipes inside if/while.
  3555. * This is used to control execution.
  3556. * RES_FOR and RES_IN are NOT sticky (needed to support
  3557. * cases where variable or value happens to match a keyword):
  3558. */
  3559. #if ENABLE_HUSH_LOOPS
  3560. if (ctx->ctx_res_w == RES_FOR
  3561. || ctx->ctx_res_w == RES_IN)
  3562. ctx->ctx_res_w = RES_NONE;
  3563. #endif
  3564. #if ENABLE_HUSH_CASE
  3565. if (ctx->ctx_res_w == RES_MATCH)
  3566. ctx->ctx_res_w = RES_CASE_BODY;
  3567. if (ctx->ctx_res_w == RES_CASE)
  3568. ctx->ctx_res_w = RES_CASE_IN;
  3569. #endif
  3570. ctx->command = NULL; /* trick done_command below */
  3571. /* Create the memory for command, roughly:
  3572. * ctx->pipe->cmds = new struct command;
  3573. * ctx->command = &ctx->pipe->cmds[0];
  3574. */
  3575. done_command(ctx);
  3576. //debug_print_tree(ctx->list_head, 10);
  3577. }
  3578. debug_printf_parse("done_pipe return\n");
  3579. }
  3580. static void initialize_context(struct parse_context *ctx)
  3581. {
  3582. memset(ctx, 0, sizeof(*ctx));
  3583. if (MAYBE_ASSIGNMENT != 0)
  3584. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3585. ctx->pipe = ctx->list_head = new_pipe();
  3586. /* Create the memory for command, roughly:
  3587. * ctx->pipe->cmds = new struct command;
  3588. * ctx->command = &ctx->pipe->cmds[0];
  3589. */
  3590. done_command(ctx);
  3591. }
  3592. /* If a reserved word is found and processed, parse context is modified
  3593. * and 1 is returned.
  3594. */
  3595. #if HAS_KEYWORDS
  3596. struct reserved_combo {
  3597. char literal[6];
  3598. unsigned char res;
  3599. unsigned char assignment_flag;
  3600. int flag;
  3601. };
  3602. enum {
  3603. FLAG_END = (1 << RES_NONE ),
  3604. # if ENABLE_HUSH_IF
  3605. FLAG_IF = (1 << RES_IF ),
  3606. FLAG_THEN = (1 << RES_THEN ),
  3607. FLAG_ELIF = (1 << RES_ELIF ),
  3608. FLAG_ELSE = (1 << RES_ELSE ),
  3609. FLAG_FI = (1 << RES_FI ),
  3610. # endif
  3611. # if ENABLE_HUSH_LOOPS
  3612. FLAG_FOR = (1 << RES_FOR ),
  3613. FLAG_WHILE = (1 << RES_WHILE),
  3614. FLAG_UNTIL = (1 << RES_UNTIL),
  3615. FLAG_DO = (1 << RES_DO ),
  3616. FLAG_DONE = (1 << RES_DONE ),
  3617. FLAG_IN = (1 << RES_IN ),
  3618. # endif
  3619. # if ENABLE_HUSH_CASE
  3620. FLAG_MATCH = (1 << RES_MATCH),
  3621. FLAG_ESAC = (1 << RES_ESAC ),
  3622. # endif
  3623. FLAG_START = (1 << RES_XXXX ),
  3624. };
  3625. static const struct reserved_combo* match_reserved_word(o_string *word)
  3626. {
  3627. /* Mostly a list of accepted follow-up reserved words.
  3628. * FLAG_END means we are done with the sequence, and are ready
  3629. * to turn the compound list into a command.
  3630. * FLAG_START means the word must start a new compound list.
  3631. */
  3632. static const struct reserved_combo reserved_list[] = {
  3633. # if ENABLE_HUSH_IF
  3634. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3635. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3636. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3637. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3638. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3639. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3640. # endif
  3641. # if ENABLE_HUSH_LOOPS
  3642. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3643. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3644. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3645. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3646. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3647. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3648. # endif
  3649. # if ENABLE_HUSH_CASE
  3650. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3651. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3652. # endif
  3653. };
  3654. const struct reserved_combo *r;
  3655. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3656. if (strcmp(word->data, r->literal) == 0)
  3657. return r;
  3658. }
  3659. return NULL;
  3660. }
  3661. /* Return NULL: not a keyword, else: keyword
  3662. */
  3663. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3664. {
  3665. # if ENABLE_HUSH_CASE
  3666. static const struct reserved_combo reserved_match = {
  3667. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3668. };
  3669. # endif
  3670. const struct reserved_combo *r;
  3671. if (ctx->word.has_quoted_part)
  3672. return 0;
  3673. r = match_reserved_word(&ctx->word);
  3674. if (!r)
  3675. return r; /* NULL */
  3676. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3677. # if ENABLE_HUSH_CASE
  3678. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3679. /* "case word IN ..." - IN part starts first MATCH part */
  3680. r = &reserved_match;
  3681. } else
  3682. # endif
  3683. if (r->flag == 0) { /* '!' */
  3684. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3685. syntax_error("! ! command");
  3686. ctx->ctx_res_w = RES_SNTX;
  3687. }
  3688. ctx->ctx_inverted = 1;
  3689. return r;
  3690. }
  3691. if (r->flag & FLAG_START) {
  3692. struct parse_context *old;
  3693. old = xmemdup(ctx, sizeof(*ctx));
  3694. debug_printf_parse("push stack %p\n", old);
  3695. initialize_context(ctx);
  3696. ctx->stack = old;
  3697. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3698. syntax_error_at(ctx->word.data);
  3699. ctx->ctx_res_w = RES_SNTX;
  3700. return r;
  3701. } else {
  3702. /* "{...} fi" is ok. "{...} if" is not
  3703. * Example:
  3704. * if { echo foo; } then { echo bar; } fi */
  3705. if (ctx->command->group)
  3706. done_pipe(ctx, PIPE_SEQ);
  3707. }
  3708. ctx->ctx_res_w = r->res;
  3709. ctx->old_flag = r->flag;
  3710. ctx->is_assignment = r->assignment_flag;
  3711. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3712. if (ctx->old_flag & FLAG_END) {
  3713. struct parse_context *old;
  3714. done_pipe(ctx, PIPE_SEQ);
  3715. debug_printf_parse("pop stack %p\n", ctx->stack);
  3716. old = ctx->stack;
  3717. old->command->group = ctx->list_head;
  3718. old->command->cmd_type = CMD_NORMAL;
  3719. # if !BB_MMU
  3720. /* At this point, the compound command's string is in
  3721. * ctx->as_string... except for the leading keyword!
  3722. * Consider this example: "echo a | if true; then echo a; fi"
  3723. * ctx->as_string will contain "true; then echo a; fi",
  3724. * with "if " remaining in old->as_string!
  3725. */
  3726. {
  3727. char *str;
  3728. int len = old->as_string.length;
  3729. /* Concatenate halves */
  3730. o_addstr(&old->as_string, ctx->as_string.data);
  3731. o_free(&ctx->as_string);
  3732. /* Find where leading keyword starts in first half */
  3733. str = old->as_string.data + len;
  3734. if (str > old->as_string.data)
  3735. str--; /* skip whitespace after keyword */
  3736. while (str > old->as_string.data && isalpha(str[-1]))
  3737. str--;
  3738. /* Ugh, we're done with this horrid hack */
  3739. old->command->group_as_string = xstrdup(str);
  3740. debug_printf_parse("pop, remembering as:'%s'\n",
  3741. old->command->group_as_string);
  3742. }
  3743. # endif
  3744. *ctx = *old; /* physical copy */
  3745. free(old);
  3746. }
  3747. return r;
  3748. }
  3749. #endif /* HAS_KEYWORDS */
  3750. /* Word is complete, look at it and update parsing context.
  3751. * Normal return is 0. Syntax errors return 1.
  3752. * Note: on return, word is reset, but not o_free'd!
  3753. */
  3754. static int done_word(struct parse_context *ctx)
  3755. {
  3756. struct command *command = ctx->command;
  3757. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3758. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3759. debug_printf_parse("done_word return 0: true null, ignored\n");
  3760. return 0;
  3761. }
  3762. if (ctx->pending_redirect) {
  3763. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3764. * only if run as "bash", not "sh" */
  3765. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3766. * "2.7 Redirection
  3767. * If the redirection operator is "<<" or "<<-", the word
  3768. * that follows the redirection operator shall be
  3769. * subjected to quote removal; it is unspecified whether
  3770. * any of the other expansions occur. For the other
  3771. * redirection operators, the word that follows the
  3772. * redirection operator shall be subjected to tilde
  3773. * expansion, parameter expansion, command substitution,
  3774. * arithmetic expansion, and quote removal.
  3775. * Pathname expansion shall not be performed
  3776. * on the word by a non-interactive shell; an interactive
  3777. * shell may perform it, but shall do so only when
  3778. * the expansion would result in one word."
  3779. */
  3780. //bash does not do parameter/command substitution or arithmetic expansion
  3781. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3782. // as written:
  3783. // <<EOF$t
  3784. // <<EOF$((1))
  3785. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3786. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3787. /* Cater for >\file case:
  3788. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3789. * Same with heredocs:
  3790. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3791. */
  3792. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3793. unbackslash(ctx->pending_redirect->rd_filename);
  3794. /* Is it <<"HEREDOC"? */
  3795. if (ctx->word.has_quoted_part) {
  3796. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3797. }
  3798. }
  3799. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3800. ctx->pending_redirect = NULL;
  3801. } else {
  3802. #if HAS_KEYWORDS
  3803. # if ENABLE_HUSH_CASE
  3804. if (ctx->ctx_dsemicolon
  3805. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3806. ) {
  3807. /* already done when ctx_dsemicolon was set to 1: */
  3808. /* ctx->ctx_res_w = RES_MATCH; */
  3809. ctx->ctx_dsemicolon = 0;
  3810. } else
  3811. # endif
  3812. if (!command->argv /* if it's the first word... */
  3813. # if ENABLE_HUSH_LOOPS
  3814. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3815. && ctx->ctx_res_w != RES_IN
  3816. # endif
  3817. # if ENABLE_HUSH_CASE
  3818. && ctx->ctx_res_w != RES_CASE
  3819. # endif
  3820. ) {
  3821. const struct reserved_combo *reserved;
  3822. reserved = reserved_word(ctx);
  3823. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3824. if (reserved) {
  3825. # if ENABLE_HUSH_LINENO_VAR
  3826. /* Case:
  3827. * "while ...; do
  3828. * cmd ..."
  3829. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3830. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3831. */
  3832. if (0
  3833. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3834. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3835. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3836. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3837. ) {
  3838. done_pipe(ctx, PIPE_SEQ);
  3839. }
  3840. # endif
  3841. o_reset_to_empty_unquoted(&ctx->word);
  3842. debug_printf_parse("done_word return %d\n",
  3843. (ctx->ctx_res_w == RES_SNTX));
  3844. return (ctx->ctx_res_w == RES_SNTX);
  3845. }
  3846. # if defined(CMD_SINGLEWORD_NOGLOB)
  3847. if (0
  3848. # if BASH_TEST2
  3849. || strcmp(ctx->word.data, "[[") == 0
  3850. # endif
  3851. /* In bash, local/export/readonly are special, args
  3852. * are assignments and therefore expansion of them
  3853. * should be "one-word" expansion:
  3854. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3855. * compare with:
  3856. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3857. * ls: cannot access i=a: No such file or directory
  3858. * ls: cannot access b: No such file or directory
  3859. * Note: bash 3.2.33(1) does this only if export word
  3860. * itself is not quoted:
  3861. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3862. * aaa bbb
  3863. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3864. * aaa
  3865. */
  3866. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3867. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3868. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3869. ) {
  3870. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3871. }
  3872. /* fall through */
  3873. # endif
  3874. }
  3875. #endif /* HAS_KEYWORDS */
  3876. if (command->group) {
  3877. /* "{ echo foo; } echo bar" - bad */
  3878. syntax_error_at(ctx->word.data);
  3879. debug_printf_parse("done_word return 1: syntax error, "
  3880. "groups and arglists don't mix\n");
  3881. return 1;
  3882. }
  3883. /* If this word wasn't an assignment, next ones definitely
  3884. * can't be assignments. Even if they look like ones. */
  3885. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3886. && ctx->is_assignment != WORD_IS_KEYWORD
  3887. ) {
  3888. ctx->is_assignment = NOT_ASSIGNMENT;
  3889. } else {
  3890. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3891. command->assignment_cnt++;
  3892. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3893. }
  3894. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3895. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3896. }
  3897. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3898. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3899. debug_print_strings("word appended to argv", command->argv);
  3900. }
  3901. #if ENABLE_HUSH_LOOPS
  3902. if (ctx->ctx_res_w == RES_FOR) {
  3903. if (ctx->word.has_quoted_part
  3904. || endofname(command->argv[0])[0] != '\0'
  3905. ) {
  3906. /* bash says just "not a valid identifier" */
  3907. syntax_error("not a valid identifier in for");
  3908. return 1;
  3909. }
  3910. /* Force FOR to have just one word (variable name) */
  3911. /* NB: basically, this makes hush see "for v in ..."
  3912. * syntax as if it is "for v; in ...". FOR and IN become
  3913. * two pipe structs in parse tree. */
  3914. done_pipe(ctx, PIPE_SEQ);
  3915. }
  3916. #endif
  3917. #if ENABLE_HUSH_CASE
  3918. /* Force CASE to have just one word */
  3919. if (ctx->ctx_res_w == RES_CASE) {
  3920. done_pipe(ctx, PIPE_SEQ);
  3921. }
  3922. #endif
  3923. o_reset_to_empty_unquoted(&ctx->word);
  3924. debug_printf_parse("done_word return 0\n");
  3925. return 0;
  3926. }
  3927. /* Peek ahead in the input to find out if we have a "&n" construct,
  3928. * as in "2>&1", that represents duplicating a file descriptor.
  3929. * Return:
  3930. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3931. * REDIRFD_SYNTAX_ERR if syntax error,
  3932. * REDIRFD_TO_FILE if no & was seen,
  3933. * or the number found.
  3934. */
  3935. #if BB_MMU
  3936. #define parse_redir_right_fd(as_string, input) \
  3937. parse_redir_right_fd(input)
  3938. #endif
  3939. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3940. {
  3941. int ch, d, ok;
  3942. ch = i_peek(input);
  3943. if (ch != '&')
  3944. return REDIRFD_TO_FILE;
  3945. ch = i_getch(input); /* get the & */
  3946. nommu_addchr(as_string, ch);
  3947. ch = i_peek(input);
  3948. if (ch == '-') {
  3949. ch = i_getch(input);
  3950. nommu_addchr(as_string, ch);
  3951. return REDIRFD_CLOSE;
  3952. }
  3953. d = 0;
  3954. ok = 0;
  3955. while (ch != EOF && isdigit(ch)) {
  3956. d = d*10 + (ch-'0');
  3957. ok = 1;
  3958. ch = i_getch(input);
  3959. nommu_addchr(as_string, ch);
  3960. ch = i_peek(input);
  3961. }
  3962. if (ok) return d;
  3963. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3964. bb_error_msg("ambiguous redirect");
  3965. return REDIRFD_SYNTAX_ERR;
  3966. }
  3967. /* Return code is 0 normal, 1 if a syntax error is detected
  3968. */
  3969. static int parse_redirect(struct parse_context *ctx,
  3970. int fd,
  3971. redir_type style,
  3972. struct in_str *input)
  3973. {
  3974. struct command *command = ctx->command;
  3975. struct redir_struct *redir;
  3976. struct redir_struct **redirp;
  3977. int dup_num;
  3978. dup_num = REDIRFD_TO_FILE;
  3979. if (style != REDIRECT_HEREDOC) {
  3980. /* Check for a '>&1' type redirect */
  3981. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3982. if (dup_num == REDIRFD_SYNTAX_ERR)
  3983. return 1;
  3984. } else {
  3985. int ch = i_peek_and_eat_bkslash_nl(input);
  3986. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3987. if (dup_num) { /* <<-... */
  3988. ch = i_getch(input);
  3989. nommu_addchr(&ctx->as_string, ch);
  3990. ch = i_peek(input);
  3991. }
  3992. }
  3993. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3994. int ch = i_peek_and_eat_bkslash_nl(input);
  3995. if (ch == '|') {
  3996. /* >|FILE redirect ("clobbering" >).
  3997. * Since we do not support "set -o noclobber" yet,
  3998. * >| and > are the same for now. Just eat |.
  3999. */
  4000. ch = i_getch(input);
  4001. nommu_addchr(&ctx->as_string, ch);
  4002. }
  4003. }
  4004. /* Create a new redir_struct and append it to the linked list */
  4005. redirp = &command->redirects;
  4006. while ((redir = *redirp) != NULL) {
  4007. redirp = &(redir->next);
  4008. }
  4009. *redirp = redir = xzalloc(sizeof(*redir));
  4010. /* redir->next = NULL; */
  4011. /* redir->rd_filename = NULL; */
  4012. redir->rd_type = style;
  4013. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4014. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4015. redir_table[style].descrip);
  4016. redir->rd_dup = dup_num;
  4017. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4018. /* Erik had a check here that the file descriptor in question
  4019. * is legit; I postpone that to "run time"
  4020. * A "-" representation of "close me" shows up as a -3 here */
  4021. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4022. redir->rd_fd, redir->rd_dup);
  4023. } else {
  4024. #if 0 /* Instead we emit error message at run time */
  4025. if (ctx->pending_redirect) {
  4026. /* For example, "cmd > <file" */
  4027. syntax_error("invalid redirect");
  4028. }
  4029. #endif
  4030. /* Set ctx->pending_redirect, so we know what to do at the
  4031. * end of the next parsed word. */
  4032. ctx->pending_redirect = redir;
  4033. }
  4034. return 0;
  4035. }
  4036. /* If a redirect is immediately preceded by a number, that number is
  4037. * supposed to tell which file descriptor to redirect. This routine
  4038. * looks for such preceding numbers. In an ideal world this routine
  4039. * needs to handle all the following classes of redirects...
  4040. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4041. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4042. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4043. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4044. *
  4045. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4046. * "2.7 Redirection
  4047. * ... If n is quoted, the number shall not be recognized as part of
  4048. * the redirection expression. For example:
  4049. * echo \2>a
  4050. * writes the character 2 into file a"
  4051. * We are getting it right by setting ->has_quoted_part on any \<char>
  4052. *
  4053. * A -1 return means no valid number was found,
  4054. * the caller should use the appropriate default for this redirection.
  4055. */
  4056. static int redirect_opt_num(o_string *o)
  4057. {
  4058. int num;
  4059. if (o->data == NULL)
  4060. return -1;
  4061. num = bb_strtou(o->data, NULL, 10);
  4062. if (errno || num < 0)
  4063. return -1;
  4064. o_reset_to_empty_unquoted(o);
  4065. return num;
  4066. }
  4067. #if BB_MMU
  4068. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4069. fetch_till_str(input, word, skip_tabs)
  4070. #endif
  4071. static char *fetch_till_str(o_string *as_string,
  4072. struct in_str *input,
  4073. const char *word,
  4074. int heredoc_flags)
  4075. {
  4076. o_string heredoc = NULL_O_STRING;
  4077. unsigned past_EOL;
  4078. int prev = 0; /* not \ */
  4079. int ch;
  4080. /* Starting with "" is necessary for this case:
  4081. * cat <<EOF
  4082. *
  4083. * xxx
  4084. * EOF
  4085. */
  4086. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4087. goto jump_in;
  4088. while (1) {
  4089. ch = i_getch(input);
  4090. if (ch != EOF)
  4091. nommu_addchr(as_string, ch);
  4092. if (ch == '\n' || ch == EOF) {
  4093. check_heredoc_end:
  4094. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4095. /* End-of-line, and not a line continuation */
  4096. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4097. heredoc.data[past_EOL] = '\0';
  4098. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4099. return heredoc.data;
  4100. }
  4101. if (ch == '\n') {
  4102. /* This is a new line.
  4103. * Remember position and backslash-escaping status.
  4104. */
  4105. o_addchr(&heredoc, ch);
  4106. prev = ch;
  4107. jump_in:
  4108. past_EOL = heredoc.length;
  4109. /* Get 1st char of next line, possibly skipping leading tabs */
  4110. do {
  4111. ch = i_getch(input);
  4112. if (ch != EOF)
  4113. nommu_addchr(as_string, ch);
  4114. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4115. /* If this immediately ended the line,
  4116. * go back to end-of-line checks.
  4117. */
  4118. if (ch == '\n')
  4119. goto check_heredoc_end;
  4120. }
  4121. } else {
  4122. /* Backslash-line continuation in an unquoted
  4123. * heredoc. This does not need special handling
  4124. * for heredoc body (unquoted heredocs are
  4125. * expanded on "execution" and that would take
  4126. * care of this case too), but not the case
  4127. * of line continuation *in terminator*:
  4128. * cat <<EOF
  4129. * Ok1
  4130. * EO\
  4131. * F
  4132. */
  4133. heredoc.data[--heredoc.length] = '\0';
  4134. prev = 0; /* not '\' */
  4135. continue;
  4136. }
  4137. }
  4138. if (ch == EOF) {
  4139. o_free(&heredoc);
  4140. return NULL; /* error */
  4141. }
  4142. o_addchr(&heredoc, ch);
  4143. nommu_addchr(as_string, ch);
  4144. if (prev == '\\' && ch == '\\')
  4145. /* Correctly handle foo\\<eol> (not a line cont.) */
  4146. prev = 0; /* not '\' */
  4147. else
  4148. prev = ch;
  4149. }
  4150. }
  4151. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4152. * and load them all. There should be exactly heredoc_cnt of them.
  4153. */
  4154. #if BB_MMU
  4155. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4156. fetch_heredocs(pi, heredoc_cnt, input)
  4157. #endif
  4158. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4159. {
  4160. while (pi && heredoc_cnt) {
  4161. int i;
  4162. struct command *cmd = pi->cmds;
  4163. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4164. pi->num_cmds,
  4165. cmd->argv ? cmd->argv[0] : "NONE"
  4166. );
  4167. for (i = 0; i < pi->num_cmds; i++) {
  4168. struct redir_struct *redir = cmd->redirects;
  4169. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4170. i, cmd->argv ? cmd->argv[0] : "NONE");
  4171. while (redir) {
  4172. if (redir->rd_type == REDIRECT_HEREDOC) {
  4173. char *p;
  4174. redir->rd_type = REDIRECT_HEREDOC2;
  4175. /* redir->rd_dup is (ab)used to indicate <<- */
  4176. p = fetch_till_str(as_string, input,
  4177. redir->rd_filename, redir->rd_dup);
  4178. if (!p) {
  4179. syntax_error("unexpected EOF in here document");
  4180. return -1;
  4181. }
  4182. free(redir->rd_filename);
  4183. redir->rd_filename = p;
  4184. heredoc_cnt--;
  4185. }
  4186. redir = redir->next;
  4187. }
  4188. if (cmd->group) {
  4189. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4190. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4191. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4192. if (heredoc_cnt < 0)
  4193. return heredoc_cnt; /* error */
  4194. }
  4195. cmd++;
  4196. }
  4197. pi = pi->next;
  4198. }
  4199. return heredoc_cnt;
  4200. }
  4201. static int run_list(struct pipe *pi);
  4202. #if BB_MMU
  4203. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4204. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4205. #endif
  4206. static struct pipe *parse_stream(char **pstring,
  4207. int *heredoc_cnt_ptr,
  4208. struct in_str *input,
  4209. int end_trigger);
  4210. /* Returns number of heredocs not yet consumed,
  4211. * or -1 on error.
  4212. */
  4213. static int parse_group(struct parse_context *ctx,
  4214. struct in_str *input, int ch)
  4215. {
  4216. /* ctx->word contains characters seen prior to ( or {.
  4217. * Typically it's empty, but for function defs,
  4218. * it contains function name (without '()'). */
  4219. #if BB_MMU
  4220. # define as_string NULL
  4221. #else
  4222. char *as_string = NULL;
  4223. #endif
  4224. struct pipe *pipe_list;
  4225. int heredoc_cnt = 0;
  4226. int endch;
  4227. struct command *command = ctx->command;
  4228. debug_printf_parse("parse_group entered\n");
  4229. #if ENABLE_HUSH_FUNCTIONS
  4230. if (ch == '(' && !ctx->word.has_quoted_part) {
  4231. if (ctx->word.length)
  4232. if (done_word(ctx))
  4233. return -1;
  4234. if (!command->argv)
  4235. goto skip; /* (... */
  4236. if (command->argv[1]) { /* word word ... (... */
  4237. syntax_error_unexpected_ch('(');
  4238. return -1;
  4239. }
  4240. /* it is "word(..." or "word (..." */
  4241. do
  4242. ch = i_getch(input);
  4243. while (ch == ' ' || ch == '\t');
  4244. if (ch != ')') {
  4245. syntax_error_unexpected_ch(ch);
  4246. return -1;
  4247. }
  4248. nommu_addchr(&ctx->as_string, ch);
  4249. do
  4250. ch = i_getch(input);
  4251. while (ch == ' ' || ch == '\t' || ch == '\n');
  4252. if (ch != '{' && ch != '(') {
  4253. syntax_error_unexpected_ch(ch);
  4254. return -1;
  4255. }
  4256. nommu_addchr(&ctx->as_string, ch);
  4257. command->cmd_type = CMD_FUNCDEF;
  4258. goto skip;
  4259. }
  4260. #endif
  4261. #if 0 /* Prevented by caller */
  4262. if (command->argv /* word [word]{... */
  4263. || ctx->word.length /* word{... */
  4264. || ctx->word.has_quoted_part /* ""{... */
  4265. ) {
  4266. syntax_error(NULL);
  4267. debug_printf_parse("parse_group return -1: "
  4268. "syntax error, groups and arglists don't mix\n");
  4269. return -1;
  4270. }
  4271. #endif
  4272. IF_HUSH_FUNCTIONS(skip:)
  4273. endch = '}';
  4274. if (ch == '(') {
  4275. endch = ')';
  4276. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4277. command->cmd_type = CMD_SUBSHELL;
  4278. } else {
  4279. /* bash does not allow "{echo...", requires whitespace */
  4280. ch = i_peek(input);
  4281. if (ch != ' ' && ch != '\t' && ch != '\n'
  4282. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4283. ) {
  4284. syntax_error_unexpected_ch(ch);
  4285. return -1;
  4286. }
  4287. if (ch != '(') {
  4288. ch = i_getch(input);
  4289. nommu_addchr(&ctx->as_string, ch);
  4290. }
  4291. }
  4292. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4293. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4294. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4295. #if !BB_MMU
  4296. if (as_string)
  4297. o_addstr(&ctx->as_string, as_string);
  4298. #endif
  4299. /* empty ()/{} or parse error? */
  4300. if (!pipe_list || pipe_list == ERR_PTR) {
  4301. /* parse_stream already emitted error msg */
  4302. if (!BB_MMU)
  4303. free(as_string);
  4304. debug_printf_parse("parse_group return -1: "
  4305. "parse_stream returned %p\n", pipe_list);
  4306. return -1;
  4307. }
  4308. #if !BB_MMU
  4309. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4310. command->group_as_string = as_string;
  4311. debug_printf_parse("end of group, remembering as:'%s'\n",
  4312. command->group_as_string);
  4313. #endif
  4314. #if ENABLE_HUSH_FUNCTIONS
  4315. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4316. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4317. struct command *cmd2;
  4318. cmd2 = xzalloc(sizeof(*cmd2));
  4319. cmd2->cmd_type = CMD_SUBSHELL;
  4320. cmd2->group = pipe_list;
  4321. # if !BB_MMU
  4322. //UNTESTED!
  4323. cmd2->group_as_string = command->group_as_string;
  4324. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4325. # endif
  4326. pipe_list = new_pipe();
  4327. pipe_list->cmds = cmd2;
  4328. pipe_list->num_cmds = 1;
  4329. }
  4330. #endif
  4331. command->group = pipe_list;
  4332. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4333. return heredoc_cnt;
  4334. /* command remains "open", available for possible redirects */
  4335. #undef as_string
  4336. }
  4337. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4338. /* Subroutines for copying $(...) and `...` things */
  4339. /* '...' */
  4340. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4341. {
  4342. while (1) {
  4343. int ch = i_getch(input);
  4344. if (ch == EOF) {
  4345. syntax_error_unterm_ch('\'');
  4346. return 0;
  4347. }
  4348. if (ch == '\'')
  4349. return 1;
  4350. o_addchr(dest, ch);
  4351. }
  4352. }
  4353. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4354. {
  4355. while (1) {
  4356. int ch = i_getch(input);
  4357. if (ch == EOF) {
  4358. syntax_error_unterm_ch('\'');
  4359. return 0;
  4360. }
  4361. if (ch == '\'')
  4362. return 1;
  4363. o_addqchr(dest, ch);
  4364. }
  4365. }
  4366. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4367. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4368. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4369. {
  4370. while (1) {
  4371. int ch = i_getch(input);
  4372. if (ch == EOF) {
  4373. syntax_error_unterm_ch('"');
  4374. return 0;
  4375. }
  4376. if (ch == '"')
  4377. return 1;
  4378. if (ch == '\\') { /* \x. Copy both chars. */
  4379. o_addchr(dest, ch);
  4380. ch = i_getch(input);
  4381. }
  4382. o_addchr(dest, ch);
  4383. if (ch == '`') {
  4384. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4385. return 0;
  4386. o_addchr(dest, ch);
  4387. continue;
  4388. }
  4389. //if (ch == '$') ...
  4390. }
  4391. }
  4392. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4393. * \` quoting.
  4394. * "Within the backquoted style of command substitution, backslash
  4395. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4396. * The search for the matching backquote shall be satisfied by the first
  4397. * backquote found without a preceding backslash; during this search,
  4398. * if a non-escaped backquote is encountered within a shell comment,
  4399. * a here-document, an embedded command substitution of the $(command)
  4400. * form, or a quoted string, undefined results occur. A single-quoted
  4401. * or double-quoted string that begins, but does not end, within the
  4402. * "`...`" sequence produces undefined results."
  4403. * Example Output
  4404. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4405. */
  4406. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4407. {
  4408. while (1) {
  4409. int ch = i_getch(input);
  4410. if (ch == '`')
  4411. return 1;
  4412. if (ch == '\\') {
  4413. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4414. ch = i_getch(input);
  4415. if (ch != '`'
  4416. && ch != '$'
  4417. && ch != '\\'
  4418. && (!in_dquote || ch != '"')
  4419. ) {
  4420. o_addchr(dest, '\\');
  4421. }
  4422. }
  4423. if (ch == EOF) {
  4424. syntax_error_unterm_ch('`');
  4425. return 0;
  4426. }
  4427. o_addchr(dest, ch);
  4428. }
  4429. }
  4430. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4431. * quoting and nested ()s.
  4432. * "With the $(command) style of command substitution, all characters
  4433. * following the open parenthesis to the matching closing parenthesis
  4434. * constitute the command. Any valid shell script can be used for command,
  4435. * except a script consisting solely of redirections which produces
  4436. * unspecified results."
  4437. * Example Output
  4438. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4439. * echo $(echo 'TEST)' BEST) TEST) BEST
  4440. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4441. *
  4442. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4443. * can contain arbitrary constructs, just like $(cmd).
  4444. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4445. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4446. */
  4447. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4448. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4449. {
  4450. int ch;
  4451. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4452. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4453. char end_char2 = end_ch >> 8;
  4454. # endif
  4455. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4456. #if ENABLE_HUSH_INTERACTIVE
  4457. G.promptmode = 1; /* PS2 */
  4458. #endif
  4459. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4460. while (1) {
  4461. ch = i_getch(input);
  4462. if (ch == EOF) {
  4463. syntax_error_unterm_ch(end_ch);
  4464. return 0;
  4465. }
  4466. if (ch == end_ch
  4467. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4468. || ch == end_char2
  4469. # endif
  4470. ) {
  4471. if (!dbl)
  4472. break;
  4473. /* we look for closing )) of $((EXPR)) */
  4474. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4475. i_getch(input); /* eat second ')' */
  4476. break;
  4477. }
  4478. }
  4479. o_addchr(dest, ch);
  4480. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4481. if (ch == '(' || ch == '{') {
  4482. ch = (ch == '(' ? ')' : '}');
  4483. if (!add_till_closing_bracket(dest, input, ch))
  4484. return 0;
  4485. o_addchr(dest, ch);
  4486. continue;
  4487. }
  4488. if (ch == '\'') {
  4489. if (!add_till_single_quote(dest, input))
  4490. return 0;
  4491. o_addchr(dest, ch);
  4492. continue;
  4493. }
  4494. if (ch == '"') {
  4495. if (!add_till_double_quote(dest, input))
  4496. return 0;
  4497. o_addchr(dest, ch);
  4498. continue;
  4499. }
  4500. if (ch == '`') {
  4501. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4502. return 0;
  4503. o_addchr(dest, ch);
  4504. continue;
  4505. }
  4506. if (ch == '\\') {
  4507. /* \x. Copy verbatim. Important for \(, \) */
  4508. ch = i_getch(input);
  4509. if (ch == EOF) {
  4510. syntax_error_unterm_ch(end_ch);
  4511. return 0;
  4512. }
  4513. #if 0
  4514. if (ch == '\n') {
  4515. /* "backslash+newline", ignore both */
  4516. o_delchr(dest); /* undo insertion of '\' */
  4517. continue;
  4518. }
  4519. #endif
  4520. o_addchr(dest, ch);
  4521. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4522. continue;
  4523. }
  4524. }
  4525. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4526. return ch;
  4527. }
  4528. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4529. /* Return code: 0 for OK, 1 for syntax error */
  4530. #if BB_MMU
  4531. #define parse_dollar(as_string, dest, input, quote_mask) \
  4532. parse_dollar(dest, input, quote_mask)
  4533. #define as_string NULL
  4534. #endif
  4535. static int parse_dollar(o_string *as_string,
  4536. o_string *dest,
  4537. struct in_str *input, unsigned char quote_mask)
  4538. {
  4539. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4540. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4541. if (isalpha(ch)) {
  4542. make_var:
  4543. ch = i_getch(input);
  4544. nommu_addchr(as_string, ch);
  4545. /*make_var1:*/
  4546. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4547. while (1) {
  4548. debug_printf_parse(": '%c'\n", ch);
  4549. o_addchr(dest, ch | quote_mask);
  4550. quote_mask = 0;
  4551. ch = i_peek_and_eat_bkslash_nl(input);
  4552. if (!isalnum(ch) && ch != '_') {
  4553. /* End of variable name reached */
  4554. break;
  4555. }
  4556. ch = i_getch(input);
  4557. nommu_addchr(as_string, ch);
  4558. }
  4559. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4560. } else if (isdigit(ch)) {
  4561. make_one_char_var:
  4562. ch = i_getch(input);
  4563. nommu_addchr(as_string, ch);
  4564. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4565. debug_printf_parse(": '%c'\n", ch);
  4566. o_addchr(dest, ch | quote_mask);
  4567. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4568. } else switch (ch) {
  4569. case '$': /* pid */
  4570. case '!': /* last bg pid */
  4571. case '?': /* last exit code */
  4572. case '#': /* number of args */
  4573. case '*': /* args */
  4574. case '@': /* args */
  4575. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4576. goto make_one_char_var;
  4577. case '{': {
  4578. char len_single_ch;
  4579. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4580. ch = i_getch(input); /* eat '{' */
  4581. nommu_addchr(as_string, ch);
  4582. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4583. /* It should be ${?}, or ${#var},
  4584. * or even ${?+subst} - operator acting on a special variable,
  4585. * or the beginning of variable name.
  4586. */
  4587. if (ch == EOF
  4588. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4589. ) {
  4590. bad_dollar_syntax:
  4591. syntax_error_unterm_str("${name}");
  4592. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4593. return 0;
  4594. }
  4595. nommu_addchr(as_string, ch);
  4596. len_single_ch = ch;
  4597. ch |= quote_mask;
  4598. /* It's possible to just call add_till_closing_bracket() at this point.
  4599. * However, this regresses some of our testsuite cases
  4600. * which check invalid constructs like ${%}.
  4601. * Oh well... let's check that the var name part is fine... */
  4602. while (1) {
  4603. unsigned pos;
  4604. o_addchr(dest, ch);
  4605. debug_printf_parse(": '%c'\n", ch);
  4606. ch = i_getch(input);
  4607. nommu_addchr(as_string, ch);
  4608. if (ch == '}')
  4609. break;
  4610. if (!isalnum(ch) && ch != '_') {
  4611. unsigned end_ch;
  4612. unsigned char last_ch;
  4613. /* handle parameter expansions
  4614. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4615. */
  4616. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4617. if (len_single_ch != '#'
  4618. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4619. || i_peek(input) != '}'
  4620. ) {
  4621. goto bad_dollar_syntax;
  4622. }
  4623. /* else: it's "length of C" ${#C} op,
  4624. * where C is a single char
  4625. * special var name, e.g. ${#!}.
  4626. */
  4627. }
  4628. /* Eat everything until closing '}' (or ':') */
  4629. end_ch = '}';
  4630. if (BASH_SUBSTR
  4631. && ch == ':'
  4632. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4633. ) {
  4634. /* It's ${var:N[:M]} thing */
  4635. end_ch = '}' * 0x100 + ':';
  4636. }
  4637. if (BASH_PATTERN_SUBST
  4638. && ch == '/'
  4639. ) {
  4640. /* It's ${var/[/]pattern[/repl]} thing */
  4641. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4642. i_getch(input);
  4643. nommu_addchr(as_string, '/');
  4644. ch = '\\';
  4645. }
  4646. end_ch = '}' * 0x100 + '/';
  4647. }
  4648. o_addchr(dest, ch);
  4649. /* The pattern can't be empty.
  4650. * IOW: if the first char after "${v//" is a slash,
  4651. * it does not terminate the pattern - it's the first char of the pattern:
  4652. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4653. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4654. */
  4655. if (i_peek(input) == '/') {
  4656. o_addchr(dest, i_getch(input));
  4657. }
  4658. again:
  4659. if (!BB_MMU)
  4660. pos = dest->length;
  4661. #if ENABLE_HUSH_DOLLAR_OPS
  4662. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4663. if (last_ch == 0) /* error? */
  4664. return 0;
  4665. #else
  4666. #error Simple code to only allow ${var} is not implemented
  4667. #endif
  4668. if (as_string) {
  4669. o_addstr(as_string, dest->data + pos);
  4670. o_addchr(as_string, last_ch);
  4671. }
  4672. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4673. && (end_ch & 0xff00)
  4674. ) {
  4675. /* close the first block: */
  4676. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4677. /* while parsing N from ${var:N[:M]}
  4678. * or pattern from ${var/[/]pattern[/repl]} */
  4679. if ((end_ch & 0xff) == last_ch) {
  4680. /* got ':' or '/'- parse the rest */
  4681. end_ch = '}';
  4682. goto again;
  4683. }
  4684. /* got '}' */
  4685. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4686. /* it's ${var:N} - emulate :999999999 */
  4687. o_addstr(dest, "999999999");
  4688. } /* else: it's ${var/[/]pattern} */
  4689. }
  4690. break;
  4691. }
  4692. len_single_ch = 0; /* it can't be ${#C} op */
  4693. }
  4694. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4695. break;
  4696. }
  4697. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4698. case '(': {
  4699. unsigned pos;
  4700. ch = i_getch(input);
  4701. nommu_addchr(as_string, ch);
  4702. # if ENABLE_FEATURE_SH_MATH
  4703. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4704. ch = i_getch(input);
  4705. nommu_addchr(as_string, ch);
  4706. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4707. o_addchr(dest, /*quote_mask |*/ '+');
  4708. if (!BB_MMU)
  4709. pos = dest->length;
  4710. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4711. return 0; /* error */
  4712. if (as_string) {
  4713. o_addstr(as_string, dest->data + pos);
  4714. o_addchr(as_string, ')');
  4715. o_addchr(as_string, ')');
  4716. }
  4717. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4718. break;
  4719. }
  4720. # endif
  4721. # if ENABLE_HUSH_TICK
  4722. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4723. o_addchr(dest, quote_mask | '`');
  4724. if (!BB_MMU)
  4725. pos = dest->length;
  4726. if (!add_till_closing_bracket(dest, input, ')'))
  4727. return 0; /* error */
  4728. if (as_string) {
  4729. o_addstr(as_string, dest->data + pos);
  4730. o_addchr(as_string, ')');
  4731. }
  4732. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4733. # endif
  4734. break;
  4735. }
  4736. #endif
  4737. case '_':
  4738. goto make_var;
  4739. #if 0
  4740. /* TODO: $_: */
  4741. /* $_ Shell or shell script name; or last argument of last command
  4742. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4743. * but in command's env, set to full pathname used to invoke it */
  4744. ch = i_getch(input);
  4745. nommu_addchr(as_string, ch);
  4746. ch = i_peek_and_eat_bkslash_nl(input);
  4747. if (isalnum(ch)) { /* it's $_name or $_123 */
  4748. ch = '_';
  4749. goto make_var1;
  4750. }
  4751. /* else: it's $_ */
  4752. #endif
  4753. default:
  4754. o_addQchr(dest, '$');
  4755. }
  4756. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4757. return 1;
  4758. #undef as_string
  4759. }
  4760. #if BB_MMU
  4761. #define encode_string(as_string, dest, input, dquote_end) \
  4762. encode_string(dest, input, dquote_end)
  4763. #define as_string NULL
  4764. #endif
  4765. static int encode_string(o_string *as_string,
  4766. o_string *dest,
  4767. struct in_str *input,
  4768. int dquote_end)
  4769. {
  4770. int ch;
  4771. int next;
  4772. again:
  4773. ch = i_getch(input);
  4774. if (ch != EOF)
  4775. nommu_addchr(as_string, ch);
  4776. if (ch == dquote_end) { /* may be only '"' or EOF */
  4777. debug_printf_parse("encode_string return 1 (ok)\n");
  4778. return 1;
  4779. }
  4780. /* note: can't move it above ch == dquote_end check! */
  4781. if (ch == EOF) {
  4782. syntax_error_unterm_ch('"');
  4783. return 0; /* error */
  4784. }
  4785. next = '\0';
  4786. if (ch != '\n') {
  4787. next = i_peek(input);
  4788. }
  4789. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4790. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4791. if (ch == '\\') {
  4792. if (next == EOF) {
  4793. /* Testcase: in interactive shell a file with
  4794. * echo "unterminated string\<eof>
  4795. * is sourced.
  4796. */
  4797. syntax_error_unterm_ch('"');
  4798. return 0; /* error */
  4799. }
  4800. /* bash:
  4801. * "The backslash retains its special meaning [in "..."]
  4802. * only when followed by one of the following characters:
  4803. * $, `, ", \, or <newline>. A double quote may be quoted
  4804. * within double quotes by preceding it with a backslash."
  4805. * NB: in (unquoted) heredoc, above does not apply to ",
  4806. * therefore we check for it by "next == dquote_end" cond.
  4807. */
  4808. if (next == dquote_end || strchr("$`\\\n", next)) {
  4809. ch = i_getch(input); /* eat next */
  4810. if (ch == '\n')
  4811. goto again; /* skip \<newline> */
  4812. } /* else: ch remains == '\\', and we double it below: */
  4813. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4814. nommu_addchr(as_string, ch);
  4815. goto again;
  4816. }
  4817. if (ch == '$') {
  4818. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4819. debug_printf_parse("encode_string return 0: "
  4820. "parse_dollar returned 0 (error)\n");
  4821. return 0;
  4822. }
  4823. goto again;
  4824. }
  4825. #if ENABLE_HUSH_TICK
  4826. if (ch == '`') {
  4827. //unsigned pos = dest->length;
  4828. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4829. o_addchr(dest, 0x80 | '`');
  4830. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4831. return 0; /* error */
  4832. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4833. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4834. goto again;
  4835. }
  4836. #endif
  4837. o_addQchr(dest, ch);
  4838. goto again;
  4839. #undef as_string
  4840. }
  4841. /*
  4842. * Scan input until EOF or end_trigger char.
  4843. * Return a list of pipes to execute, or NULL on EOF
  4844. * or if end_trigger character is met.
  4845. * On syntax error, exit if shell is not interactive,
  4846. * reset parsing machinery and start parsing anew,
  4847. * or return ERR_PTR.
  4848. */
  4849. static struct pipe *parse_stream(char **pstring,
  4850. int *heredoc_cnt_ptr,
  4851. struct in_str *input,
  4852. int end_trigger)
  4853. {
  4854. struct parse_context ctx;
  4855. int heredoc_cnt;
  4856. /* Single-quote triggers a bypass of the main loop until its mate is
  4857. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4858. */
  4859. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4860. end_trigger ? end_trigger : 'X');
  4861. debug_enter();
  4862. initialize_context(&ctx);
  4863. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4864. * Preventing this:
  4865. */
  4866. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4867. /* We used to separate words on $IFS here. This was wrong.
  4868. * $IFS is used only for word splitting when $var is expanded,
  4869. * here we should use blank chars as separators, not $IFS
  4870. */
  4871. heredoc_cnt = 0;
  4872. while (1) {
  4873. const char *is_blank;
  4874. const char *is_special;
  4875. int ch;
  4876. int next;
  4877. int redir_fd;
  4878. redir_type redir_style;
  4879. ch = i_getch(input);
  4880. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4881. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4882. if (ch == EOF) {
  4883. struct pipe *pi;
  4884. if (heredoc_cnt) {
  4885. syntax_error_unterm_str("here document");
  4886. goto parse_error;
  4887. }
  4888. if (end_trigger == ')') {
  4889. syntax_error_unterm_ch('(');
  4890. goto parse_error;
  4891. }
  4892. if (end_trigger == '}') {
  4893. syntax_error_unterm_ch('{');
  4894. goto parse_error;
  4895. }
  4896. if (done_word(&ctx)) {
  4897. goto parse_error;
  4898. }
  4899. o_free_and_set_NULL(&ctx.word);
  4900. done_pipe(&ctx, PIPE_SEQ);
  4901. pi = ctx.list_head;
  4902. /* If we got nothing... */
  4903. /* (this makes bare "&" cmd a no-op.
  4904. * bash says: "syntax error near unexpected token '&'") */
  4905. if (pi->num_cmds == 0
  4906. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4907. ) {
  4908. free_pipe_list(pi);
  4909. pi = NULL;
  4910. }
  4911. #if !BB_MMU
  4912. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4913. if (pstring)
  4914. *pstring = ctx.as_string.data;
  4915. else
  4916. o_free(&ctx.as_string);
  4917. #endif
  4918. // heredoc_cnt must be 0 here anyway
  4919. //if (heredoc_cnt_ptr)
  4920. // *heredoc_cnt_ptr = heredoc_cnt;
  4921. debug_leave();
  4922. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4923. debug_printf_parse("parse_stream return %p\n", pi);
  4924. return pi;
  4925. }
  4926. /* Handle "'" and "\" first, as they won't play nice with
  4927. * i_peek_and_eat_bkslash_nl() anyway:
  4928. * echo z\\
  4929. * and
  4930. * echo '\
  4931. * '
  4932. * would break.
  4933. */
  4934. if (ch == '\\') {
  4935. ch = i_getch(input);
  4936. if (ch == '\n')
  4937. continue; /* drop \<newline>, get next char */
  4938. nommu_addchr(&ctx.as_string, '\\');
  4939. o_addchr(&ctx.word, '\\');
  4940. if (ch == EOF) {
  4941. /* Testcase: eval 'echo Ok\' */
  4942. /* bash-4.3.43 was removing backslash,
  4943. * but 4.4.19 retains it, most other shells too
  4944. */
  4945. continue; /* get next char */
  4946. }
  4947. /* Example: echo Hello \2>file
  4948. * we need to know that word 2 is quoted
  4949. */
  4950. ctx.word.has_quoted_part = 1;
  4951. nommu_addchr(&ctx.as_string, ch);
  4952. o_addchr(&ctx.word, ch);
  4953. continue; /* get next char */
  4954. }
  4955. nommu_addchr(&ctx.as_string, ch);
  4956. if (ch == '\'') {
  4957. ctx.word.has_quoted_part = 1;
  4958. next = i_getch(input);
  4959. if (next == '\'' && !ctx.pending_redirect)
  4960. goto insert_empty_quoted_str_marker;
  4961. ch = next;
  4962. while (1) {
  4963. if (ch == EOF) {
  4964. syntax_error_unterm_ch('\'');
  4965. goto parse_error;
  4966. }
  4967. nommu_addchr(&ctx.as_string, ch);
  4968. if (ch == '\'')
  4969. break;
  4970. if (ch == SPECIAL_VAR_SYMBOL) {
  4971. /* Convert raw ^C to corresponding special variable reference */
  4972. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4973. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4974. }
  4975. o_addqchr(&ctx.word, ch);
  4976. ch = i_getch(input);
  4977. }
  4978. continue; /* get next char */
  4979. }
  4980. next = '\0';
  4981. if (ch != '\n')
  4982. next = i_peek_and_eat_bkslash_nl(input);
  4983. is_special = "{}<>;&|()#" /* special outside of "str" */
  4984. "$\"" IF_HUSH_TICK("`") /* always special */
  4985. SPECIAL_VAR_SYMBOL_STR;
  4986. /* Are { and } special here? */
  4987. if (ctx.command->argv /* word [word]{... - non-special */
  4988. || ctx.word.length /* word{... - non-special */
  4989. || ctx.word.has_quoted_part /* ""{... - non-special */
  4990. || (next != ';' /* }; - special */
  4991. && next != ')' /* }) - special */
  4992. && next != '(' /* {( - special */
  4993. && next != '&' /* }& and }&& ... - special */
  4994. && next != '|' /* }|| ... - special */
  4995. && !strchr(defifs, next) /* {word - non-special */
  4996. )
  4997. ) {
  4998. /* They are not special, skip "{}" */
  4999. is_special += 2;
  5000. }
  5001. is_special = strchr(is_special, ch);
  5002. is_blank = strchr(defifs, ch);
  5003. if (!is_special && !is_blank) { /* ordinary char */
  5004. ordinary_char:
  5005. o_addQchr(&ctx.word, ch);
  5006. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5007. || ctx.is_assignment == WORD_IS_KEYWORD)
  5008. && ch == '='
  5009. && endofname(ctx.word.data)[0] == '='
  5010. ) {
  5011. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5012. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5013. }
  5014. continue;
  5015. }
  5016. if (is_blank) {
  5017. #if ENABLE_HUSH_LINENO_VAR
  5018. /* Case:
  5019. * "while ...; do<whitespace><newline>
  5020. * cmd ..."
  5021. * would think that "cmd" starts in <whitespace> -
  5022. * i.e., at the previous line.
  5023. * We need to skip all whitespace before newlines.
  5024. */
  5025. while (ch != '\n') {
  5026. next = i_peek(input);
  5027. if (next != ' ' && next != '\t' && next != '\n')
  5028. break; /* next char is not ws */
  5029. ch = i_getch(input);
  5030. }
  5031. /* ch == last eaten whitespace char */
  5032. #endif
  5033. if (done_word(&ctx)) {
  5034. goto parse_error;
  5035. }
  5036. if (ch == '\n') {
  5037. /* Is this a case when newline is simply ignored?
  5038. * Some examples:
  5039. * "cmd | <newline> cmd ..."
  5040. * "case ... in <newline> word) ..."
  5041. */
  5042. if (IS_NULL_CMD(ctx.command)
  5043. && ctx.word.length == 0
  5044. && !ctx.word.has_quoted_part
  5045. && heredoc_cnt == 0
  5046. ) {
  5047. /* This newline can be ignored. But...
  5048. * Without check #1, interactive shell
  5049. * ignores even bare <newline>,
  5050. * and shows the continuation prompt:
  5051. * ps1_prompt$ <enter>
  5052. * ps2> _ <=== wrong, should be ps1
  5053. * Without check #2, "cmd & <newline>"
  5054. * is similarly mistreated.
  5055. * (BTW, this makes "cmd & cmd"
  5056. * and "cmd && cmd" non-orthogonal.
  5057. * Really, ask yourself, why
  5058. * "cmd && <newline>" doesn't start
  5059. * cmd but waits for more input?
  5060. * The only reason is that it might be
  5061. * a "cmd1 && <nl> cmd2 &" construct,
  5062. * cmd1 may need to run in BG).
  5063. */
  5064. struct pipe *pi = ctx.list_head;
  5065. if (pi->num_cmds != 0 /* check #1 */
  5066. && pi->followup != PIPE_BG /* check #2 */
  5067. ) {
  5068. continue;
  5069. }
  5070. }
  5071. /* Treat newline as a command separator. */
  5072. done_pipe(&ctx, PIPE_SEQ);
  5073. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5074. if (heredoc_cnt) {
  5075. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5076. if (heredoc_cnt != 0)
  5077. goto parse_error;
  5078. }
  5079. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5080. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5081. ch = ';';
  5082. /* note: if (is_blank) continue;
  5083. * will still trigger for us */
  5084. }
  5085. }
  5086. /* "cmd}" or "cmd }..." without semicolon or &:
  5087. * } is an ordinary char in this case, even inside { cmd; }
  5088. * Pathological example: { ""}; } should exec "}" cmd
  5089. */
  5090. if (ch == '}') {
  5091. if (ctx.word.length != 0 /* word} */
  5092. || ctx.word.has_quoted_part /* ""} */
  5093. ) {
  5094. goto ordinary_char;
  5095. }
  5096. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5097. /* Generally, there should be semicolon: "cmd; }"
  5098. * However, bash allows to omit it if "cmd" is
  5099. * a group. Examples:
  5100. * { { echo 1; } }
  5101. * {(echo 1)}
  5102. * { echo 0 >&2 | { echo 1; } }
  5103. * { while false; do :; done }
  5104. * { case a in b) ;; esac }
  5105. */
  5106. if (ctx.command->group)
  5107. goto term_group;
  5108. goto ordinary_char;
  5109. }
  5110. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5111. /* Can't be an end of {cmd}, skip the check */
  5112. goto skip_end_trigger;
  5113. /* else: } does terminate a group */
  5114. }
  5115. term_group:
  5116. if (end_trigger && end_trigger == ch
  5117. && (ch != ';' || heredoc_cnt == 0)
  5118. #if ENABLE_HUSH_CASE
  5119. && (ch != ')'
  5120. || ctx.ctx_res_w != RES_MATCH
  5121. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5122. )
  5123. #endif
  5124. ) {
  5125. if (done_word(&ctx)) {
  5126. goto parse_error;
  5127. }
  5128. done_pipe(&ctx, PIPE_SEQ);
  5129. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5130. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5131. /* Do we sit outside of any if's, loops or case's? */
  5132. if (!HAS_KEYWORDS
  5133. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5134. ) {
  5135. o_free_and_set_NULL(&ctx.word);
  5136. #if !BB_MMU
  5137. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5138. if (pstring)
  5139. *pstring = ctx.as_string.data;
  5140. else
  5141. o_free(&ctx.as_string);
  5142. #endif
  5143. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5144. /* Example: bare "{ }", "()" */
  5145. G.last_exitcode = 2; /* bash compat */
  5146. syntax_error_unexpected_ch(ch);
  5147. goto parse_error2;
  5148. }
  5149. if (heredoc_cnt_ptr)
  5150. *heredoc_cnt_ptr = heredoc_cnt;
  5151. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5152. debug_printf_parse("parse_stream return %p: "
  5153. "end_trigger char found\n",
  5154. ctx.list_head);
  5155. debug_leave();
  5156. return ctx.list_head;
  5157. }
  5158. }
  5159. if (is_blank)
  5160. continue;
  5161. /* Catch <, > before deciding whether this word is
  5162. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5163. switch (ch) {
  5164. case '>':
  5165. redir_fd = redirect_opt_num(&ctx.word);
  5166. if (done_word(&ctx)) {
  5167. goto parse_error;
  5168. }
  5169. redir_style = REDIRECT_OVERWRITE;
  5170. if (next == '>') {
  5171. redir_style = REDIRECT_APPEND;
  5172. ch = i_getch(input);
  5173. nommu_addchr(&ctx.as_string, ch);
  5174. }
  5175. #if 0
  5176. else if (next == '(') {
  5177. syntax_error(">(process) not supported");
  5178. goto parse_error;
  5179. }
  5180. #endif
  5181. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5182. goto parse_error;
  5183. continue; /* get next char */
  5184. case '<':
  5185. redir_fd = redirect_opt_num(&ctx.word);
  5186. if (done_word(&ctx)) {
  5187. goto parse_error;
  5188. }
  5189. redir_style = REDIRECT_INPUT;
  5190. if (next == '<') {
  5191. redir_style = REDIRECT_HEREDOC;
  5192. heredoc_cnt++;
  5193. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5194. ch = i_getch(input);
  5195. nommu_addchr(&ctx.as_string, ch);
  5196. } else if (next == '>') {
  5197. redir_style = REDIRECT_IO;
  5198. ch = i_getch(input);
  5199. nommu_addchr(&ctx.as_string, ch);
  5200. }
  5201. #if 0
  5202. else if (next == '(') {
  5203. syntax_error("<(process) not supported");
  5204. goto parse_error;
  5205. }
  5206. #endif
  5207. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5208. goto parse_error;
  5209. continue; /* get next char */
  5210. case '#':
  5211. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5212. /* skip "#comment" */
  5213. /* note: we do not add it to &ctx.as_string */
  5214. /* TODO: in bash:
  5215. * comment inside $() goes to the next \n, even inside quoted string (!):
  5216. * cmd "$(cmd2 #comment)" - syntax error
  5217. * cmd "`cmd2 #comment`" - ok
  5218. * We accept both (comment ends where command subst ends, in both cases).
  5219. */
  5220. while (1) {
  5221. ch = i_peek(input);
  5222. if (ch == '\n') {
  5223. nommu_addchr(&ctx.as_string, '\n');
  5224. break;
  5225. }
  5226. ch = i_getch(input);
  5227. if (ch == EOF)
  5228. break;
  5229. }
  5230. continue; /* get next char */
  5231. }
  5232. break;
  5233. }
  5234. skip_end_trigger:
  5235. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5236. /* check that we are not in word in "a=1 2>word b=1": */
  5237. && !ctx.pending_redirect
  5238. ) {
  5239. /* ch is a special char and thus this word
  5240. * cannot be an assignment */
  5241. ctx.is_assignment = NOT_ASSIGNMENT;
  5242. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5243. }
  5244. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5245. switch (ch) {
  5246. case SPECIAL_VAR_SYMBOL:
  5247. /* Convert raw ^C to corresponding special variable reference */
  5248. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5249. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5250. /* fall through */
  5251. case '#':
  5252. /* non-comment #: "echo a#b" etc */
  5253. o_addchr(&ctx.word, ch);
  5254. continue; /* get next char */
  5255. case '$':
  5256. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5257. debug_printf_parse("parse_stream parse error: "
  5258. "parse_dollar returned 0 (error)\n");
  5259. goto parse_error;
  5260. }
  5261. continue; /* get next char */
  5262. case '"':
  5263. ctx.word.has_quoted_part = 1;
  5264. if (next == '"' && !ctx.pending_redirect) {
  5265. i_getch(input); /* eat second " */
  5266. insert_empty_quoted_str_marker:
  5267. nommu_addchr(&ctx.as_string, next);
  5268. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5269. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5270. continue; /* get next char */
  5271. }
  5272. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5273. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5274. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5275. goto parse_error;
  5276. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5277. continue; /* get next char */
  5278. #if ENABLE_HUSH_TICK
  5279. case '`': {
  5280. USE_FOR_NOMMU(unsigned pos;)
  5281. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5282. o_addchr(&ctx.word, '`');
  5283. USE_FOR_NOMMU(pos = ctx.word.length;)
  5284. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5285. goto parse_error;
  5286. # if !BB_MMU
  5287. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5288. o_addchr(&ctx.as_string, '`');
  5289. # endif
  5290. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5291. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5292. continue; /* get next char */
  5293. }
  5294. #endif
  5295. case ';':
  5296. #if ENABLE_HUSH_CASE
  5297. case_semi:
  5298. #endif
  5299. if (done_word(&ctx)) {
  5300. goto parse_error;
  5301. }
  5302. done_pipe(&ctx, PIPE_SEQ);
  5303. #if ENABLE_HUSH_CASE
  5304. /* Eat multiple semicolons, detect
  5305. * whether it means something special */
  5306. while (1) {
  5307. ch = i_peek_and_eat_bkslash_nl(input);
  5308. if (ch != ';')
  5309. break;
  5310. ch = i_getch(input);
  5311. nommu_addchr(&ctx.as_string, ch);
  5312. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5313. ctx.ctx_dsemicolon = 1;
  5314. ctx.ctx_res_w = RES_MATCH;
  5315. break;
  5316. }
  5317. }
  5318. #endif
  5319. new_cmd:
  5320. /* We just finished a cmd. New one may start
  5321. * with an assignment */
  5322. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5323. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5324. continue; /* get next char */
  5325. case '&':
  5326. if (done_word(&ctx)) {
  5327. goto parse_error;
  5328. }
  5329. if (next == '&') {
  5330. ch = i_getch(input);
  5331. nommu_addchr(&ctx.as_string, ch);
  5332. done_pipe(&ctx, PIPE_AND);
  5333. } else {
  5334. done_pipe(&ctx, PIPE_BG);
  5335. }
  5336. goto new_cmd;
  5337. case '|':
  5338. if (done_word(&ctx)) {
  5339. goto parse_error;
  5340. }
  5341. #if ENABLE_HUSH_CASE
  5342. if (ctx.ctx_res_w == RES_MATCH)
  5343. break; /* we are in case's "word | word)" */
  5344. #endif
  5345. if (next == '|') { /* || */
  5346. ch = i_getch(input);
  5347. nommu_addchr(&ctx.as_string, ch);
  5348. done_pipe(&ctx, PIPE_OR);
  5349. } else {
  5350. /* we could pick up a file descriptor choice here
  5351. * with redirect_opt_num(), but bash doesn't do it.
  5352. * "echo foo 2| cat" yields "foo 2". */
  5353. done_command(&ctx);
  5354. }
  5355. goto new_cmd;
  5356. case '(':
  5357. #if ENABLE_HUSH_CASE
  5358. /* "case... in [(]word)..." - skip '(' */
  5359. if (ctx.ctx_res_w == RES_MATCH
  5360. && ctx.command->argv == NULL /* not (word|(... */
  5361. && ctx.word.length == 0 /* not word(... */
  5362. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5363. ) {
  5364. continue; /* get next char */
  5365. }
  5366. #endif
  5367. /* fall through */
  5368. case '{': {
  5369. int n = parse_group(&ctx, input, ch);
  5370. if (n < 0) {
  5371. goto parse_error;
  5372. }
  5373. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5374. heredoc_cnt += n;
  5375. goto new_cmd;
  5376. }
  5377. case ')':
  5378. #if ENABLE_HUSH_CASE
  5379. if (ctx.ctx_res_w == RES_MATCH)
  5380. goto case_semi;
  5381. #endif
  5382. case '}':
  5383. /* proper use of this character is caught by end_trigger:
  5384. * if we see {, we call parse_group(..., end_trigger='}')
  5385. * and it will match } earlier (not here). */
  5386. G.last_exitcode = 2;
  5387. syntax_error_unexpected_ch(ch);
  5388. goto parse_error2;
  5389. default:
  5390. if (HUSH_DEBUG)
  5391. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5392. }
  5393. } /* while (1) */
  5394. parse_error:
  5395. G.last_exitcode = 1;
  5396. parse_error2:
  5397. {
  5398. struct parse_context *pctx;
  5399. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5400. /* Clean up allocated tree.
  5401. * Sample for finding leaks on syntax error recovery path.
  5402. * Run it from interactive shell, watch pmap `pidof hush`.
  5403. * while if false; then false; fi; do break; fi
  5404. * Samples to catch leaks at execution:
  5405. * while if (true | { true;}); then echo ok; fi; do break; done
  5406. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5407. */
  5408. pctx = &ctx;
  5409. do {
  5410. /* Update pipe/command counts,
  5411. * otherwise freeing may miss some */
  5412. done_pipe(pctx, PIPE_SEQ);
  5413. debug_printf_clean("freeing list %p from ctx %p\n",
  5414. pctx->list_head, pctx);
  5415. debug_print_tree(pctx->list_head, 0);
  5416. free_pipe_list(pctx->list_head);
  5417. debug_printf_clean("freed list %p\n", pctx->list_head);
  5418. #if !BB_MMU
  5419. o_free(&pctx->as_string);
  5420. #endif
  5421. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5422. if (pctx != &ctx) {
  5423. free(pctx);
  5424. }
  5425. IF_HAS_KEYWORDS(pctx = p2;)
  5426. } while (HAS_KEYWORDS && pctx);
  5427. o_free(&ctx.word);
  5428. #if !BB_MMU
  5429. if (pstring)
  5430. *pstring = NULL;
  5431. #endif
  5432. debug_leave();
  5433. return ERR_PTR;
  5434. }
  5435. }
  5436. /*** Execution routines ***/
  5437. /* Expansion can recurse, need forward decls: */
  5438. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5439. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5440. expand_string_to_string(str)
  5441. #endif
  5442. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5443. #if ENABLE_HUSH_TICK
  5444. static int process_command_subs(o_string *dest, const char *s);
  5445. #endif
  5446. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5447. /* expand_strvec_to_strvec() takes a list of strings, expands
  5448. * all variable references within and returns a pointer to
  5449. * a list of expanded strings, possibly with larger number
  5450. * of strings. (Think VAR="a b"; echo $VAR).
  5451. * This new list is allocated as a single malloc block.
  5452. * NULL-terminated list of char* pointers is at the beginning of it,
  5453. * followed by strings themselves.
  5454. * Caller can deallocate entire list by single free(list). */
  5455. /* A horde of its helpers come first: */
  5456. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5457. {
  5458. while (--len >= 0) {
  5459. char c = *str++;
  5460. #if ENABLE_HUSH_BRACE_EXPANSION
  5461. if (c == '{' || c == '}') {
  5462. /* { -> \{, } -> \} */
  5463. o_addchr(o, '\\');
  5464. /* And now we want to add { or } and continue:
  5465. * o_addchr(o, c);
  5466. * continue;
  5467. * luckily, just falling through achieves this.
  5468. */
  5469. }
  5470. #endif
  5471. o_addchr(o, c);
  5472. if (c == '\\') {
  5473. /* \z -> \\\z; \<eol> -> \\<eol> */
  5474. o_addchr(o, '\\');
  5475. if (len) {
  5476. len--;
  5477. o_addchr(o, '\\');
  5478. o_addchr(o, *str++);
  5479. }
  5480. }
  5481. }
  5482. }
  5483. /* Store given string, finalizing the word and starting new one whenever
  5484. * we encounter IFS char(s). This is used for expanding variable values.
  5485. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5486. * Return in output->ended_in_ifs:
  5487. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5488. */
  5489. static int expand_on_ifs(o_string *output, int n, const char *str)
  5490. {
  5491. int last_is_ifs = 0;
  5492. while (1) {
  5493. int word_len;
  5494. if (!*str) /* EOL - do not finalize word */
  5495. break;
  5496. word_len = strcspn(str, G.ifs);
  5497. if (word_len) {
  5498. /* We have WORD_LEN leading non-IFS chars */
  5499. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5500. o_addblock(output, str, word_len);
  5501. } else {
  5502. /* Protect backslashes against globbing up :)
  5503. * Example: "v='\*'; echo b$v" prints "b\*"
  5504. * (and does not try to glob on "*")
  5505. */
  5506. o_addblock_duplicate_backslash(output, str, word_len);
  5507. /*/ Why can't we do it easier? */
  5508. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5509. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5510. }
  5511. last_is_ifs = 0;
  5512. str += word_len;
  5513. if (!*str) /* EOL - do not finalize word */
  5514. break;
  5515. }
  5516. /* We know str here points to at least one IFS char */
  5517. last_is_ifs = 1;
  5518. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5519. if (!*str) /* EOL - do not finalize word */
  5520. break;
  5521. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5522. && strchr(G.ifs, *str) /* the second check would fail */
  5523. ) {
  5524. /* This is a non-whitespace $IFS char */
  5525. /* Skip it and IFS whitespace chars, start new word */
  5526. str++;
  5527. str += strspn(str, G.ifs_whitespace);
  5528. goto new_word;
  5529. }
  5530. /* Start new word... but not always! */
  5531. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5532. if (output->has_quoted_part
  5533. /*
  5534. * Case "v=' a'; echo $v":
  5535. * here nothing precedes the space in $v expansion,
  5536. * therefore we should not finish the word
  5537. * (IOW: if there *is* word to finalize, only then do it):
  5538. * It's okay if this accesses the byte before first argv[]:
  5539. * past call to o_save_ptr() cleared it to zero byte
  5540. * (grep for -prev-ifs-check-).
  5541. */
  5542. || output->data[output->length - 1]
  5543. ) {
  5544. new_word:
  5545. o_addchr(output, '\0');
  5546. debug_print_list("expand_on_ifs", output, n);
  5547. n = o_save_ptr(output, n);
  5548. }
  5549. }
  5550. output->ended_in_ifs = last_is_ifs;
  5551. debug_print_list("expand_on_ifs[1]", output, n);
  5552. return n;
  5553. }
  5554. /* Helper to expand $((...)) and heredoc body. These act as if
  5555. * they are in double quotes, with the exception that they are not :).
  5556. * Just the rules are similar: "expand only $var and `cmd`"
  5557. *
  5558. * Returns malloced string.
  5559. * As an optimization, we return NULL if expansion is not needed.
  5560. */
  5561. static char *encode_then_expand_string(const char *str)
  5562. {
  5563. char *exp_str;
  5564. struct in_str input;
  5565. o_string dest = NULL_O_STRING;
  5566. const char *cp;
  5567. cp = str;
  5568. for (;;) {
  5569. if (!*cp) return NULL; /* string has no special chars */
  5570. if (*cp == '$') break;
  5571. if (*cp == '\\') break;
  5572. #if ENABLE_HUSH_TICK
  5573. if (*cp == '`') break;
  5574. #endif
  5575. cp++;
  5576. }
  5577. /* We need to expand. Example:
  5578. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5579. */
  5580. setup_string_in_str(&input, str);
  5581. encode_string(NULL, &dest, &input, EOF);
  5582. //TODO: error check (encode_string returns 0 on error)?
  5583. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5584. exp_str = expand_string_to_string(dest.data,
  5585. EXP_FLAG_ESC_GLOB_CHARS,
  5586. /*unbackslash:*/ 1
  5587. );
  5588. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5589. o_free(&dest);
  5590. return exp_str;
  5591. }
  5592. static const char *first_special_char_in_vararg(const char *cp)
  5593. {
  5594. for (;;) {
  5595. if (!*cp) return NULL; /* string has no special chars */
  5596. if (*cp == '$') return cp;
  5597. if (*cp == '\\') return cp;
  5598. if (*cp == '\'') return cp;
  5599. if (*cp == '"') return cp;
  5600. #if ENABLE_HUSH_TICK
  5601. if (*cp == '`') return cp;
  5602. #endif
  5603. /* dquoted "${x:+ARG}" should not glob, therefore
  5604. * '*' et al require some non-literal processing: */
  5605. if (*cp == '*') return cp;
  5606. if (*cp == '?') return cp;
  5607. if (*cp == '[') return cp;
  5608. cp++;
  5609. }
  5610. }
  5611. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5612. * These can contain single- and double-quoted strings,
  5613. * and treated as if the ARG string is initially unquoted. IOW:
  5614. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5615. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5616. * (word splitting and globbing of the ${var...} result).
  5617. */
  5618. #if !BASH_PATTERN_SUBST
  5619. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5620. encode_then_expand_vararg(str, handle_squotes)
  5621. #endif
  5622. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5623. {
  5624. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5625. const int do_unbackslash = 0;
  5626. #endif
  5627. char *exp_str;
  5628. struct in_str input;
  5629. o_string dest = NULL_O_STRING;
  5630. if (!first_special_char_in_vararg(str)) {
  5631. /* string has no special chars */
  5632. return NULL;
  5633. }
  5634. setup_string_in_str(&input, str);
  5635. dest.data = xzalloc(1); /* start as "", not as NULL */
  5636. exp_str = NULL;
  5637. for (;;) {
  5638. int ch;
  5639. ch = i_getch(&input);
  5640. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5641. __func__, ch, ch, !!dest.o_expflags);
  5642. if (!dest.o_expflags) {
  5643. if (ch == EOF)
  5644. break;
  5645. if (handle_squotes && ch == '\'') {
  5646. if (!add_till_single_quote_dquoted(&dest, &input))
  5647. goto ret; /* error */
  5648. continue;
  5649. }
  5650. }
  5651. if (ch == EOF) {
  5652. syntax_error_unterm_ch('"');
  5653. goto ret; /* error */
  5654. }
  5655. if (ch == '"') {
  5656. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5657. continue;
  5658. }
  5659. if (ch == '\\') {
  5660. ch = i_getch(&input);
  5661. if (ch == EOF) {
  5662. //example? error message? syntax_error_unterm_ch('"');
  5663. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5664. goto ret;
  5665. }
  5666. o_addqchr(&dest, ch);
  5667. continue;
  5668. }
  5669. if (ch == '$') {
  5670. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5671. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5672. goto ret;
  5673. }
  5674. continue;
  5675. }
  5676. #if ENABLE_HUSH_TICK
  5677. if (ch == '`') {
  5678. //unsigned pos = dest->length;
  5679. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5680. o_addchr(&dest, 0x80 | '`');
  5681. if (!add_till_backquote(&dest, &input,
  5682. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5683. )
  5684. ) {
  5685. goto ret; /* error */
  5686. }
  5687. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5688. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5689. continue;
  5690. }
  5691. #endif
  5692. o_addQchr(&dest, ch);
  5693. } /* for (;;) */
  5694. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5695. exp_str = expand_string_to_string(dest.data,
  5696. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5697. do_unbackslash
  5698. );
  5699. ret:
  5700. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5701. o_free(&dest);
  5702. return exp_str;
  5703. }
  5704. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5705. */
  5706. static int encode_then_append_var_plusminus(o_string *output, int n,
  5707. char *str, int dquoted)
  5708. {
  5709. struct in_str input;
  5710. o_string dest = NULL_O_STRING;
  5711. if (!first_special_char_in_vararg(str)
  5712. && '\0' == str[strcspn(str, G.ifs)]
  5713. ) {
  5714. /* string has no special chars
  5715. * && string has no $IFS chars
  5716. */
  5717. if (dquoted) {
  5718. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5719. * set -- "${notexist-}"; echo $#
  5720. */
  5721. output->has_quoted_part = 1;
  5722. }
  5723. return expand_vars_to_list(output, n, str);
  5724. }
  5725. setup_string_in_str(&input, str);
  5726. for (;;) {
  5727. int ch;
  5728. ch = i_getch(&input);
  5729. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5730. __func__, ch, ch, dest.o_expflags);
  5731. if (!dest.o_expflags) {
  5732. if (ch == EOF)
  5733. break;
  5734. if (!dquoted && strchr(G.ifs, ch)) {
  5735. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5736. * do not assume we are at the start of the word (PREFIX above).
  5737. */
  5738. if (dest.data) {
  5739. n = expand_vars_to_list(output, n, dest.data);
  5740. o_free_and_set_NULL(&dest);
  5741. o_addchr(output, '\0');
  5742. n = o_save_ptr(output, n); /* create next word */
  5743. } else
  5744. if (output->length != o_get_last_ptr(output, n)
  5745. || output->has_quoted_part
  5746. ) {
  5747. /* For these cases:
  5748. * f() { for i; do echo "|$i|"; done; }; x=x
  5749. * f a${x:+ }b # 1st condition
  5750. * |a|
  5751. * |b|
  5752. * f ""${x:+ }b # 2nd condition
  5753. * ||
  5754. * |b|
  5755. */
  5756. o_addchr(output, '\0');
  5757. n = o_save_ptr(output, n); /* create next word */
  5758. }
  5759. continue;
  5760. }
  5761. if (!dquoted && ch == '\'') {
  5762. if (!add_till_single_quote_dquoted(&dest, &input))
  5763. goto ret; /* error */
  5764. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5765. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5766. continue;
  5767. }
  5768. }
  5769. if (ch == EOF) {
  5770. syntax_error_unterm_ch('"');
  5771. goto ret; /* error */
  5772. }
  5773. if (ch == '"') {
  5774. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5775. if (dest.o_expflags) {
  5776. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5777. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5778. }
  5779. continue;
  5780. }
  5781. if (ch == '\\') {
  5782. ch = i_getch(&input);
  5783. if (ch == EOF) {
  5784. //example? error message? syntax_error_unterm_ch('"');
  5785. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5786. goto ret;
  5787. }
  5788. o_addqchr(&dest, ch);
  5789. continue;
  5790. }
  5791. if (ch == '$') {
  5792. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5793. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5794. goto ret;
  5795. }
  5796. continue;
  5797. }
  5798. #if ENABLE_HUSH_TICK
  5799. if (ch == '`') {
  5800. //unsigned pos = dest->length;
  5801. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5802. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5803. if (!add_till_backquote(&dest, &input,
  5804. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5805. )
  5806. ) {
  5807. goto ret; /* error */
  5808. }
  5809. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5810. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5811. continue;
  5812. }
  5813. #endif
  5814. if (dquoted) {
  5815. /* Always glob-protect if in dquotes:
  5816. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5817. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5818. */
  5819. o_addqchr(&dest, ch);
  5820. } else {
  5821. /* Glob-protect only if char is quoted:
  5822. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5823. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5824. */
  5825. o_addQchr(&dest, ch);
  5826. }
  5827. } /* for (;;) */
  5828. if (dest.data) {
  5829. n = expand_vars_to_list(output, n, dest.data);
  5830. }
  5831. ret:
  5832. o_free(&dest);
  5833. return n;
  5834. }
  5835. #if ENABLE_FEATURE_SH_MATH
  5836. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5837. {
  5838. arith_state_t math_state;
  5839. arith_t res;
  5840. char *exp_str;
  5841. math_state.lookupvar = get_local_var_value;
  5842. math_state.setvar = set_local_var_from_halves;
  5843. //math_state.endofname = endofname;
  5844. exp_str = encode_then_expand_string(arg);
  5845. res = arith(&math_state, exp_str ? exp_str : arg);
  5846. free(exp_str);
  5847. if (errmsg_p)
  5848. *errmsg_p = math_state.errmsg;
  5849. if (math_state.errmsg)
  5850. msg_and_die_if_script(math_state.errmsg);
  5851. return res;
  5852. }
  5853. #endif
  5854. #if BASH_PATTERN_SUBST
  5855. /* ${var/[/]pattern[/repl]} helpers */
  5856. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5857. {
  5858. while (1) {
  5859. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5860. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5861. if (end) {
  5862. *size = end - val;
  5863. return val;
  5864. }
  5865. if (*val == '\0')
  5866. return NULL;
  5867. /* Optimization: if "*pat" did not match the start of "string",
  5868. * we know that "tring", "ring" etc will not match too:
  5869. */
  5870. if (pattern[0] == '*')
  5871. return NULL;
  5872. val++;
  5873. }
  5874. }
  5875. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5876. {
  5877. char *result = NULL;
  5878. unsigned res_len = 0;
  5879. unsigned repl_len = strlen(repl);
  5880. /* Null pattern never matches, including if "var" is empty */
  5881. if (!pattern[0])
  5882. return result; /* NULL, no replaces happened */
  5883. while (1) {
  5884. int size;
  5885. char *s = strstr_pattern(val, pattern, &size);
  5886. if (!s)
  5887. break;
  5888. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5889. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5890. res_len += (s - val) + repl_len;
  5891. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5892. val = s + size;
  5893. if (exp_op == '/')
  5894. break;
  5895. }
  5896. if (*val && result) {
  5897. result = xrealloc(result, res_len + strlen(val) + 1);
  5898. strcpy(result + res_len, val);
  5899. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5900. }
  5901. debug_printf_varexp("result:'%s'\n", result);
  5902. return result;
  5903. }
  5904. #endif /* BASH_PATTERN_SUBST */
  5905. static int append_str_maybe_ifs_split(o_string *output, int n,
  5906. int first_ch, const char *val)
  5907. {
  5908. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5909. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5910. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5911. if (val && val[0])
  5912. n = expand_on_ifs(output, n, val);
  5913. } else { /* quoted "$VAR" */
  5914. output->has_quoted_part = 1;
  5915. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5916. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5917. if (val && val[0])
  5918. o_addQstr(output, val);
  5919. }
  5920. return n;
  5921. }
  5922. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5923. */
  5924. static NOINLINE int expand_one_var(o_string *output, int n,
  5925. int first_ch, char *arg, char **pp)
  5926. {
  5927. const char *val;
  5928. char *to_be_freed;
  5929. char *p;
  5930. char *var;
  5931. char exp_op;
  5932. char exp_save = exp_save; /* for compiler */
  5933. char *exp_saveptr; /* points to expansion operator */
  5934. char *exp_word = exp_word; /* for compiler */
  5935. char arg0;
  5936. val = NULL;
  5937. to_be_freed = NULL;
  5938. p = *pp;
  5939. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5940. var = arg;
  5941. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5942. arg0 = arg[0];
  5943. arg[0] = (arg0 & 0x7f);
  5944. exp_op = 0;
  5945. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5946. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5947. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5948. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5949. ) {
  5950. /* It must be length operator: ${#var} */
  5951. var++;
  5952. exp_op = 'L';
  5953. } else {
  5954. /* Maybe handle parameter expansion */
  5955. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5956. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5957. ) {
  5958. /* ${?:0}, ${#[:]%0} etc */
  5959. exp_saveptr = var + 1;
  5960. } else {
  5961. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5962. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5963. }
  5964. exp_op = exp_save = *exp_saveptr;
  5965. if (exp_op) {
  5966. exp_word = exp_saveptr + 1;
  5967. if (exp_op == ':') {
  5968. exp_op = *exp_word++;
  5969. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5970. if (BASH_SUBSTR
  5971. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5972. ) {
  5973. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5974. exp_op = ':';
  5975. exp_word--;
  5976. }
  5977. }
  5978. *exp_saveptr = '\0';
  5979. } /* else: it's not an expansion op, but bare ${var} */
  5980. }
  5981. /* Look up the variable in question */
  5982. if (isdigit(var[0])) {
  5983. /* parse_dollar should have vetted var for us */
  5984. int nn = xatoi_positive(var);
  5985. if (nn < G.global_argc)
  5986. val = G.global_argv[nn];
  5987. /* else val remains NULL: $N with too big N */
  5988. } else {
  5989. switch (var[0]) {
  5990. case '$': /* pid */
  5991. val = utoa(G.root_pid);
  5992. break;
  5993. case '!': /* bg pid */
  5994. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  5995. break;
  5996. case '?': /* exitcode */
  5997. val = utoa(G.last_exitcode);
  5998. break;
  5999. case '#': /* argc */
  6000. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6001. break;
  6002. case '-': { /* active options */
  6003. /* Check set_mode() to see what option chars we support */
  6004. char *cp;
  6005. val = cp = G.optstring_buf;
  6006. if (G.o_opt[OPT_O_ERREXIT])
  6007. *cp++ = 'e';
  6008. if (G_interactive_fd)
  6009. *cp++ = 'i';
  6010. if (G_x_mode)
  6011. *cp++ = 'x';
  6012. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6013. * commands read but are not executed,
  6014. * so $- can not execute too, 'n' is never seen in $-.
  6015. */
  6016. if (G.opt_c)
  6017. *cp++ = 'c';
  6018. if (G.opt_s)
  6019. *cp++ = 's';
  6020. *cp = '\0';
  6021. break;
  6022. }
  6023. default:
  6024. val = get_local_var_value(var);
  6025. }
  6026. }
  6027. /* Handle any expansions */
  6028. if (exp_op == 'L') {
  6029. reinit_unicode_for_hush();
  6030. debug_printf_expand("expand: length(%s)=", val);
  6031. val = utoa(val ? unicode_strlen(val) : 0);
  6032. debug_printf_expand("%s\n", val);
  6033. } else if (exp_op) {
  6034. if (exp_op == '%' || exp_op == '#') {
  6035. /* Standard-mandated substring removal ops:
  6036. * ${parameter%word} - remove smallest suffix pattern
  6037. * ${parameter%%word} - remove largest suffix pattern
  6038. * ${parameter#word} - remove smallest prefix pattern
  6039. * ${parameter##word} - remove largest prefix pattern
  6040. *
  6041. * Word is expanded to produce a glob pattern.
  6042. * Then var's value is matched to it and matching part removed.
  6043. */
  6044. //FIXME: ${x#...${...}...}
  6045. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6046. //inner ${...} may have side effects!
  6047. if (val && val[0]) {
  6048. char *t;
  6049. char *exp_exp_word;
  6050. char *loc;
  6051. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6052. if (exp_op == *exp_word) /* ## or %% */
  6053. exp_word++;
  6054. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6055. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6056. if (exp_exp_word)
  6057. exp_word = exp_exp_word;
  6058. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6059. /*
  6060. * HACK ALERT. We depend here on the fact that
  6061. * G.global_argv and results of utoa and get_local_var_value
  6062. * are actually in writable memory:
  6063. * scan_and_match momentarily stores NULs there.
  6064. */
  6065. t = (char*)val;
  6066. loc = scan_and_match(t, exp_word, scan_flags);
  6067. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6068. free(exp_exp_word);
  6069. if (loc) { /* match was found */
  6070. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6071. val = loc; /* take right part */
  6072. else /* %[%] */
  6073. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6074. }
  6075. }
  6076. }
  6077. #if BASH_PATTERN_SUBST
  6078. else if (exp_op == '/' || exp_op == '\\') {
  6079. /* It's ${var/[/]pattern[/repl]} thing.
  6080. * Note that in encoded form it has TWO parts:
  6081. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6082. * and if // is used, it is encoded as \:
  6083. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6084. */
  6085. if (val && val[0]) {
  6086. /* pattern uses non-standard expansion.
  6087. * repl should be unbackslashed and globbed
  6088. * by the usual expansion rules:
  6089. * >az >bz
  6090. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6091. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6092. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6093. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6094. * (note that a*z _pattern_ is never globbed!)
  6095. */
  6096. char *pattern, *repl, *t;
  6097. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6098. if (!pattern)
  6099. pattern = xstrdup(exp_word);
  6100. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6101. *p++ = SPECIAL_VAR_SYMBOL;
  6102. exp_word = p;
  6103. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6104. *p = '\0';
  6105. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6106. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6107. /* HACK ALERT. We depend here on the fact that
  6108. * G.global_argv and results of utoa and get_local_var_value
  6109. * are actually in writable memory:
  6110. * replace_pattern momentarily stores NULs there. */
  6111. t = (char*)val;
  6112. to_be_freed = replace_pattern(t,
  6113. pattern,
  6114. (repl ? repl : exp_word),
  6115. exp_op);
  6116. if (to_be_freed) /* at least one replace happened */
  6117. val = to_be_freed;
  6118. free(pattern);
  6119. free(repl);
  6120. } else {
  6121. /* Empty variable always gives nothing */
  6122. // "v=''; echo ${v/*/w}" prints "", not "w"
  6123. /* Just skip "replace" part */
  6124. *p++ = SPECIAL_VAR_SYMBOL;
  6125. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6126. *p = '\0';
  6127. }
  6128. }
  6129. #endif /* BASH_PATTERN_SUBST */
  6130. else if (exp_op == ':') {
  6131. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6132. /* It's ${var:N[:M]} bashism.
  6133. * Note that in encoded form it has TWO parts:
  6134. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6135. */
  6136. arith_t beg, len;
  6137. const char *errmsg;
  6138. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6139. if (errmsg)
  6140. goto arith_err;
  6141. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6142. *p++ = SPECIAL_VAR_SYMBOL;
  6143. exp_word = p;
  6144. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6145. *p = '\0';
  6146. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6147. if (errmsg)
  6148. goto arith_err;
  6149. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6150. if (beg < 0) {
  6151. /* negative beg counts from the end */
  6152. beg = (arith_t)strlen(val) + beg;
  6153. if (beg < 0) /* ${v: -999999} is "" */
  6154. beg = len = 0;
  6155. }
  6156. debug_printf_varexp("from val:'%s'\n", val);
  6157. if (len < 0) {
  6158. /* in bash, len=-n means strlen()-n */
  6159. len = (arith_t)strlen(val) - beg + len;
  6160. if (len < 0) /* bash compat */
  6161. msg_and_die_if_script("%s: substring expression < 0", var);
  6162. }
  6163. if (len <= 0 || !val || beg >= strlen(val)) {
  6164. arith_err:
  6165. val = NULL;
  6166. } else {
  6167. /* Paranoia. What if user entered 9999999999999
  6168. * which fits in arith_t but not int? */
  6169. if (len >= INT_MAX)
  6170. len = INT_MAX;
  6171. val = to_be_freed = xstrndup(val + beg, len);
  6172. }
  6173. debug_printf_varexp("val:'%s'\n", val);
  6174. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6175. msg_and_die_if_script("malformed ${%s:...}", var);
  6176. val = NULL;
  6177. #endif
  6178. } else { /* one of "-=+?" */
  6179. /* Standard-mandated substitution ops:
  6180. * ${var?word} - indicate error if unset
  6181. * If var is unset, word (or a message indicating it is unset
  6182. * if word is null) is written to standard error
  6183. * and the shell exits with a non-zero exit status.
  6184. * Otherwise, the value of var is substituted.
  6185. * ${var-word} - use default value
  6186. * If var is unset, word is substituted.
  6187. * ${var=word} - assign and use default value
  6188. * If var is unset, word is assigned to var.
  6189. * In all cases, final value of var is substituted.
  6190. * ${var+word} - use alternative value
  6191. * If var is unset, null is substituted.
  6192. * Otherwise, word is substituted.
  6193. *
  6194. * Word is subjected to tilde expansion, parameter expansion,
  6195. * command substitution, and arithmetic expansion.
  6196. * If word is not needed, it is not expanded.
  6197. *
  6198. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6199. * but also treat null var as if it is unset.
  6200. *
  6201. * Word-splitting and single quote behavior:
  6202. *
  6203. * $ f() { for i; do echo "|$i|"; done; };
  6204. *
  6205. * $ x=; f ${x:?'x y' z}
  6206. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6207. * $ x=; f "${x:?'x y' z}"
  6208. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6209. *
  6210. * $ x=; f ${x:='x y' z}
  6211. * |x|
  6212. * |y|
  6213. * |z|
  6214. * $ x=; f "${x:='x y' z}"
  6215. * |'x y' z|
  6216. *
  6217. * $ x=x; f ${x:+'x y' z}
  6218. * |x y|
  6219. * |z|
  6220. * $ x=x; f "${x:+'x y' z}"
  6221. * |'x y' z|
  6222. *
  6223. * $ x=; f ${x:-'x y' z}
  6224. * |x y|
  6225. * |z|
  6226. * $ x=; f "${x:-'x y' z}"
  6227. * |'x y' z|
  6228. */
  6229. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6230. if (exp_op == '+')
  6231. use_word = !use_word;
  6232. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6233. (exp_save == ':') ? "true" : "false", use_word);
  6234. if (use_word) {
  6235. if (exp_op == '+' || exp_op == '-') {
  6236. /* ${var+word} - use alternative value */
  6237. /* ${var-word} - use default value */
  6238. n = encode_then_append_var_plusminus(output, n, exp_word,
  6239. /*dquoted:*/ (arg0 & 0x80)
  6240. );
  6241. val = NULL;
  6242. } else {
  6243. /* ${var?word} - indicate error if unset */
  6244. /* ${var=word} - assign and use default value */
  6245. to_be_freed = encode_then_expand_vararg(exp_word,
  6246. /*handle_squotes:*/ !(arg0 & 0x80),
  6247. /*unbackslash:*/ 0
  6248. );
  6249. if (to_be_freed)
  6250. exp_word = to_be_freed;
  6251. if (exp_op == '?') {
  6252. /* mimic bash message */
  6253. msg_and_die_if_script("%s: %s",
  6254. var,
  6255. exp_word[0]
  6256. ? exp_word
  6257. : "parameter null or not set"
  6258. /* ash has more specific messages, a-la: */
  6259. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6260. );
  6261. //TODO: how interactive bash aborts expansion mid-command?
  6262. //It aborts the entire line, returns to prompt:
  6263. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6264. // bash: x: x y z
  6265. // $
  6266. // ("echo YO" is not executed, neither the f function call)
  6267. } else {
  6268. val = exp_word;
  6269. }
  6270. if (exp_op == '=') {
  6271. /* ${var=[word]} or ${var:=[word]} */
  6272. if (isdigit(var[0]) || var[0] == '#') {
  6273. /* mimic bash message */
  6274. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6275. val = NULL;
  6276. } else {
  6277. char *new_var = xasprintf("%s=%s", var, val);
  6278. set_local_var(new_var, /*flag:*/ 0);
  6279. }
  6280. }
  6281. }
  6282. }
  6283. } /* one of "-=+?" */
  6284. *exp_saveptr = exp_save;
  6285. } /* if (exp_op) */
  6286. arg[0] = arg0;
  6287. *pp = p;
  6288. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6289. free(to_be_freed);
  6290. return n;
  6291. }
  6292. /* Expand all variable references in given string, adding words to list[]
  6293. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6294. * to be filled). This routine is extremely tricky: has to deal with
  6295. * variables/parameters with whitespace, $* and $@, and constructs like
  6296. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6297. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6298. {
  6299. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6300. * expansion of right-hand side of assignment == 1-element expand.
  6301. */
  6302. char cant_be_null = 0; /* only bit 0x80 matters */
  6303. char *p;
  6304. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6305. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6306. debug_print_list("expand_vars_to_list[0]", output, n);
  6307. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6308. char first_ch;
  6309. #if ENABLE_FEATURE_SH_MATH
  6310. char arith_buf[sizeof(arith_t)*3 + 2];
  6311. #endif
  6312. if (output->ended_in_ifs) {
  6313. o_addchr(output, '\0');
  6314. n = o_save_ptr(output, n);
  6315. output->ended_in_ifs = 0;
  6316. }
  6317. o_addblock(output, arg, p - arg);
  6318. debug_print_list("expand_vars_to_list[1]", output, n);
  6319. arg = ++p;
  6320. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6321. /* Fetch special var name (if it is indeed one of them)
  6322. * and quote bit, force the bit on if singleword expansion -
  6323. * important for not getting v=$@ expand to many words. */
  6324. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6325. /* Is this variable quoted and thus expansion can't be null?
  6326. * "$@" is special. Even if quoted, it can still
  6327. * expand to nothing (not even an empty string),
  6328. * thus it is excluded. */
  6329. if ((first_ch & 0x7f) != '@')
  6330. cant_be_null |= first_ch;
  6331. switch (first_ch & 0x7f) {
  6332. /* Highest bit in first_ch indicates that var is double-quoted */
  6333. case '*':
  6334. case '@': {
  6335. int i;
  6336. if (!G.global_argv[1])
  6337. break;
  6338. i = 1;
  6339. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6340. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6341. while (G.global_argv[i]) {
  6342. n = expand_on_ifs(output, n, G.global_argv[i]);
  6343. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6344. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6345. /* this argv[] is not empty and not last:
  6346. * put terminating NUL, start new word */
  6347. o_addchr(output, '\0');
  6348. debug_print_list("expand_vars_to_list[2]", output, n);
  6349. n = o_save_ptr(output, n);
  6350. debug_print_list("expand_vars_to_list[3]", output, n);
  6351. }
  6352. }
  6353. } else
  6354. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6355. * and in this case should treat it like '$*' - see 'else...' below */
  6356. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6357. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6358. ) {
  6359. while (1) {
  6360. o_addQstr(output, G.global_argv[i]);
  6361. if (++i >= G.global_argc)
  6362. break;
  6363. o_addchr(output, '\0');
  6364. debug_print_list("expand_vars_to_list[4]", output, n);
  6365. n = o_save_ptr(output, n);
  6366. }
  6367. } else { /* quoted $* (or v="$@" case): add as one word */
  6368. while (1) {
  6369. o_addQstr(output, G.global_argv[i]);
  6370. if (!G.global_argv[++i])
  6371. break;
  6372. if (G.ifs[0])
  6373. o_addchr(output, G.ifs[0]);
  6374. }
  6375. output->has_quoted_part = 1;
  6376. }
  6377. break;
  6378. }
  6379. case SPECIAL_VAR_SYMBOL: {
  6380. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6381. /* "Empty variable", used to make "" etc to not disappear */
  6382. output->has_quoted_part = 1;
  6383. cant_be_null = 0x80;
  6384. arg++;
  6385. break;
  6386. }
  6387. case SPECIAL_VAR_QUOTED_SVS:
  6388. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6389. /* "^C variable", represents literal ^C char (possible in scripts) */
  6390. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6391. arg++;
  6392. break;
  6393. #if ENABLE_HUSH_TICK
  6394. case '`': {
  6395. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6396. o_string subst_result = NULL_O_STRING;
  6397. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6398. arg++;
  6399. /* Can't just stuff it into output o_string,
  6400. * expanded result may need to be globbed
  6401. * and $IFS-split */
  6402. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6403. G.last_exitcode = process_command_subs(&subst_result, arg);
  6404. G.expand_exitcode = G.last_exitcode;
  6405. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6406. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6407. o_free(&subst_result);
  6408. break;
  6409. }
  6410. #endif
  6411. #if ENABLE_FEATURE_SH_MATH
  6412. case '+': {
  6413. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6414. arith_t res;
  6415. arg++; /* skip '+' */
  6416. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6417. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6418. res = expand_and_evaluate_arith(arg, NULL);
  6419. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6420. sprintf(arith_buf, ARITH_FMT, res);
  6421. o_addstr(output, arith_buf);
  6422. break;
  6423. }
  6424. #endif
  6425. default:
  6426. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6427. n = expand_one_var(output, n, first_ch, arg, &p);
  6428. break;
  6429. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6430. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6431. * Do the check to avoid writing to a const string. */
  6432. if (*p != SPECIAL_VAR_SYMBOL)
  6433. *p = SPECIAL_VAR_SYMBOL;
  6434. arg = ++p;
  6435. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6436. if (*arg) {
  6437. /* handle trailing string */
  6438. if (output->ended_in_ifs) {
  6439. o_addchr(output, '\0');
  6440. n = o_save_ptr(output, n);
  6441. }
  6442. debug_print_list("expand_vars_to_list[a]", output, n);
  6443. /* this part is literal, and it was already pre-quoted
  6444. * if needed (much earlier), do not use o_addQstr here!
  6445. */
  6446. o_addstr(output, arg);
  6447. debug_print_list("expand_vars_to_list[b]", output, n);
  6448. } else
  6449. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6450. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6451. && !output->has_quoted_part
  6452. ) {
  6453. n--;
  6454. /* allow to reuse list[n] later without re-growth */
  6455. output->has_empty_slot = 1;
  6456. }
  6457. return n;
  6458. }
  6459. static char **expand_variables(char **argv, unsigned expflags)
  6460. {
  6461. int n;
  6462. char **list;
  6463. o_string output = NULL_O_STRING;
  6464. output.o_expflags = expflags;
  6465. n = 0;
  6466. for (;;) {
  6467. /* go to next list[n] */
  6468. output.ended_in_ifs = 0;
  6469. n = o_save_ptr(&output, n);
  6470. if (!*argv)
  6471. break;
  6472. /* expand argv[i] */
  6473. n = expand_vars_to_list(&output, n, *argv++);
  6474. /* if (!output->has_empty_slot) -- need this?? */
  6475. o_addchr(&output, '\0');
  6476. }
  6477. debug_print_list("expand_variables", &output, n);
  6478. /* output.data (malloced in one block) gets returned in "list" */
  6479. list = o_finalize_list(&output, n);
  6480. debug_print_strings("expand_variables[1]", list);
  6481. return list;
  6482. }
  6483. static char **expand_strvec_to_strvec(char **argv)
  6484. {
  6485. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6486. }
  6487. #if defined(CMD_SINGLEWORD_NOGLOB)
  6488. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6489. {
  6490. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6491. }
  6492. #endif
  6493. /* Used for expansion of right hand of assignments,
  6494. * $((...)), heredocs, variable expansion parts.
  6495. *
  6496. * NB: should NOT do globbing!
  6497. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6498. */
  6499. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6500. {
  6501. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6502. const int do_unbackslash = 1;
  6503. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6504. #endif
  6505. char *argv[2], **list;
  6506. debug_printf_expand("string_to_string<='%s'\n", str);
  6507. /* This is generally an optimization, but it also
  6508. * handles "", which otherwise trips over !list[0] check below.
  6509. * (is this ever happens that we actually get str="" here?)
  6510. */
  6511. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6512. //TODO: Can use on strings with \ too, just unbackslash() them?
  6513. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6514. return xstrdup(str);
  6515. }
  6516. argv[0] = (char*)str;
  6517. argv[1] = NULL;
  6518. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6519. if (!list[0]) {
  6520. /* Example where it happens:
  6521. * x=; echo ${x:-"$@"}
  6522. */
  6523. ((char*)list)[0] = '\0';
  6524. } else {
  6525. if (HUSH_DEBUG)
  6526. if (list[1])
  6527. bb_error_msg_and_die("BUG in varexp2");
  6528. /* actually, just move string 2*sizeof(char*) bytes back */
  6529. overlapping_strcpy((char*)list, list[0]);
  6530. if (do_unbackslash)
  6531. unbackslash((char*)list);
  6532. }
  6533. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6534. return (char*)list;
  6535. }
  6536. #if 0
  6537. static char* expand_strvec_to_string(char **argv)
  6538. {
  6539. char **list;
  6540. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6541. /* Convert all NULs to spaces */
  6542. if (list[0]) {
  6543. int n = 1;
  6544. while (list[n]) {
  6545. if (HUSH_DEBUG)
  6546. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6547. bb_error_msg_and_die("BUG in varexp3");
  6548. /* bash uses ' ' regardless of $IFS contents */
  6549. list[n][-1] = ' ';
  6550. n++;
  6551. }
  6552. }
  6553. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6554. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6555. return (char*)list;
  6556. }
  6557. #endif
  6558. static char **expand_assignments(char **argv, int count)
  6559. {
  6560. int i;
  6561. char **p;
  6562. G.expanded_assignments = p = NULL;
  6563. /* Expand assignments into one string each */
  6564. for (i = 0; i < count; i++) {
  6565. p = add_string_to_strings(p,
  6566. expand_string_to_string(argv[i],
  6567. EXP_FLAG_ESC_GLOB_CHARS,
  6568. /*unbackslash:*/ 1
  6569. )
  6570. );
  6571. G.expanded_assignments = p;
  6572. }
  6573. G.expanded_assignments = NULL;
  6574. return p;
  6575. }
  6576. static void switch_off_special_sigs(unsigned mask)
  6577. {
  6578. unsigned sig = 0;
  6579. while ((mask >>= 1) != 0) {
  6580. sig++;
  6581. if (!(mask & 1))
  6582. continue;
  6583. #if ENABLE_HUSH_TRAP
  6584. if (G_traps) {
  6585. if (G_traps[sig] && !G_traps[sig][0])
  6586. /* trap is '', has to remain SIG_IGN */
  6587. continue;
  6588. free(G_traps[sig]);
  6589. G_traps[sig] = NULL;
  6590. }
  6591. #endif
  6592. /* We are here only if no trap or trap was not '' */
  6593. install_sighandler(sig, SIG_DFL);
  6594. }
  6595. }
  6596. #if BB_MMU
  6597. /* never called */
  6598. void re_execute_shell(char ***to_free, const char *s,
  6599. char *g_argv0, char **g_argv,
  6600. char **builtin_argv) NORETURN;
  6601. static void reset_traps_to_defaults(void)
  6602. {
  6603. /* This function is always called in a child shell
  6604. * after fork (not vfork, NOMMU doesn't use this function).
  6605. */
  6606. IF_HUSH_TRAP(unsigned sig;)
  6607. unsigned mask;
  6608. /* Child shells are not interactive.
  6609. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6610. * Testcase: (while :; do :; done) + ^Z should background.
  6611. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6612. */
  6613. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6614. if (!G_traps && !mask)
  6615. return; /* already no traps and no special sigs */
  6616. /* Switch off special sigs */
  6617. switch_off_special_sigs(mask);
  6618. # if ENABLE_HUSH_JOB
  6619. G_fatal_sig_mask = 0;
  6620. # endif
  6621. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6622. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6623. * remain set in G.special_sig_mask */
  6624. # if ENABLE_HUSH_TRAP
  6625. if (!G_traps)
  6626. return;
  6627. /* Reset all sigs to default except ones with empty traps */
  6628. for (sig = 0; sig < NSIG; sig++) {
  6629. if (!G_traps[sig])
  6630. continue; /* no trap: nothing to do */
  6631. if (!G_traps[sig][0])
  6632. continue; /* empty trap: has to remain SIG_IGN */
  6633. /* sig has non-empty trap, reset it: */
  6634. free(G_traps[sig]);
  6635. G_traps[sig] = NULL;
  6636. /* There is no signal for trap 0 (EXIT) */
  6637. if (sig == 0)
  6638. continue;
  6639. install_sighandler(sig, pick_sighandler(sig));
  6640. }
  6641. # endif
  6642. }
  6643. #else /* !BB_MMU */
  6644. static void re_execute_shell(char ***to_free, const char *s,
  6645. char *g_argv0, char **g_argv,
  6646. char **builtin_argv) NORETURN;
  6647. static void re_execute_shell(char ***to_free, const char *s,
  6648. char *g_argv0, char **g_argv,
  6649. char **builtin_argv)
  6650. {
  6651. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6652. /* delims + 2 * (number of bytes in printed hex numbers) */
  6653. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6654. char *heredoc_argv[4];
  6655. struct variable *cur;
  6656. # if ENABLE_HUSH_FUNCTIONS
  6657. struct function *funcp;
  6658. # endif
  6659. char **argv, **pp;
  6660. unsigned cnt;
  6661. unsigned long long empty_trap_mask;
  6662. if (!g_argv0) { /* heredoc */
  6663. argv = heredoc_argv;
  6664. argv[0] = (char *) G.argv0_for_re_execing;
  6665. argv[1] = (char *) "-<";
  6666. argv[2] = (char *) s;
  6667. argv[3] = NULL;
  6668. pp = &argv[3]; /* used as pointer to empty environment */
  6669. goto do_exec;
  6670. }
  6671. cnt = 0;
  6672. pp = builtin_argv;
  6673. if (pp) while (*pp++)
  6674. cnt++;
  6675. empty_trap_mask = 0;
  6676. if (G_traps) {
  6677. int sig;
  6678. for (sig = 1; sig < NSIG; sig++) {
  6679. if (G_traps[sig] && !G_traps[sig][0])
  6680. empty_trap_mask |= 1LL << sig;
  6681. }
  6682. }
  6683. sprintf(param_buf, NOMMU_HACK_FMT
  6684. , (unsigned) G.root_pid
  6685. , (unsigned) G.root_ppid
  6686. , (unsigned) G.last_bg_pid
  6687. , (unsigned) G.last_exitcode
  6688. , cnt
  6689. , empty_trap_mask
  6690. IF_HUSH_LOOPS(, G.depth_of_loop)
  6691. );
  6692. # undef NOMMU_HACK_FMT
  6693. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6694. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6695. */
  6696. cnt += 6;
  6697. for (cur = G.top_var; cur; cur = cur->next) {
  6698. if (!cur->flg_export || cur->flg_read_only)
  6699. cnt += 2;
  6700. }
  6701. # if ENABLE_HUSH_FUNCTIONS
  6702. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6703. cnt += 3;
  6704. # endif
  6705. pp = g_argv;
  6706. while (*pp++)
  6707. cnt++;
  6708. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6709. *pp++ = (char *) G.argv0_for_re_execing;
  6710. *pp++ = param_buf;
  6711. for (cur = G.top_var; cur; cur = cur->next) {
  6712. if (strcmp(cur->varstr, hush_version_str) == 0)
  6713. continue;
  6714. if (cur->flg_read_only) {
  6715. *pp++ = (char *) "-R";
  6716. *pp++ = cur->varstr;
  6717. } else if (!cur->flg_export) {
  6718. *pp++ = (char *) "-V";
  6719. *pp++ = cur->varstr;
  6720. }
  6721. }
  6722. # if ENABLE_HUSH_FUNCTIONS
  6723. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6724. *pp++ = (char *) "-F";
  6725. *pp++ = funcp->name;
  6726. *pp++ = funcp->body_as_string;
  6727. }
  6728. # endif
  6729. /* We can pass activated traps here. Say, -Tnn:trap_string
  6730. *
  6731. * However, POSIX says that subshells reset signals with traps
  6732. * to SIG_DFL.
  6733. * I tested bash-3.2 and it not only does that with true subshells
  6734. * of the form ( list ), but with any forked children shells.
  6735. * I set trap "echo W" WINCH; and then tried:
  6736. *
  6737. * { echo 1; sleep 20; echo 2; } &
  6738. * while true; do echo 1; sleep 20; echo 2; break; done &
  6739. * true | { echo 1; sleep 20; echo 2; } | cat
  6740. *
  6741. * In all these cases sending SIGWINCH to the child shell
  6742. * did not run the trap. If I add trap "echo V" WINCH;
  6743. * _inside_ group (just before echo 1), it works.
  6744. *
  6745. * I conclude it means we don't need to pass active traps here.
  6746. */
  6747. *pp++ = (char *) "-c";
  6748. *pp++ = (char *) s;
  6749. if (builtin_argv) {
  6750. while (*++builtin_argv)
  6751. *pp++ = *builtin_argv;
  6752. *pp++ = (char *) "";
  6753. }
  6754. *pp++ = g_argv0;
  6755. while (*g_argv)
  6756. *pp++ = *g_argv++;
  6757. /* *pp = NULL; - is already there */
  6758. pp = environ;
  6759. do_exec:
  6760. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6761. /* Don't propagate SIG_IGN to the child */
  6762. if (SPECIAL_JOBSTOP_SIGS != 0)
  6763. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6764. execve(bb_busybox_exec_path, argv, pp);
  6765. /* Fallback. Useful for init=/bin/hush usage etc */
  6766. if (argv[0][0] == '/')
  6767. execve(argv[0], argv, pp);
  6768. xfunc_error_retval = 127;
  6769. bb_error_msg_and_die("can't re-execute the shell");
  6770. }
  6771. #endif /* !BB_MMU */
  6772. static int run_and_free_list(struct pipe *pi);
  6773. /* Executing from string: eval, sh -c '...'
  6774. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6775. * end_trigger controls how often we stop parsing
  6776. * NUL: parse all, execute, return
  6777. * ';': parse till ';' or newline, execute, repeat till EOF
  6778. */
  6779. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6780. {
  6781. /* Why we need empty flag?
  6782. * An obscure corner case "false; ``; echo $?":
  6783. * empty command in `` should still set $? to 0.
  6784. * But we can't just set $? to 0 at the start,
  6785. * this breaks "false; echo `echo $?`" case.
  6786. */
  6787. bool empty = 1;
  6788. while (1) {
  6789. struct pipe *pipe_list;
  6790. #if ENABLE_HUSH_INTERACTIVE
  6791. if (end_trigger == ';') {
  6792. G.promptmode = 0; /* PS1 */
  6793. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6794. }
  6795. #endif
  6796. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6797. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6798. /* If we are in "big" script
  6799. * (not in `cmd` or something similar)...
  6800. */
  6801. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6802. /* Discard cached input (rest of line) */
  6803. int ch = inp->last_char;
  6804. while (ch != EOF && ch != '\n') {
  6805. //bb_error_msg("Discarded:'%c'", ch);
  6806. ch = i_getch(inp);
  6807. }
  6808. /* Force prompt */
  6809. inp->p = NULL;
  6810. /* This stream isn't empty */
  6811. empty = 0;
  6812. continue;
  6813. }
  6814. if (!pipe_list && empty)
  6815. G.last_exitcode = 0;
  6816. break;
  6817. }
  6818. debug_print_tree(pipe_list, 0);
  6819. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6820. run_and_free_list(pipe_list);
  6821. empty = 0;
  6822. if (G_flag_return_in_progress == 1)
  6823. break;
  6824. }
  6825. }
  6826. static void parse_and_run_string(const char *s)
  6827. {
  6828. struct in_str input;
  6829. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6830. setup_string_in_str(&input, s);
  6831. parse_and_run_stream(&input, '\0');
  6832. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6833. }
  6834. static void parse_and_run_file(HFILE *fp)
  6835. {
  6836. struct in_str input;
  6837. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6838. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6839. setup_file_in_str(&input, fp);
  6840. parse_and_run_stream(&input, ';');
  6841. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6842. }
  6843. #if ENABLE_HUSH_TICK
  6844. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6845. {
  6846. pid_t pid;
  6847. int channel[2];
  6848. # if !BB_MMU
  6849. char **to_free = NULL;
  6850. # endif
  6851. xpipe(channel);
  6852. pid = BB_MMU ? xfork() : xvfork();
  6853. if (pid == 0) { /* child */
  6854. disable_restore_tty_pgrp_on_exit();
  6855. /* Process substitution is not considered to be usual
  6856. * 'command execution'.
  6857. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6858. */
  6859. bb_signals(0
  6860. + (1 << SIGTSTP)
  6861. + (1 << SIGTTIN)
  6862. + (1 << SIGTTOU)
  6863. , SIG_IGN);
  6864. close(channel[0]); /* NB: close _first_, then move fd! */
  6865. xmove_fd(channel[1], 1);
  6866. # if ENABLE_HUSH_TRAP
  6867. /* Awful hack for `trap` or $(trap).
  6868. *
  6869. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6870. * contains an example where "trap" is executed in a subshell:
  6871. *
  6872. * save_traps=$(trap)
  6873. * ...
  6874. * eval "$save_traps"
  6875. *
  6876. * Standard does not say that "trap" in subshell shall print
  6877. * parent shell's traps. It only says that its output
  6878. * must have suitable form, but then, in the above example
  6879. * (which is not supposed to be normative), it implies that.
  6880. *
  6881. * bash (and probably other shell) does implement it
  6882. * (traps are reset to defaults, but "trap" still shows them),
  6883. * but as a result, "trap" logic is hopelessly messed up:
  6884. *
  6885. * # trap
  6886. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6887. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6888. * # true | trap <--- trap is in subshell - no output (ditto)
  6889. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6890. * trap -- 'echo Ho' SIGWINCH
  6891. * # echo `(trap)` <--- in subshell in subshell - output
  6892. * trap -- 'echo Ho' SIGWINCH
  6893. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6894. * trap -- 'echo Ho' SIGWINCH
  6895. *
  6896. * The rules when to forget and when to not forget traps
  6897. * get really complex and nonsensical.
  6898. *
  6899. * Our solution: ONLY bare $(trap) or `trap` is special.
  6900. */
  6901. s = skip_whitespace(s);
  6902. if (is_prefixed_with(s, "trap")
  6903. && skip_whitespace(s + 4)[0] == '\0'
  6904. ) {
  6905. static const char *const argv[] = { NULL, NULL };
  6906. builtin_trap((char**)argv);
  6907. fflush_all(); /* important */
  6908. _exit(0);
  6909. }
  6910. # endif
  6911. # if BB_MMU
  6912. /* Prevent it from trying to handle ctrl-z etc */
  6913. IF_HUSH_JOB(G.run_list_level = 1;)
  6914. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6915. reset_traps_to_defaults();
  6916. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6917. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6918. parse_and_run_string(s);
  6919. _exit(G.last_exitcode);
  6920. # else
  6921. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6922. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6923. * huge=`cat BIG` # was blocking here forever
  6924. * echo OK
  6925. */
  6926. re_execute_shell(&to_free,
  6927. s,
  6928. G.global_argv[0],
  6929. G.global_argv + 1,
  6930. NULL);
  6931. # endif
  6932. }
  6933. /* parent */
  6934. *pid_p = pid;
  6935. # if ENABLE_HUSH_FAST
  6936. G.count_SIGCHLD++;
  6937. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6938. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6939. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6940. # endif
  6941. enable_restore_tty_pgrp_on_exit();
  6942. # if !BB_MMU
  6943. free(to_free);
  6944. # endif
  6945. close(channel[1]);
  6946. return channel[0];
  6947. }
  6948. /* Return code is exit status of the process that is run. */
  6949. static int process_command_subs(o_string *dest, const char *s)
  6950. {
  6951. FILE *fp;
  6952. pid_t pid;
  6953. int status, ch, eol_cnt;
  6954. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6955. /* Now send results of command back into original context */
  6956. eol_cnt = 0;
  6957. while ((ch = getc(fp)) != EOF) {
  6958. if (ch == '\0')
  6959. continue;
  6960. if (ch == '\n') {
  6961. eol_cnt++;
  6962. continue;
  6963. }
  6964. while (eol_cnt) {
  6965. o_addchr(dest, '\n');
  6966. eol_cnt--;
  6967. }
  6968. o_addQchr(dest, ch);
  6969. }
  6970. debug_printf("done reading from `cmd` pipe, closing it\n");
  6971. fclose(fp);
  6972. /* We need to extract exitcode. Test case
  6973. * "true; echo `sleep 1; false` $?"
  6974. * should print 1 */
  6975. safe_waitpid(pid, &status, 0);
  6976. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6977. return WEXITSTATUS(status);
  6978. }
  6979. #endif /* ENABLE_HUSH_TICK */
  6980. static void setup_heredoc(struct redir_struct *redir)
  6981. {
  6982. struct fd_pair pair;
  6983. pid_t pid;
  6984. int len, written;
  6985. /* the _body_ of heredoc (misleading field name) */
  6986. const char *heredoc = redir->rd_filename;
  6987. char *expanded;
  6988. #if !BB_MMU
  6989. char **to_free;
  6990. #endif
  6991. expanded = NULL;
  6992. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6993. expanded = encode_then_expand_string(heredoc);
  6994. if (expanded)
  6995. heredoc = expanded;
  6996. }
  6997. len = strlen(heredoc);
  6998. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  6999. xpiped_pair(pair);
  7000. xmove_fd(pair.rd, redir->rd_fd);
  7001. /* Try writing without forking. Newer kernels have
  7002. * dynamically growing pipes. Must use non-blocking write! */
  7003. ndelay_on(pair.wr);
  7004. while (1) {
  7005. written = write(pair.wr, heredoc, len);
  7006. if (written <= 0)
  7007. break;
  7008. len -= written;
  7009. if (len == 0) {
  7010. close(pair.wr);
  7011. free(expanded);
  7012. return;
  7013. }
  7014. heredoc += written;
  7015. }
  7016. ndelay_off(pair.wr);
  7017. /* Okay, pipe buffer was not big enough */
  7018. /* Note: we must not create a stray child (bastard? :)
  7019. * for the unsuspecting parent process. Child creates a grandchild
  7020. * and exits before parent execs the process which consumes heredoc
  7021. * (that exec happens after we return from this function) */
  7022. #if !BB_MMU
  7023. to_free = NULL;
  7024. #endif
  7025. pid = xvfork();
  7026. if (pid == 0) {
  7027. /* child */
  7028. disable_restore_tty_pgrp_on_exit();
  7029. pid = BB_MMU ? xfork() : xvfork();
  7030. if (pid != 0)
  7031. _exit(0);
  7032. /* grandchild */
  7033. close(redir->rd_fd); /* read side of the pipe */
  7034. #if BB_MMU
  7035. full_write(pair.wr, heredoc, len); /* may loop or block */
  7036. _exit(0);
  7037. #else
  7038. /* Delegate blocking writes to another process */
  7039. xmove_fd(pair.wr, STDOUT_FILENO);
  7040. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7041. #endif
  7042. }
  7043. /* parent */
  7044. #if ENABLE_HUSH_FAST
  7045. G.count_SIGCHLD++;
  7046. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7047. #endif
  7048. enable_restore_tty_pgrp_on_exit();
  7049. #if !BB_MMU
  7050. free(to_free);
  7051. #endif
  7052. close(pair.wr);
  7053. free(expanded);
  7054. wait(NULL); /* wait till child has died */
  7055. }
  7056. struct squirrel {
  7057. int orig_fd;
  7058. int moved_to;
  7059. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7060. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7061. };
  7062. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7063. {
  7064. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7065. sq[i].orig_fd = orig;
  7066. sq[i].moved_to = moved;
  7067. sq[i+1].orig_fd = -1; /* end marker */
  7068. return sq;
  7069. }
  7070. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7071. {
  7072. int moved_to;
  7073. int i;
  7074. i = 0;
  7075. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7076. /* If we collide with an already moved fd... */
  7077. if (fd == sq[i].moved_to) {
  7078. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7079. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7080. if (sq[i].moved_to < 0) /* what? */
  7081. xfunc_die();
  7082. return sq;
  7083. }
  7084. if (fd == sq[i].orig_fd) {
  7085. /* Example: echo Hello >/dev/null 1>&2 */
  7086. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7087. return sq;
  7088. }
  7089. }
  7090. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7091. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7092. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7093. if (moved_to < 0 && errno != EBADF)
  7094. xfunc_die();
  7095. return append_squirrel(sq, i, fd, moved_to);
  7096. }
  7097. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7098. {
  7099. int i;
  7100. i = 0;
  7101. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7102. /* If we collide with an already moved fd... */
  7103. if (fd == sq[i].orig_fd) {
  7104. /* Examples:
  7105. * "echo 3>FILE 3>&- 3>FILE"
  7106. * "echo 3>&- 3>FILE"
  7107. * No need for last redirect to insert
  7108. * another "need to close 3" indicator.
  7109. */
  7110. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7111. return sq;
  7112. }
  7113. }
  7114. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7115. return append_squirrel(sq, i, fd, -1);
  7116. }
  7117. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7118. * Move all conflicting internally used fds,
  7119. * and remember them so that we can restore them later.
  7120. */
  7121. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7122. {
  7123. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7124. avoid_fd = 9;
  7125. #if ENABLE_HUSH_INTERACTIVE
  7126. if (fd == G_interactive_fd) {
  7127. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7128. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7129. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7130. return 1; /* "we closed fd" */
  7131. }
  7132. #endif
  7133. /* Are we called from setup_redirects(squirrel==NULL)
  7134. * in redirect in a [v]forked child?
  7135. */
  7136. if (sqp == NULL) {
  7137. /* No need to move script fds.
  7138. * For NOMMU case, it's actively wrong: we'd change ->fd
  7139. * fields in memory for the parent, but parent's fds
  7140. * aren't be moved, it would use wrong fd!
  7141. * Reproducer: "cmd 3>FILE" in script.
  7142. * If we would call move_HFILEs_on_redirect(), child would:
  7143. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7144. * close(3) = 0
  7145. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7146. */
  7147. //bb_error_msg("sqp == NULL: [v]forked child");
  7148. return 0;
  7149. }
  7150. /* If this one of script's fds? */
  7151. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7152. return 1; /* yes. "we closed fd" (actually moved it) */
  7153. /* Are we called for "exec 3>FILE"? Came through
  7154. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7155. * This case used to fail for this script:
  7156. * exec 3>FILE
  7157. * echo Ok
  7158. * ...100000 more lines...
  7159. * echo Ok
  7160. * as follows:
  7161. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7162. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7163. * dup2(4, 3) = 3
  7164. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7165. * close(4) = 0
  7166. * write(1, "Ok\n", 3) = 3
  7167. * ... = 3
  7168. * write(1, "Ok\n", 3) = 3
  7169. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7170. * ^^^^^^^^ oops, wrong fd!!!
  7171. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7172. * it now works:
  7173. */
  7174. if (sqp == ERR_PTR) {
  7175. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7176. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7177. return 0;
  7178. }
  7179. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7180. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7181. return 0; /* "we did not close fd" */
  7182. }
  7183. static void restore_redirects(struct squirrel *sq)
  7184. {
  7185. if (sq) {
  7186. int i;
  7187. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7188. if (sq[i].moved_to >= 0) {
  7189. /* We simply die on error */
  7190. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7191. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7192. } else {
  7193. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7194. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7195. close(sq[i].orig_fd);
  7196. }
  7197. }
  7198. free(sq);
  7199. }
  7200. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7201. }
  7202. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7203. static void close_saved_fds_and_FILE_fds(void)
  7204. {
  7205. if (G_interactive_fd)
  7206. close(G_interactive_fd);
  7207. close_all_HFILE_list();
  7208. }
  7209. #endif
  7210. static int internally_opened_fd(int fd, struct squirrel *sq)
  7211. {
  7212. int i;
  7213. #if ENABLE_HUSH_INTERACTIVE
  7214. if (fd == G_interactive_fd)
  7215. return 1;
  7216. #endif
  7217. /* If this one of script's fds? */
  7218. if (fd_in_HFILEs(fd))
  7219. return 1;
  7220. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7221. if (fd == sq[i].moved_to)
  7222. return 1;
  7223. }
  7224. return 0;
  7225. }
  7226. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7227. * and stderr if they are redirected. */
  7228. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7229. {
  7230. struct redir_struct *redir;
  7231. for (redir = prog->redirects; redir; redir = redir->next) {
  7232. int newfd;
  7233. int closed;
  7234. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7235. /* "rd_fd<<HERE" case */
  7236. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7237. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7238. * of the heredoc */
  7239. debug_printf_redir("set heredoc '%s'\n",
  7240. redir->rd_filename);
  7241. setup_heredoc(redir);
  7242. continue;
  7243. }
  7244. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7245. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7246. char *p;
  7247. int mode;
  7248. if (redir->rd_filename == NULL) {
  7249. /* Examples:
  7250. * "cmd >" (no filename)
  7251. * "cmd > <file" (2nd redirect starts too early)
  7252. */
  7253. syntax_error("invalid redirect");
  7254. continue;
  7255. }
  7256. mode = redir_table[redir->rd_type].mode;
  7257. p = expand_string_to_string(redir->rd_filename,
  7258. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7259. newfd = open_or_warn(p, mode);
  7260. free(p);
  7261. if (newfd < 0) {
  7262. /* Error message from open_or_warn can be lost
  7263. * if stderr has been redirected, but bash
  7264. * and ash both lose it as well
  7265. * (though zsh doesn't!)
  7266. */
  7267. return 1;
  7268. }
  7269. if (newfd == redir->rd_fd && sqp) {
  7270. /* open() gave us precisely the fd we wanted.
  7271. * This means that this fd was not busy
  7272. * (not opened to anywhere).
  7273. * Remember to close it on restore:
  7274. */
  7275. *sqp = add_squirrel_closed(*sqp, newfd);
  7276. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7277. }
  7278. } else {
  7279. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7280. newfd = redir->rd_dup;
  7281. }
  7282. if (newfd == redir->rd_fd)
  7283. continue;
  7284. /* if "N>FILE": move newfd to redir->rd_fd */
  7285. /* if "N>&M": dup newfd to redir->rd_fd */
  7286. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7287. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7288. if (newfd == REDIRFD_CLOSE) {
  7289. /* "N>&-" means "close me" */
  7290. if (!closed) {
  7291. /* ^^^ optimization: saving may already
  7292. * have closed it. If not... */
  7293. close(redir->rd_fd);
  7294. }
  7295. /* Sometimes we do another close on restore, getting EBADF.
  7296. * Consider "echo 3>FILE 3>&-"
  7297. * first redirect remembers "need to close 3",
  7298. * and second redirect closes 3! Restore code then closes 3 again.
  7299. */
  7300. } else {
  7301. /* if newfd is a script fd or saved fd, simulate EBADF */
  7302. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7303. //errno = EBADF;
  7304. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7305. newfd = -1; /* same effect as code above */
  7306. }
  7307. xdup2(newfd, redir->rd_fd);
  7308. if (redir->rd_dup == REDIRFD_TO_FILE)
  7309. /* "rd_fd > FILE" */
  7310. close(newfd);
  7311. /* else: "rd_fd > rd_dup" */
  7312. }
  7313. }
  7314. return 0;
  7315. }
  7316. static char *find_in_path(const char *arg)
  7317. {
  7318. char *ret = NULL;
  7319. const char *PATH = get_local_var_value("PATH");
  7320. if (!PATH)
  7321. return NULL;
  7322. while (1) {
  7323. const char *end = strchrnul(PATH, ':');
  7324. int sz = end - PATH; /* must be int! */
  7325. free(ret);
  7326. if (sz != 0) {
  7327. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7328. } else {
  7329. /* We have xxx::yyyy in $PATH,
  7330. * it means "use current dir" */
  7331. ret = xstrdup(arg);
  7332. }
  7333. if (access(ret, F_OK) == 0)
  7334. break;
  7335. if (*end == '\0') {
  7336. free(ret);
  7337. return NULL;
  7338. }
  7339. PATH = end + 1;
  7340. }
  7341. return ret;
  7342. }
  7343. static const struct built_in_command *find_builtin_helper(const char *name,
  7344. const struct built_in_command *x,
  7345. const struct built_in_command *end)
  7346. {
  7347. while (x != end) {
  7348. if (strcmp(name, x->b_cmd) != 0) {
  7349. x++;
  7350. continue;
  7351. }
  7352. debug_printf_exec("found builtin '%s'\n", name);
  7353. return x;
  7354. }
  7355. return NULL;
  7356. }
  7357. static const struct built_in_command *find_builtin1(const char *name)
  7358. {
  7359. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7360. }
  7361. static const struct built_in_command *find_builtin(const char *name)
  7362. {
  7363. const struct built_in_command *x = find_builtin1(name);
  7364. if (x)
  7365. return x;
  7366. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7367. }
  7368. static void remove_nested_vars(void)
  7369. {
  7370. struct variable *cur;
  7371. struct variable **cur_pp;
  7372. cur_pp = &G.top_var;
  7373. while ((cur = *cur_pp) != NULL) {
  7374. if (cur->var_nest_level <= G.var_nest_level) {
  7375. cur_pp = &cur->next;
  7376. continue;
  7377. }
  7378. /* Unexport */
  7379. if (cur->flg_export) {
  7380. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7381. bb_unsetenv(cur->varstr);
  7382. }
  7383. /* Remove from global list */
  7384. *cur_pp = cur->next;
  7385. /* Free */
  7386. if (!cur->max_len) {
  7387. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7388. free(cur->varstr);
  7389. }
  7390. free(cur);
  7391. }
  7392. }
  7393. static void enter_var_nest_level(void)
  7394. {
  7395. G.var_nest_level++;
  7396. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7397. /* Try: f() { echo -n .; f; }; f
  7398. * struct variable::var_nest_level is uint16_t,
  7399. * thus limiting recursion to < 2^16.
  7400. * In any case, with 8 Mbyte stack SEGV happens
  7401. * not too long after 2^16 recursions anyway.
  7402. */
  7403. if (G.var_nest_level > 0xff00)
  7404. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7405. }
  7406. static void leave_var_nest_level(void)
  7407. {
  7408. G.var_nest_level--;
  7409. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7410. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7411. bb_error_msg_and_die("BUG: nesting underflow");
  7412. remove_nested_vars();
  7413. }
  7414. #if ENABLE_HUSH_FUNCTIONS
  7415. static struct function **find_function_slot(const char *name)
  7416. {
  7417. struct function *funcp;
  7418. struct function **funcpp = &G.top_func;
  7419. while ((funcp = *funcpp) != NULL) {
  7420. if (strcmp(name, funcp->name) == 0) {
  7421. debug_printf_exec("found function '%s'\n", name);
  7422. break;
  7423. }
  7424. funcpp = &funcp->next;
  7425. }
  7426. return funcpp;
  7427. }
  7428. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7429. {
  7430. const struct function *funcp = *find_function_slot(name);
  7431. return funcp;
  7432. }
  7433. /* Note: takes ownership on name ptr */
  7434. static struct function *new_function(char *name)
  7435. {
  7436. struct function **funcpp = find_function_slot(name);
  7437. struct function *funcp = *funcpp;
  7438. if (funcp != NULL) {
  7439. struct command *cmd = funcp->parent_cmd;
  7440. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7441. if (!cmd) {
  7442. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7443. free(funcp->name);
  7444. /* Note: if !funcp->body, do not free body_as_string!
  7445. * This is a special case of "-F name body" function:
  7446. * body_as_string was not malloced! */
  7447. if (funcp->body) {
  7448. free_pipe_list(funcp->body);
  7449. # if !BB_MMU
  7450. free(funcp->body_as_string);
  7451. # endif
  7452. }
  7453. } else {
  7454. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7455. cmd->argv[0] = funcp->name;
  7456. cmd->group = funcp->body;
  7457. # if !BB_MMU
  7458. cmd->group_as_string = funcp->body_as_string;
  7459. # endif
  7460. }
  7461. } else {
  7462. debug_printf_exec("remembering new function '%s'\n", name);
  7463. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7464. /*funcp->next = NULL;*/
  7465. }
  7466. funcp->name = name;
  7467. return funcp;
  7468. }
  7469. # if ENABLE_HUSH_UNSET
  7470. static void unset_func(const char *name)
  7471. {
  7472. struct function **funcpp = find_function_slot(name);
  7473. struct function *funcp = *funcpp;
  7474. if (funcp != NULL) {
  7475. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7476. *funcpp = funcp->next;
  7477. /* funcp is unlinked now, deleting it.
  7478. * Note: if !funcp->body, the function was created by
  7479. * "-F name body", do not free ->body_as_string
  7480. * and ->name as they were not malloced. */
  7481. if (funcp->body) {
  7482. free_pipe_list(funcp->body);
  7483. free(funcp->name);
  7484. # if !BB_MMU
  7485. free(funcp->body_as_string);
  7486. # endif
  7487. }
  7488. free(funcp);
  7489. }
  7490. }
  7491. # endif
  7492. # if BB_MMU
  7493. #define exec_function(to_free, funcp, argv) \
  7494. exec_function(funcp, argv)
  7495. # endif
  7496. static void exec_function(char ***to_free,
  7497. const struct function *funcp,
  7498. char **argv) NORETURN;
  7499. static void exec_function(char ***to_free,
  7500. const struct function *funcp,
  7501. char **argv)
  7502. {
  7503. # if BB_MMU
  7504. int n;
  7505. argv[0] = G.global_argv[0];
  7506. G.global_argv = argv;
  7507. G.global_argc = n = 1 + string_array_len(argv + 1);
  7508. // Example when we are here: "cmd | func"
  7509. // func will run with saved-redirect fds open.
  7510. // $ f() { echo /proc/self/fd/*; }
  7511. // $ true | f
  7512. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7513. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7514. // Same in script:
  7515. // $ . ./SCRIPT
  7516. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7517. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7518. // They are CLOEXEC so external programs won't see them, but
  7519. // for "more correctness" we might want to close those extra fds here:
  7520. //? close_saved_fds_and_FILE_fds();
  7521. /* "we are in a function, ok to use return" */
  7522. G_flag_return_in_progress = -1;
  7523. enter_var_nest_level();
  7524. IF_HUSH_LOCAL(G.func_nest_level++;)
  7525. /* On MMU, funcp->body is always non-NULL */
  7526. n = run_list(funcp->body);
  7527. fflush_all();
  7528. _exit(n);
  7529. # else
  7530. //? close_saved_fds_and_FILE_fds();
  7531. //TODO: check whether "true | func_with_return" works
  7532. re_execute_shell(to_free,
  7533. funcp->body_as_string,
  7534. G.global_argv[0],
  7535. argv + 1,
  7536. NULL);
  7537. # endif
  7538. }
  7539. static int run_function(const struct function *funcp, char **argv)
  7540. {
  7541. int rc;
  7542. save_arg_t sv;
  7543. smallint sv_flg;
  7544. save_and_replace_G_args(&sv, argv);
  7545. /* "We are in function, ok to use return" */
  7546. sv_flg = G_flag_return_in_progress;
  7547. G_flag_return_in_progress = -1;
  7548. /* Make "local" variables properly shadow previous ones */
  7549. IF_HUSH_LOCAL(enter_var_nest_level();)
  7550. IF_HUSH_LOCAL(G.func_nest_level++;)
  7551. /* On MMU, funcp->body is always non-NULL */
  7552. # if !BB_MMU
  7553. if (!funcp->body) {
  7554. /* Function defined by -F */
  7555. parse_and_run_string(funcp->body_as_string);
  7556. rc = G.last_exitcode;
  7557. } else
  7558. # endif
  7559. {
  7560. rc = run_list(funcp->body);
  7561. }
  7562. IF_HUSH_LOCAL(G.func_nest_level--;)
  7563. IF_HUSH_LOCAL(leave_var_nest_level();)
  7564. G_flag_return_in_progress = sv_flg;
  7565. restore_G_args(&sv, argv);
  7566. return rc;
  7567. }
  7568. #endif /* ENABLE_HUSH_FUNCTIONS */
  7569. #if BB_MMU
  7570. #define exec_builtin(to_free, x, argv) \
  7571. exec_builtin(x, argv)
  7572. #else
  7573. #define exec_builtin(to_free, x, argv) \
  7574. exec_builtin(to_free, argv)
  7575. #endif
  7576. static void exec_builtin(char ***to_free,
  7577. const struct built_in_command *x,
  7578. char **argv) NORETURN;
  7579. static void exec_builtin(char ***to_free,
  7580. const struct built_in_command *x,
  7581. char **argv)
  7582. {
  7583. #if BB_MMU
  7584. int rcode;
  7585. fflush_all();
  7586. //? close_saved_fds_and_FILE_fds();
  7587. rcode = x->b_function(argv);
  7588. fflush_all();
  7589. _exit(rcode);
  7590. #else
  7591. fflush_all();
  7592. /* On NOMMU, we must never block!
  7593. * Example: { sleep 99 | read line; } & echo Ok
  7594. */
  7595. re_execute_shell(to_free,
  7596. argv[0],
  7597. G.global_argv[0],
  7598. G.global_argv + 1,
  7599. argv);
  7600. #endif
  7601. }
  7602. static void execvp_or_die(char **argv) NORETURN;
  7603. static void execvp_or_die(char **argv)
  7604. {
  7605. int e;
  7606. debug_printf_exec("execing '%s'\n", argv[0]);
  7607. /* Don't propagate SIG_IGN to the child */
  7608. if (SPECIAL_JOBSTOP_SIGS != 0)
  7609. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7610. execvp(argv[0], argv);
  7611. e = 2;
  7612. if (errno == EACCES) e = 126;
  7613. if (errno == ENOENT) e = 127;
  7614. bb_perror_msg("can't execute '%s'", argv[0]);
  7615. _exit(e);
  7616. }
  7617. #if ENABLE_HUSH_MODE_X
  7618. static void x_mode_print_optionally_squoted(const char *str)
  7619. {
  7620. unsigned len;
  7621. const char *cp;
  7622. cp = str;
  7623. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7624. /* test a char with: bash -c 'set -x; echo "CH"' */
  7625. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7626. " " "\001\002\003\004\005\006\007"
  7627. "\010\011\012\013\014\015\016\017"
  7628. "\020\021\022\023\024\025\026\027"
  7629. "\030\031\032\033\034\035\036\037"
  7630. )
  7631. ] == '\0'
  7632. ) {
  7633. /* string has no special chars */
  7634. x_mode_addstr(str);
  7635. return;
  7636. }
  7637. cp = str;
  7638. for (;;) {
  7639. /* print '....' up to EOL or first squote */
  7640. len = (int)(strchrnul(cp, '\'') - cp);
  7641. if (len != 0) {
  7642. x_mode_addchr('\'');
  7643. x_mode_addblock(cp, len);
  7644. x_mode_addchr('\'');
  7645. cp += len;
  7646. }
  7647. if (*cp == '\0')
  7648. break;
  7649. /* string contains squote(s), print them as \' */
  7650. x_mode_addchr('\\');
  7651. x_mode_addchr('\'');
  7652. cp++;
  7653. }
  7654. }
  7655. static void dump_cmd_in_x_mode(char **argv)
  7656. {
  7657. if (G_x_mode && argv) {
  7658. unsigned n;
  7659. /* "+[+++...][ cmd...]\n\0" */
  7660. x_mode_prefix();
  7661. n = 0;
  7662. while (argv[n]) {
  7663. x_mode_addchr(' ');
  7664. if (argv[n][0] == '\0') {
  7665. x_mode_addchr('\'');
  7666. x_mode_addchr('\'');
  7667. } else {
  7668. x_mode_print_optionally_squoted(argv[n]);
  7669. }
  7670. n++;
  7671. }
  7672. x_mode_flush();
  7673. }
  7674. }
  7675. #else
  7676. # define dump_cmd_in_x_mode(argv) ((void)0)
  7677. #endif
  7678. #if ENABLE_HUSH_COMMAND
  7679. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7680. {
  7681. char *to_free;
  7682. if (!opt_vV)
  7683. return;
  7684. to_free = NULL;
  7685. if (!explanation) {
  7686. char *path = getenv("PATH");
  7687. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7688. if (!explanation)
  7689. _exit(1); /* PROG was not found */
  7690. if (opt_vV != 'V')
  7691. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7692. }
  7693. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7694. free(to_free);
  7695. fflush_all();
  7696. _exit(0);
  7697. }
  7698. #else
  7699. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7700. #endif
  7701. #if BB_MMU
  7702. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7703. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7704. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7705. pseudo_exec(command, argv_expanded)
  7706. #endif
  7707. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7708. * Never returns.
  7709. * Don't exit() here. If you don't exec, use _exit instead.
  7710. * The at_exit handlers apparently confuse the calling process,
  7711. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7712. */
  7713. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7714. char **argv, int assignment_cnt,
  7715. char **argv_expanded) NORETURN;
  7716. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7717. char **argv, int assignment_cnt,
  7718. char **argv_expanded)
  7719. {
  7720. const struct built_in_command *x;
  7721. struct variable **sv_shadowed;
  7722. char **new_env;
  7723. IF_HUSH_COMMAND(char opt_vV = 0;)
  7724. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7725. new_env = expand_assignments(argv, assignment_cnt);
  7726. dump_cmd_in_x_mode(new_env);
  7727. if (!argv[assignment_cnt]) {
  7728. /* Case when we are here: ... | var=val | ...
  7729. * (note that we do not exit early, i.e., do not optimize out
  7730. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7731. */
  7732. free_strings(new_env);
  7733. _exit(EXIT_SUCCESS);
  7734. }
  7735. sv_shadowed = G.shadowed_vars_pp;
  7736. #if BB_MMU
  7737. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7738. #else
  7739. G.shadowed_vars_pp = &nommu_save->old_vars;
  7740. G.var_nest_level++;
  7741. #endif
  7742. set_vars_and_save_old(new_env);
  7743. G.shadowed_vars_pp = sv_shadowed;
  7744. if (argv_expanded) {
  7745. argv = argv_expanded;
  7746. } else {
  7747. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7748. #if !BB_MMU
  7749. nommu_save->argv = argv;
  7750. #endif
  7751. }
  7752. dump_cmd_in_x_mode(argv);
  7753. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7754. if (strchr(argv[0], '/') != NULL)
  7755. goto skip;
  7756. #endif
  7757. #if ENABLE_HUSH_FUNCTIONS
  7758. /* Check if the command matches any functions (this goes before bltins) */
  7759. funcp = find_function(argv[0]);
  7760. if (funcp)
  7761. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7762. #endif
  7763. #if ENABLE_HUSH_COMMAND
  7764. /* "command BAR": run BAR without looking it up among functions
  7765. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7766. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7767. */
  7768. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7769. char *p;
  7770. argv++;
  7771. p = *argv;
  7772. if (p[0] != '-' || !p[1])
  7773. continue; /* bash allows "command command command [-OPT] BAR" */
  7774. for (;;) {
  7775. p++;
  7776. switch (*p) {
  7777. case '\0':
  7778. argv++;
  7779. p = *argv;
  7780. if (p[0] != '-' || !p[1])
  7781. goto after_opts;
  7782. continue; /* next arg is also -opts, process it too */
  7783. case 'v':
  7784. case 'V':
  7785. opt_vV = *p;
  7786. continue;
  7787. default:
  7788. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7789. }
  7790. }
  7791. }
  7792. after_opts:
  7793. # if ENABLE_HUSH_FUNCTIONS
  7794. if (opt_vV && find_function(argv[0]))
  7795. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7796. # endif
  7797. #endif
  7798. /* Check if the command matches any of the builtins.
  7799. * Depending on context, this might be redundant. But it's
  7800. * easier to waste a few CPU cycles than it is to figure out
  7801. * if this is one of those cases.
  7802. */
  7803. /* Why "BB_MMU ? :" difference in logic? -
  7804. * On NOMMU, it is more expensive to re-execute shell
  7805. * just in order to run echo or test builtin.
  7806. * It's better to skip it here and run corresponding
  7807. * non-builtin later. */
  7808. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7809. if (x) {
  7810. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7811. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7812. }
  7813. #if ENABLE_FEATURE_SH_STANDALONE
  7814. /* Check if the command matches any busybox applets */
  7815. {
  7816. int a = find_applet_by_name(argv[0]);
  7817. if (a >= 0) {
  7818. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7819. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7820. if (APPLET_IS_NOEXEC(a)) {
  7821. /* Do not leak open fds from opened script files etc.
  7822. * Testcase: interactive "ls -l /proc/self/fd"
  7823. * should not show tty fd open.
  7824. */
  7825. close_saved_fds_and_FILE_fds();
  7826. //FIXME: should also close saved redir fds
  7827. //This casuses test failures in
  7828. //redir_children_should_not_see_saved_fd_2.tests
  7829. //redir_children_should_not_see_saved_fd_3.tests
  7830. //if you replace "busybox find" with just "find" in them
  7831. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7832. switch_off_special_sigs(G.special_sig_mask);
  7833. debug_printf_exec("running applet '%s'\n", argv[0]);
  7834. run_noexec_applet_and_exit(a, argv[0], argv);
  7835. }
  7836. # endif
  7837. /* Re-exec ourselves */
  7838. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7839. /* Don't propagate SIG_IGN to the child */
  7840. if (SPECIAL_JOBSTOP_SIGS != 0)
  7841. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7842. execv(bb_busybox_exec_path, argv);
  7843. /* If they called chroot or otherwise made the binary no longer
  7844. * executable, fall through */
  7845. }
  7846. }
  7847. #endif
  7848. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7849. skip:
  7850. #endif
  7851. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7852. execvp_or_die(argv);
  7853. }
  7854. /* Called after [v]fork() in run_pipe
  7855. */
  7856. static void pseudo_exec(nommu_save_t *nommu_save,
  7857. struct command *command,
  7858. char **argv_expanded) NORETURN;
  7859. static void pseudo_exec(nommu_save_t *nommu_save,
  7860. struct command *command,
  7861. char **argv_expanded)
  7862. {
  7863. #if ENABLE_HUSH_FUNCTIONS
  7864. if (command->cmd_type == CMD_FUNCDEF) {
  7865. /* Ignore funcdefs in pipes:
  7866. * true | f() { cmd }
  7867. */
  7868. _exit(0);
  7869. }
  7870. #endif
  7871. if (command->argv) {
  7872. pseudo_exec_argv(nommu_save, command->argv,
  7873. command->assignment_cnt, argv_expanded);
  7874. }
  7875. if (command->group) {
  7876. /* Cases when we are here:
  7877. * ( list )
  7878. * { list } &
  7879. * ... | ( list ) | ...
  7880. * ... | { list } | ...
  7881. */
  7882. #if BB_MMU
  7883. int rcode;
  7884. debug_printf_exec("pseudo_exec: run_list\n");
  7885. reset_traps_to_defaults();
  7886. rcode = run_list(command->group);
  7887. /* OK to leak memory by not calling free_pipe_list,
  7888. * since this process is about to exit */
  7889. _exit(rcode);
  7890. #else
  7891. re_execute_shell(&nommu_save->argv_from_re_execing,
  7892. command->group_as_string,
  7893. G.global_argv[0],
  7894. G.global_argv + 1,
  7895. NULL);
  7896. #endif
  7897. }
  7898. /* Case when we are here: ... | >file */
  7899. debug_printf_exec("pseudo_exec'ed null command\n");
  7900. _exit(EXIT_SUCCESS);
  7901. }
  7902. #if ENABLE_HUSH_JOB
  7903. static const char *get_cmdtext(struct pipe *pi)
  7904. {
  7905. char **argv;
  7906. char *p;
  7907. int len;
  7908. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7909. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7910. * On subsequent bg argv is trashed, but we won't use it */
  7911. if (pi->cmdtext)
  7912. return pi->cmdtext;
  7913. argv = pi->cmds[0].argv;
  7914. if (!argv) {
  7915. pi->cmdtext = xzalloc(1);
  7916. return pi->cmdtext;
  7917. }
  7918. len = 0;
  7919. do {
  7920. len += strlen(*argv) + 1;
  7921. } while (*++argv);
  7922. p = xmalloc(len);
  7923. pi->cmdtext = p;
  7924. argv = pi->cmds[0].argv;
  7925. do {
  7926. p = stpcpy(p, *argv);
  7927. *p++ = ' ';
  7928. } while (*++argv);
  7929. p[-1] = '\0';
  7930. return pi->cmdtext;
  7931. }
  7932. static void remove_job_from_table(struct pipe *pi)
  7933. {
  7934. struct pipe *prev_pipe;
  7935. if (pi == G.job_list) {
  7936. G.job_list = pi->next;
  7937. } else {
  7938. prev_pipe = G.job_list;
  7939. while (prev_pipe->next != pi)
  7940. prev_pipe = prev_pipe->next;
  7941. prev_pipe->next = pi->next;
  7942. }
  7943. G.last_jobid = 0;
  7944. if (G.job_list)
  7945. G.last_jobid = G.job_list->jobid;
  7946. }
  7947. static void delete_finished_job(struct pipe *pi)
  7948. {
  7949. remove_job_from_table(pi);
  7950. free_pipe(pi);
  7951. }
  7952. static void clean_up_last_dead_job(void)
  7953. {
  7954. if (G.job_list && !G.job_list->alive_cmds)
  7955. delete_finished_job(G.job_list);
  7956. }
  7957. static void insert_job_into_table(struct pipe *pi)
  7958. {
  7959. struct pipe *job, **jobp;
  7960. int i;
  7961. clean_up_last_dead_job();
  7962. /* Find the end of the list, and find next job ID to use */
  7963. i = 0;
  7964. jobp = &G.job_list;
  7965. while ((job = *jobp) != NULL) {
  7966. if (job->jobid > i)
  7967. i = job->jobid;
  7968. jobp = &job->next;
  7969. }
  7970. pi->jobid = i + 1;
  7971. /* Create a new job struct at the end */
  7972. job = *jobp = xmemdup(pi, sizeof(*pi));
  7973. job->next = NULL;
  7974. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7975. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7976. for (i = 0; i < pi->num_cmds; i++) {
  7977. job->cmds[i].pid = pi->cmds[i].pid;
  7978. /* all other fields are not used and stay zero */
  7979. }
  7980. job->cmdtext = xstrdup(get_cmdtext(pi));
  7981. if (G_interactive_fd)
  7982. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  7983. G.last_jobid = job->jobid;
  7984. }
  7985. #endif /* JOB */
  7986. static int job_exited_or_stopped(struct pipe *pi)
  7987. {
  7988. int rcode, i;
  7989. if (pi->alive_cmds != pi->stopped_cmds)
  7990. return -1;
  7991. /* All processes in fg pipe have exited or stopped */
  7992. rcode = 0;
  7993. i = pi->num_cmds;
  7994. while (--i >= 0) {
  7995. rcode = pi->cmds[i].cmd_exitcode;
  7996. /* usually last process gives overall exitstatus,
  7997. * but with "set -o pipefail", last *failed* process does */
  7998. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  7999. break;
  8000. }
  8001. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8002. return rcode;
  8003. }
  8004. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8005. {
  8006. #if ENABLE_HUSH_JOB
  8007. struct pipe *pi;
  8008. #endif
  8009. int i, dead;
  8010. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8011. #if DEBUG_JOBS
  8012. if (WIFSTOPPED(status))
  8013. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8014. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8015. if (WIFSIGNALED(status))
  8016. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8017. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8018. if (WIFEXITED(status))
  8019. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8020. childpid, WEXITSTATUS(status));
  8021. #endif
  8022. /* Were we asked to wait for a fg pipe? */
  8023. if (fg_pipe) {
  8024. i = fg_pipe->num_cmds;
  8025. while (--i >= 0) {
  8026. int rcode;
  8027. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8028. if (fg_pipe->cmds[i].pid != childpid)
  8029. continue;
  8030. if (dead) {
  8031. int ex;
  8032. fg_pipe->cmds[i].pid = 0;
  8033. fg_pipe->alive_cmds--;
  8034. ex = WEXITSTATUS(status);
  8035. /* bash prints killer signal's name for *last*
  8036. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8037. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8038. */
  8039. if (WIFSIGNALED(status)) {
  8040. int sig = WTERMSIG(status);
  8041. if (i == fg_pipe->num_cmds-1)
  8042. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8043. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8044. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8045. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8046. * Maybe we need to use sig | 128? */
  8047. ex = sig + 128;
  8048. }
  8049. fg_pipe->cmds[i].cmd_exitcode = ex;
  8050. } else {
  8051. fg_pipe->stopped_cmds++;
  8052. }
  8053. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8054. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8055. rcode = job_exited_or_stopped(fg_pipe);
  8056. if (rcode >= 0) {
  8057. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8058. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8059. * and "killall -STOP cat" */
  8060. if (G_interactive_fd) {
  8061. #if ENABLE_HUSH_JOB
  8062. if (fg_pipe->alive_cmds != 0)
  8063. insert_job_into_table(fg_pipe);
  8064. #endif
  8065. return rcode;
  8066. }
  8067. if (fg_pipe->alive_cmds == 0)
  8068. return rcode;
  8069. }
  8070. /* There are still running processes in the fg_pipe */
  8071. return -1;
  8072. }
  8073. /* It wasn't in fg_pipe, look for process in bg pipes */
  8074. }
  8075. #if ENABLE_HUSH_JOB
  8076. /* We were asked to wait for bg or orphaned children */
  8077. /* No need to remember exitcode in this case */
  8078. for (pi = G.job_list; pi; pi = pi->next) {
  8079. for (i = 0; i < pi->num_cmds; i++) {
  8080. if (pi->cmds[i].pid == childpid)
  8081. goto found_pi_and_prognum;
  8082. }
  8083. }
  8084. /* Happens when shell is used as init process (init=/bin/sh) */
  8085. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8086. return -1; /* this wasn't a process from fg_pipe */
  8087. found_pi_and_prognum:
  8088. if (dead) {
  8089. /* child exited */
  8090. int rcode = WEXITSTATUS(status);
  8091. if (WIFSIGNALED(status))
  8092. rcode = 128 + WTERMSIG(status);
  8093. pi->cmds[i].cmd_exitcode = rcode;
  8094. if (G.last_bg_pid == pi->cmds[i].pid)
  8095. G.last_bg_pid_exitcode = rcode;
  8096. pi->cmds[i].pid = 0;
  8097. pi->alive_cmds--;
  8098. if (!pi->alive_cmds) {
  8099. #if ENABLE_HUSH_BASH_COMPAT
  8100. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8101. #endif
  8102. if (G_interactive_fd) {
  8103. printf(JOB_STATUS_FORMAT, pi->jobid,
  8104. "Done", pi->cmdtext);
  8105. delete_finished_job(pi);
  8106. } else {
  8107. /*
  8108. * bash deletes finished jobs from job table only in interactive mode,
  8109. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8110. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8111. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8112. * We only retain one "dead" job, if it's the single job on the list.
  8113. * This covers most of real-world scenarios where this is useful.
  8114. */
  8115. if (pi != G.job_list)
  8116. delete_finished_job(pi);
  8117. }
  8118. }
  8119. } else {
  8120. /* child stopped */
  8121. pi->stopped_cmds++;
  8122. }
  8123. #endif
  8124. return -1; /* this wasn't a process from fg_pipe */
  8125. }
  8126. /* Check to see if any processes have exited -- if they have,
  8127. * figure out why and see if a job has completed.
  8128. *
  8129. * If non-NULL fg_pipe: wait for its completion or stop.
  8130. * Return its exitcode or zero if stopped.
  8131. *
  8132. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8133. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8134. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8135. * or 0 if no children changed status.
  8136. *
  8137. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8138. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8139. * or 0 if no children changed status.
  8140. */
  8141. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8142. {
  8143. int attributes;
  8144. int status;
  8145. int rcode = 0;
  8146. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8147. attributes = WUNTRACED;
  8148. if (fg_pipe == NULL)
  8149. attributes |= WNOHANG;
  8150. errno = 0;
  8151. #if ENABLE_HUSH_FAST
  8152. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8153. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8154. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8155. /* There was neither fork nor SIGCHLD since last waitpid */
  8156. /* Avoid doing waitpid syscall if possible */
  8157. if (!G.we_have_children) {
  8158. errno = ECHILD;
  8159. return -1;
  8160. }
  8161. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8162. /* We have children, but they did not exit
  8163. * or stop yet (we saw no SIGCHLD) */
  8164. return 0;
  8165. }
  8166. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8167. }
  8168. #endif
  8169. /* Do we do this right?
  8170. * bash-3.00# sleep 20 | false
  8171. * <ctrl-Z pressed>
  8172. * [3]+ Stopped sleep 20 | false
  8173. * bash-3.00# echo $?
  8174. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8175. * [hush 1.14.0: yes we do it right]
  8176. */
  8177. while (1) {
  8178. pid_t childpid;
  8179. #if ENABLE_HUSH_FAST
  8180. int i;
  8181. i = G.count_SIGCHLD;
  8182. #endif
  8183. childpid = waitpid(-1, &status, attributes);
  8184. if (childpid <= 0) {
  8185. if (childpid && errno != ECHILD)
  8186. bb_perror_msg("waitpid");
  8187. #if ENABLE_HUSH_FAST
  8188. else { /* Until next SIGCHLD, waitpid's are useless */
  8189. G.we_have_children = (childpid == 0);
  8190. G.handled_SIGCHLD = i;
  8191. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8192. }
  8193. #endif
  8194. /* ECHILD (no children), or 0 (no change in children status) */
  8195. rcode = childpid;
  8196. break;
  8197. }
  8198. rcode = process_wait_result(fg_pipe, childpid, status);
  8199. if (rcode >= 0) {
  8200. /* fg_pipe exited or stopped */
  8201. break;
  8202. }
  8203. if (childpid == waitfor_pid) { /* "wait PID" */
  8204. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8205. rcode = WEXITSTATUS(status);
  8206. if (WIFSIGNALED(status))
  8207. rcode = 128 + WTERMSIG(status);
  8208. if (WIFSTOPPED(status))
  8209. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8210. rcode = 128 + WSTOPSIG(status);
  8211. rcode++;
  8212. break; /* "wait PID" called us, give it exitcode+1 */
  8213. }
  8214. #if ENABLE_HUSH_BASH_COMPAT
  8215. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8216. && G.dead_job_exitcode >= 0 /* some job did finish */
  8217. ) {
  8218. debug_printf_exec("waitfor_pid:-1\n");
  8219. rcode = G.dead_job_exitcode + 1;
  8220. break;
  8221. }
  8222. #endif
  8223. /* This wasn't one of our processes, or */
  8224. /* fg_pipe still has running processes, do waitpid again */
  8225. } /* while (waitpid succeeds)... */
  8226. return rcode;
  8227. }
  8228. #if ENABLE_HUSH_JOB
  8229. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8230. {
  8231. pid_t p;
  8232. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8233. if (G_saved_tty_pgrp) {
  8234. /* Job finished, move the shell to the foreground */
  8235. p = getpgrp(); /* our process group id */
  8236. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8237. tcsetpgrp(G_interactive_fd, p);
  8238. }
  8239. return rcode;
  8240. }
  8241. #endif
  8242. /* Start all the jobs, but don't wait for anything to finish.
  8243. * See checkjobs().
  8244. *
  8245. * Return code is normally -1, when the caller has to wait for children
  8246. * to finish to determine the exit status of the pipe. If the pipe
  8247. * is a simple builtin command, however, the action is done by the
  8248. * time run_pipe returns, and the exit code is provided as the
  8249. * return value.
  8250. *
  8251. * Returns -1 only if started some children. IOW: we have to
  8252. * mask out retvals of builtins etc with 0xff!
  8253. *
  8254. * The only case when we do not need to [v]fork is when the pipe
  8255. * is single, non-backgrounded, non-subshell command. Examples:
  8256. * cmd ; ... { list } ; ...
  8257. * cmd && ... { list } && ...
  8258. * cmd || ... { list } || ...
  8259. * If it is, then we can run cmd as a builtin, NOFORK,
  8260. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8261. * with run_list. If it isn't one of these, we fork and exec cmd.
  8262. *
  8263. * Cases when we must fork:
  8264. * non-single: cmd | cmd
  8265. * backgrounded: cmd & { list } &
  8266. * subshell: ( list ) [&]
  8267. */
  8268. #if !ENABLE_HUSH_MODE_X
  8269. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8270. redirect_and_varexp_helper(command, sqp)
  8271. #endif
  8272. static int redirect_and_varexp_helper(
  8273. struct command *command,
  8274. struct squirrel **sqp,
  8275. char **argv_expanded)
  8276. {
  8277. /* Assignments occur before redirects. Try:
  8278. * a=`sleep 1` sleep 2 3>/qwe/rty
  8279. */
  8280. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8281. dump_cmd_in_x_mode(new_env);
  8282. dump_cmd_in_x_mode(argv_expanded);
  8283. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8284. set_vars_and_save_old(new_env);
  8285. return setup_redirects(command, sqp);
  8286. }
  8287. static NOINLINE int run_pipe(struct pipe *pi)
  8288. {
  8289. static const char *const null_ptr = NULL;
  8290. int cmd_no;
  8291. int next_infd;
  8292. struct command *command;
  8293. char **argv_expanded;
  8294. char **argv;
  8295. struct squirrel *squirrel = NULL;
  8296. int rcode;
  8297. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8298. debug_enter();
  8299. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8300. * Result should be 3 lines: q w e, qwe, q w e
  8301. */
  8302. if (G.ifs_whitespace != G.ifs)
  8303. free(G.ifs_whitespace);
  8304. G.ifs = get_local_var_value("IFS");
  8305. if (G.ifs) {
  8306. char *p;
  8307. G.ifs_whitespace = (char*)G.ifs;
  8308. p = skip_whitespace(G.ifs);
  8309. if (*p) {
  8310. /* Not all $IFS is whitespace */
  8311. char *d;
  8312. int len = p - G.ifs;
  8313. p = skip_non_whitespace(p);
  8314. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8315. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8316. while (*p) {
  8317. if (isspace(*p))
  8318. *d++ = *p;
  8319. p++;
  8320. }
  8321. *d = '\0';
  8322. }
  8323. } else {
  8324. G.ifs = defifs;
  8325. G.ifs_whitespace = (char*)G.ifs;
  8326. }
  8327. IF_HUSH_JOB(pi->pgrp = -1;)
  8328. pi->stopped_cmds = 0;
  8329. command = &pi->cmds[0];
  8330. argv_expanded = NULL;
  8331. if (pi->num_cmds != 1
  8332. || pi->followup == PIPE_BG
  8333. || command->cmd_type == CMD_SUBSHELL
  8334. ) {
  8335. goto must_fork;
  8336. }
  8337. pi->alive_cmds = 1;
  8338. debug_printf_exec(": group:%p argv:'%s'\n",
  8339. command->group, command->argv ? command->argv[0] : "NONE");
  8340. if (command->group) {
  8341. #if ENABLE_HUSH_FUNCTIONS
  8342. if (command->cmd_type == CMD_FUNCDEF) {
  8343. /* "executing" func () { list } */
  8344. struct function *funcp;
  8345. funcp = new_function(command->argv[0]);
  8346. /* funcp->name is already set to argv[0] */
  8347. funcp->body = command->group;
  8348. # if !BB_MMU
  8349. funcp->body_as_string = command->group_as_string;
  8350. command->group_as_string = NULL;
  8351. # endif
  8352. command->group = NULL;
  8353. command->argv[0] = NULL;
  8354. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8355. funcp->parent_cmd = command;
  8356. command->child_func = funcp;
  8357. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8358. debug_leave();
  8359. return EXIT_SUCCESS;
  8360. }
  8361. #endif
  8362. /* { list } */
  8363. debug_printf_exec("non-subshell group\n");
  8364. rcode = 1; /* exitcode if redir failed */
  8365. if (setup_redirects(command, &squirrel) == 0) {
  8366. debug_printf_exec(": run_list\n");
  8367. //FIXME: we need to pass squirrel down into run_list()
  8368. //for SH_STANDALONE case, or else this construct:
  8369. // { find /proc/self/fd; true; } >FILE; cmd2
  8370. //has no way of closing saved fd#1 for "find",
  8371. //and in SH_STANDALONE mode, "find" is not execed,
  8372. //therefore CLOEXEC on saved fd does not help.
  8373. rcode = run_list(command->group) & 0xff;
  8374. }
  8375. restore_redirects(squirrel);
  8376. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8377. debug_leave();
  8378. debug_printf_exec("run_pipe: return %d\n", rcode);
  8379. return rcode;
  8380. }
  8381. argv = command->argv ? command->argv : (char **) &null_ptr;
  8382. {
  8383. const struct built_in_command *x;
  8384. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8385. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8386. struct variable **sv_shadowed;
  8387. struct variable *old_vars;
  8388. #if ENABLE_HUSH_LINENO_VAR
  8389. G.execute_lineno = command->lineno;
  8390. #endif
  8391. if (argv[command->assignment_cnt] == NULL) {
  8392. /* Assignments, but no command.
  8393. * Ensure redirects take effect (that is, create files).
  8394. * Try "a=t >file"
  8395. */
  8396. unsigned i;
  8397. G.expand_exitcode = 0;
  8398. only_assignments:
  8399. rcode = setup_redirects(command, &squirrel);
  8400. restore_redirects(squirrel);
  8401. /* Set shell variables */
  8402. i = 0;
  8403. while (i < command->assignment_cnt) {
  8404. char *p = expand_string_to_string(argv[i],
  8405. EXP_FLAG_ESC_GLOB_CHARS,
  8406. /*unbackslash:*/ 1
  8407. );
  8408. #if ENABLE_HUSH_MODE_X
  8409. if (G_x_mode) {
  8410. char *eq;
  8411. if (i == 0)
  8412. x_mode_prefix();
  8413. x_mode_addchr(' ');
  8414. eq = strchrnul(p, '=');
  8415. if (*eq) eq++;
  8416. x_mode_addblock(p, (eq - p));
  8417. x_mode_print_optionally_squoted(eq);
  8418. x_mode_flush();
  8419. }
  8420. #endif
  8421. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8422. if (set_local_var(p, /*flag:*/ 0)) {
  8423. /* assignment to readonly var / putenv error? */
  8424. rcode = 1;
  8425. }
  8426. i++;
  8427. }
  8428. /* Redirect error sets $? to 1. Otherwise,
  8429. * if evaluating assignment value set $?, retain it.
  8430. * Else, clear $?:
  8431. * false; q=`exit 2`; echo $? - should print 2
  8432. * false; x=1; echo $? - should print 0
  8433. * Because of the 2nd case, we can't just use G.last_exitcode.
  8434. */
  8435. if (rcode == 0)
  8436. rcode = G.expand_exitcode;
  8437. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8438. debug_leave();
  8439. debug_printf_exec("run_pipe: return %d\n", rcode);
  8440. return rcode;
  8441. }
  8442. /* Expand the rest into (possibly) many strings each */
  8443. #if defined(CMD_SINGLEWORD_NOGLOB)
  8444. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8445. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8446. else
  8447. #endif
  8448. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8449. /* If someone gives us an empty string: `cmd with empty output` */
  8450. if (!argv_expanded[0]) {
  8451. free(argv_expanded);
  8452. /* `false` still has to set exitcode 1 */
  8453. G.expand_exitcode = G.last_exitcode;
  8454. goto only_assignments;
  8455. }
  8456. old_vars = NULL;
  8457. sv_shadowed = G.shadowed_vars_pp;
  8458. /* Check if argv[0] matches any functions (this goes before bltins) */
  8459. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8460. IF_HUSH_FUNCTIONS(x = NULL;)
  8461. IF_HUSH_FUNCTIONS(if (!funcp))
  8462. x = find_builtin(argv_expanded[0]);
  8463. if (x || funcp) {
  8464. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8465. debug_printf("exec with redirects only\n");
  8466. /*
  8467. * Variable assignments are executed, but then "forgotten":
  8468. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8469. * sleeps, but prints nothing.
  8470. */
  8471. enter_var_nest_level();
  8472. G.shadowed_vars_pp = &old_vars;
  8473. rcode = redirect_and_varexp_helper(command,
  8474. /*squirrel:*/ ERR_PTR,
  8475. argv_expanded
  8476. );
  8477. G.shadowed_vars_pp = sv_shadowed;
  8478. /* rcode=1 can be if redir file can't be opened */
  8479. goto clean_up_and_ret1;
  8480. }
  8481. /* Bump var nesting, or this will leak exported $a:
  8482. * a=b true; env | grep ^a=
  8483. */
  8484. enter_var_nest_level();
  8485. /* Collect all variables "shadowed" by helper
  8486. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8487. * into old_vars list:
  8488. */
  8489. G.shadowed_vars_pp = &old_vars;
  8490. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8491. if (rcode == 0) {
  8492. if (!funcp) {
  8493. /* Do not collect *to old_vars list* vars shadowed
  8494. * by e.g. "local VAR" builtin (collect them
  8495. * in the previously nested list instead):
  8496. * don't want them to be restored immediately
  8497. * after "local" completes.
  8498. */
  8499. G.shadowed_vars_pp = sv_shadowed;
  8500. debug_printf_exec(": builtin '%s' '%s'...\n",
  8501. x->b_cmd, argv_expanded[1]);
  8502. fflush_all();
  8503. rcode = x->b_function(argv_expanded) & 0xff;
  8504. fflush_all();
  8505. }
  8506. #if ENABLE_HUSH_FUNCTIONS
  8507. else {
  8508. debug_printf_exec(": function '%s' '%s'...\n",
  8509. funcp->name, argv_expanded[1]);
  8510. rcode = run_function(funcp, argv_expanded) & 0xff;
  8511. /*
  8512. * But do collect *to old_vars list* vars shadowed
  8513. * within function execution. To that end, restore
  8514. * this pointer _after_ function run:
  8515. */
  8516. G.shadowed_vars_pp = sv_shadowed;
  8517. }
  8518. #endif
  8519. }
  8520. } else
  8521. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8522. int n = find_applet_by_name(argv_expanded[0]);
  8523. if (n < 0 || !APPLET_IS_NOFORK(n))
  8524. goto must_fork;
  8525. enter_var_nest_level();
  8526. /* Collect all variables "shadowed" by helper into old_vars list */
  8527. G.shadowed_vars_pp = &old_vars;
  8528. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8529. G.shadowed_vars_pp = sv_shadowed;
  8530. if (rcode == 0) {
  8531. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8532. argv_expanded[0], argv_expanded[1]);
  8533. /*
  8534. * Note: signals (^C) can't interrupt here.
  8535. * We remember them and they will be acted upon
  8536. * after applet returns.
  8537. * This makes applets which can run for a long time
  8538. * and/or wait for user input ineligible for NOFORK:
  8539. * for example, "yes" or "rm" (rm -i waits for input).
  8540. */
  8541. rcode = run_nofork_applet(n, argv_expanded);
  8542. }
  8543. } else
  8544. goto must_fork;
  8545. restore_redirects(squirrel);
  8546. clean_up_and_ret1:
  8547. leave_var_nest_level();
  8548. add_vars(old_vars);
  8549. /*
  8550. * Try "usleep 99999999" + ^C + "echo $?"
  8551. * with FEATURE_SH_NOFORK=y.
  8552. */
  8553. if (!funcp) {
  8554. /* It was builtin or nofork.
  8555. * if this would be a real fork/execed program,
  8556. * it should have died if a fatal sig was received.
  8557. * But OTOH, there was no separate process,
  8558. * the sig was sent to _shell_, not to non-existing
  8559. * child.
  8560. * Let's just handle ^C only, this one is obvious:
  8561. * we aren't ok with exitcode 0 when ^C was pressed
  8562. * during builtin/nofork.
  8563. */
  8564. if (sigismember(&G.pending_set, SIGINT))
  8565. rcode = 128 + SIGINT;
  8566. }
  8567. free(argv_expanded);
  8568. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8569. debug_leave();
  8570. debug_printf_exec("run_pipe return %d\n", rcode);
  8571. return rcode;
  8572. }
  8573. must_fork:
  8574. /* NB: argv_expanded may already be created, and that
  8575. * might include `cmd` runs! Do not rerun it! We *must*
  8576. * use argv_expanded if it's non-NULL */
  8577. /* Going to fork a child per each pipe member */
  8578. pi->alive_cmds = 0;
  8579. next_infd = 0;
  8580. cmd_no = 0;
  8581. while (cmd_no < pi->num_cmds) {
  8582. struct fd_pair pipefds;
  8583. #if !BB_MMU
  8584. int sv_var_nest_level = G.var_nest_level;
  8585. volatile nommu_save_t nommu_save;
  8586. nommu_save.old_vars = NULL;
  8587. nommu_save.argv = NULL;
  8588. nommu_save.argv_from_re_execing = NULL;
  8589. #endif
  8590. command = &pi->cmds[cmd_no];
  8591. cmd_no++;
  8592. if (command->argv) {
  8593. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8594. command->argv[0], command->argv[1]);
  8595. } else {
  8596. debug_printf_exec(": pipe member with no argv\n");
  8597. }
  8598. /* pipes are inserted between pairs of commands */
  8599. pipefds.rd = 0;
  8600. pipefds.wr = 1;
  8601. if (cmd_no < pi->num_cmds)
  8602. xpiped_pair(pipefds);
  8603. #if ENABLE_HUSH_LINENO_VAR
  8604. G.execute_lineno = command->lineno;
  8605. #endif
  8606. command->pid = BB_MMU ? fork() : vfork();
  8607. if (!command->pid) { /* child */
  8608. #if ENABLE_HUSH_JOB
  8609. disable_restore_tty_pgrp_on_exit();
  8610. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8611. /* Every child adds itself to new process group
  8612. * with pgid == pid_of_first_child_in_pipe */
  8613. if (G.run_list_level == 1 && G_interactive_fd) {
  8614. pid_t pgrp;
  8615. pgrp = pi->pgrp;
  8616. if (pgrp < 0) /* true for 1st process only */
  8617. pgrp = getpid();
  8618. if (setpgid(0, pgrp) == 0
  8619. && pi->followup != PIPE_BG
  8620. && G_saved_tty_pgrp /* we have ctty */
  8621. ) {
  8622. /* We do it in *every* child, not just first,
  8623. * to avoid races */
  8624. tcsetpgrp(G_interactive_fd, pgrp);
  8625. }
  8626. }
  8627. #endif
  8628. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8629. /* 1st cmd in backgrounded pipe
  8630. * should have its stdin /dev/null'ed */
  8631. close(0);
  8632. if (open(bb_dev_null, O_RDONLY))
  8633. xopen("/", O_RDONLY);
  8634. } else {
  8635. xmove_fd(next_infd, 0);
  8636. }
  8637. xmove_fd(pipefds.wr, 1);
  8638. if (pipefds.rd > 1)
  8639. close(pipefds.rd);
  8640. /* Like bash, explicit redirects override pipes,
  8641. * and the pipe fd (fd#1) is available for dup'ing:
  8642. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8643. * of cmd1 goes into pipe.
  8644. */
  8645. if (setup_redirects(command, NULL)) {
  8646. /* Happens when redir file can't be opened:
  8647. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8648. * FOO
  8649. * hush: can't open '/qwe/rty': No such file or directory
  8650. * BAZ
  8651. * (echo BAR is not executed, it hits _exit(1) below)
  8652. */
  8653. _exit(1);
  8654. }
  8655. /* Stores to nommu_save list of env vars putenv'ed
  8656. * (NOMMU, on MMU we don't need that) */
  8657. /* cast away volatility... */
  8658. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8659. /* pseudo_exec() does not return */
  8660. }
  8661. /* parent or error */
  8662. #if ENABLE_HUSH_FAST
  8663. G.count_SIGCHLD++;
  8664. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8665. #endif
  8666. enable_restore_tty_pgrp_on_exit();
  8667. #if !BB_MMU
  8668. /* Clean up after vforked child */
  8669. free(nommu_save.argv);
  8670. free(nommu_save.argv_from_re_execing);
  8671. G.var_nest_level = sv_var_nest_level;
  8672. remove_nested_vars();
  8673. add_vars(nommu_save.old_vars);
  8674. #endif
  8675. free(argv_expanded);
  8676. argv_expanded = NULL;
  8677. if (command->pid < 0) { /* [v]fork failed */
  8678. /* Clearly indicate, was it fork or vfork */
  8679. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8680. } else {
  8681. pi->alive_cmds++;
  8682. #if ENABLE_HUSH_JOB
  8683. /* Second and next children need to know pid of first one */
  8684. if (pi->pgrp < 0)
  8685. pi->pgrp = command->pid;
  8686. #endif
  8687. }
  8688. if (cmd_no > 1)
  8689. close(next_infd);
  8690. if (cmd_no < pi->num_cmds)
  8691. close(pipefds.wr);
  8692. /* Pass read (output) pipe end to next iteration */
  8693. next_infd = pipefds.rd;
  8694. }
  8695. if (!pi->alive_cmds) {
  8696. debug_leave();
  8697. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8698. return 1;
  8699. }
  8700. debug_leave();
  8701. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8702. return -1;
  8703. }
  8704. /* NB: called by pseudo_exec, and therefore must not modify any
  8705. * global data until exec/_exit (we can be a child after vfork!) */
  8706. static int run_list(struct pipe *pi)
  8707. {
  8708. #if ENABLE_HUSH_CASE
  8709. char *case_word = NULL;
  8710. #endif
  8711. #if ENABLE_HUSH_LOOPS
  8712. struct pipe *loop_top = NULL;
  8713. char **for_lcur = NULL;
  8714. char **for_list = NULL;
  8715. #endif
  8716. smallint last_followup;
  8717. smalluint rcode;
  8718. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8719. smalluint cond_code = 0;
  8720. #else
  8721. enum { cond_code = 0 };
  8722. #endif
  8723. #if HAS_KEYWORDS
  8724. smallint rword; /* RES_foo */
  8725. smallint last_rword; /* ditto */
  8726. #endif
  8727. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8728. debug_enter();
  8729. #if ENABLE_HUSH_LOOPS
  8730. /* Check syntax for "for" */
  8731. {
  8732. struct pipe *cpipe;
  8733. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8734. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8735. continue;
  8736. /* current word is FOR or IN (BOLD in comments below) */
  8737. if (cpipe->next == NULL) {
  8738. syntax_error("malformed for");
  8739. debug_leave();
  8740. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8741. return 1;
  8742. }
  8743. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8744. if (cpipe->next->res_word == RES_DO)
  8745. continue;
  8746. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8747. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8748. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8749. ) {
  8750. syntax_error("malformed for");
  8751. debug_leave();
  8752. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8753. return 1;
  8754. }
  8755. }
  8756. }
  8757. #endif
  8758. /* Past this point, all code paths should jump to ret: label
  8759. * in order to return, no direct "return" statements please.
  8760. * This helps to ensure that no memory is leaked. */
  8761. #if ENABLE_HUSH_JOB
  8762. G.run_list_level++;
  8763. #endif
  8764. #if HAS_KEYWORDS
  8765. rword = RES_NONE;
  8766. last_rword = RES_XXXX;
  8767. #endif
  8768. last_followup = PIPE_SEQ;
  8769. rcode = G.last_exitcode;
  8770. /* Go through list of pipes, (maybe) executing them. */
  8771. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8772. int r;
  8773. int sv_errexit_depth;
  8774. if (G.flag_SIGINT)
  8775. break;
  8776. if (G_flag_return_in_progress == 1)
  8777. break;
  8778. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8779. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8780. rword, cond_code, last_rword);
  8781. sv_errexit_depth = G.errexit_depth;
  8782. if (
  8783. #if ENABLE_HUSH_IF
  8784. rword == RES_IF || rword == RES_ELIF ||
  8785. #endif
  8786. pi->followup != PIPE_SEQ
  8787. ) {
  8788. G.errexit_depth++;
  8789. }
  8790. #if ENABLE_HUSH_LOOPS
  8791. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8792. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8793. ) {
  8794. /* start of a loop: remember where loop starts */
  8795. loop_top = pi;
  8796. G.depth_of_loop++;
  8797. }
  8798. #endif
  8799. /* Still in the same "if...", "then..." or "do..." branch? */
  8800. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8801. if ((rcode == 0 && last_followup == PIPE_OR)
  8802. || (rcode != 0 && last_followup == PIPE_AND)
  8803. ) {
  8804. /* It is "<true> || CMD" or "<false> && CMD"
  8805. * and we should not execute CMD */
  8806. debug_printf_exec("skipped cmd because of || or &&\n");
  8807. last_followup = pi->followup;
  8808. goto dont_check_jobs_but_continue;
  8809. }
  8810. }
  8811. last_followup = pi->followup;
  8812. IF_HAS_KEYWORDS(last_rword = rword;)
  8813. #if ENABLE_HUSH_IF
  8814. if (cond_code) {
  8815. if (rword == RES_THEN) {
  8816. /* if false; then ... fi has exitcode 0! */
  8817. G.last_exitcode = rcode = EXIT_SUCCESS;
  8818. /* "if <false> THEN cmd": skip cmd */
  8819. continue;
  8820. }
  8821. } else {
  8822. if (rword == RES_ELSE || rword == RES_ELIF) {
  8823. /* "if <true> then ... ELSE/ELIF cmd":
  8824. * skip cmd and all following ones */
  8825. break;
  8826. }
  8827. }
  8828. #endif
  8829. #if ENABLE_HUSH_LOOPS
  8830. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8831. if (!for_lcur) {
  8832. /* first loop through for */
  8833. static const char encoded_dollar_at[] ALIGN1 = {
  8834. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8835. }; /* encoded representation of "$@" */
  8836. static const char *const encoded_dollar_at_argv[] = {
  8837. encoded_dollar_at, NULL
  8838. }; /* argv list with one element: "$@" */
  8839. char **vals;
  8840. G.last_exitcode = rcode = EXIT_SUCCESS;
  8841. vals = (char**)encoded_dollar_at_argv;
  8842. if (pi->next->res_word == RES_IN) {
  8843. /* if no variable values after "in" we skip "for" */
  8844. if (!pi->next->cmds[0].argv) {
  8845. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8846. break;
  8847. }
  8848. vals = pi->next->cmds[0].argv;
  8849. } /* else: "for var; do..." -> assume "$@" list */
  8850. /* create list of variable values */
  8851. debug_print_strings("for_list made from", vals);
  8852. for_list = expand_strvec_to_strvec(vals);
  8853. for_lcur = for_list;
  8854. debug_print_strings("for_list", for_list);
  8855. }
  8856. if (!*for_lcur) {
  8857. /* "for" loop is over, clean up */
  8858. free(for_list);
  8859. for_list = NULL;
  8860. for_lcur = NULL;
  8861. break;
  8862. }
  8863. /* Insert next value from for_lcur */
  8864. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8865. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8866. continue;
  8867. }
  8868. if (rword == RES_IN) {
  8869. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8870. }
  8871. if (rword == RES_DONE) {
  8872. continue; /* "done" has no cmds too */
  8873. }
  8874. #endif
  8875. #if ENABLE_HUSH_CASE
  8876. if (rword == RES_CASE) {
  8877. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8878. case_word = expand_string_to_string(pi->cmds->argv[0],
  8879. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8880. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8881. //unbackslash(case_word);
  8882. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8883. continue;
  8884. }
  8885. if (rword == RES_MATCH) {
  8886. char **argv;
  8887. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8888. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8889. break;
  8890. /* all prev words didn't match, does this one match? */
  8891. argv = pi->cmds->argv;
  8892. while (*argv) {
  8893. char *pattern;
  8894. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8895. pattern = expand_string_to_string(*argv,
  8896. EXP_FLAG_ESC_GLOB_CHARS,
  8897. /*unbackslash:*/ 0
  8898. );
  8899. /* TODO: which FNM_xxx flags to use? */
  8900. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8901. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8902. pattern, case_word, cond_code);
  8903. free(pattern);
  8904. if (cond_code == 0) {
  8905. /* match! we will execute this branch */
  8906. free(case_word);
  8907. case_word = NULL; /* make future "word)" stop */
  8908. break;
  8909. }
  8910. argv++;
  8911. }
  8912. continue;
  8913. }
  8914. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8915. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8916. if (cond_code != 0)
  8917. continue; /* not matched yet, skip this pipe */
  8918. }
  8919. if (rword == RES_ESAC) {
  8920. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8921. if (case_word) {
  8922. /* "case" did not match anything: still set $? (to 0) */
  8923. G.last_exitcode = rcode = EXIT_SUCCESS;
  8924. }
  8925. }
  8926. #endif
  8927. /* Just pressing <enter> in shell should check for jobs.
  8928. * OTOH, in non-interactive shell this is useless
  8929. * and only leads to extra job checks */
  8930. if (pi->num_cmds == 0) {
  8931. if (G_interactive_fd)
  8932. goto check_jobs_and_continue;
  8933. continue;
  8934. }
  8935. /* After analyzing all keywords and conditions, we decided
  8936. * to execute this pipe. NB: have to do checkjobs(NULL)
  8937. * after run_pipe to collect any background children,
  8938. * even if list execution is to be stopped. */
  8939. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8940. #if ENABLE_HUSH_LOOPS
  8941. G.flag_break_continue = 0;
  8942. #endif
  8943. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8944. if (r != -1) {
  8945. /* We ran a builtin, function, or group.
  8946. * rcode is already known
  8947. * and we don't need to wait for anything. */
  8948. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8949. G.last_exitcode = rcode;
  8950. check_and_run_traps();
  8951. #if ENABLE_HUSH_LOOPS
  8952. /* Was it "break" or "continue"? */
  8953. if (G.flag_break_continue) {
  8954. smallint fbc = G.flag_break_continue;
  8955. /* We might fall into outer *loop*,
  8956. * don't want to break it too */
  8957. if (loop_top) {
  8958. G.depth_break_continue--;
  8959. if (G.depth_break_continue == 0)
  8960. G.flag_break_continue = 0;
  8961. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8962. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8963. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8964. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8965. break;
  8966. }
  8967. /* "continue": simulate end of loop */
  8968. rword = RES_DONE;
  8969. continue;
  8970. }
  8971. #endif
  8972. if (G_flag_return_in_progress == 1) {
  8973. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8974. break;
  8975. }
  8976. } else if (pi->followup == PIPE_BG) {
  8977. /* What does bash do with attempts to background builtins? */
  8978. /* even bash 3.2 doesn't do that well with nested bg:
  8979. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8980. * I'm NOT treating inner &'s as jobs */
  8981. #if ENABLE_HUSH_JOB
  8982. if (G.run_list_level == 1)
  8983. insert_job_into_table(pi);
  8984. #endif
  8985. /* Last command's pid goes to $! */
  8986. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  8987. G.last_bg_pid_exitcode = 0;
  8988. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  8989. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  8990. rcode = EXIT_SUCCESS;
  8991. goto check_traps;
  8992. } else {
  8993. #if ENABLE_HUSH_JOB
  8994. if (G.run_list_level == 1 && G_interactive_fd) {
  8995. /* Waits for completion, then fg's main shell */
  8996. rcode = checkjobs_and_fg_shell(pi);
  8997. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  8998. goto check_traps;
  8999. }
  9000. #endif
  9001. /* This one just waits for completion */
  9002. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9003. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9004. check_traps:
  9005. G.last_exitcode = rcode;
  9006. check_and_run_traps();
  9007. }
  9008. /* Handle "set -e" */
  9009. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9010. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9011. if (G.errexit_depth == 0)
  9012. hush_exit(rcode);
  9013. }
  9014. G.errexit_depth = sv_errexit_depth;
  9015. /* Analyze how result affects subsequent commands */
  9016. #if ENABLE_HUSH_IF
  9017. if (rword == RES_IF || rword == RES_ELIF)
  9018. cond_code = rcode;
  9019. #endif
  9020. check_jobs_and_continue:
  9021. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9022. dont_check_jobs_but_continue: ;
  9023. #if ENABLE_HUSH_LOOPS
  9024. /* Beware of "while false; true; do ..."! */
  9025. if (pi->next
  9026. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9027. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9028. ) {
  9029. if (rword == RES_WHILE) {
  9030. if (rcode) {
  9031. /* "while false; do...done" - exitcode 0 */
  9032. G.last_exitcode = rcode = EXIT_SUCCESS;
  9033. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9034. break;
  9035. }
  9036. }
  9037. if (rword == RES_UNTIL) {
  9038. if (!rcode) {
  9039. debug_printf_exec(": until expr is true: breaking\n");
  9040. break;
  9041. }
  9042. }
  9043. }
  9044. #endif
  9045. } /* for (pi) */
  9046. #if ENABLE_HUSH_JOB
  9047. G.run_list_level--;
  9048. #endif
  9049. #if ENABLE_HUSH_LOOPS
  9050. if (loop_top)
  9051. G.depth_of_loop--;
  9052. free(for_list);
  9053. #endif
  9054. #if ENABLE_HUSH_CASE
  9055. free(case_word);
  9056. #endif
  9057. debug_leave();
  9058. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9059. return rcode;
  9060. }
  9061. /* Select which version we will use */
  9062. static int run_and_free_list(struct pipe *pi)
  9063. {
  9064. int rcode = 0;
  9065. debug_printf_exec("run_and_free_list entered\n");
  9066. if (!G.o_opt[OPT_O_NOEXEC]) {
  9067. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9068. rcode = run_list(pi);
  9069. }
  9070. /* free_pipe_list has the side effect of clearing memory.
  9071. * In the long run that function can be merged with run_list,
  9072. * but doing that now would hobble the debugging effort. */
  9073. free_pipe_list(pi);
  9074. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9075. return rcode;
  9076. }
  9077. static void install_sighandlers(unsigned mask)
  9078. {
  9079. sighandler_t old_handler;
  9080. unsigned sig = 0;
  9081. while ((mask >>= 1) != 0) {
  9082. sig++;
  9083. if (!(mask & 1))
  9084. continue;
  9085. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9086. /* POSIX allows shell to re-enable SIGCHLD
  9087. * even if it was SIG_IGN on entry.
  9088. * Therefore we skip IGN check for it:
  9089. */
  9090. if (sig == SIGCHLD)
  9091. continue;
  9092. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  9093. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  9094. */
  9095. //if (sig == SIGHUP) continue; - TODO?
  9096. if (old_handler == SIG_IGN) {
  9097. /* oops... restore back to IGN, and record this fact */
  9098. install_sighandler(sig, old_handler);
  9099. #if ENABLE_HUSH_TRAP
  9100. if (!G_traps)
  9101. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9102. free(G_traps[sig]);
  9103. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9104. #endif
  9105. }
  9106. }
  9107. }
  9108. /* Called a few times only (or even once if "sh -c") */
  9109. static void install_special_sighandlers(void)
  9110. {
  9111. unsigned mask;
  9112. /* Which signals are shell-special? */
  9113. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9114. if (G_interactive_fd) {
  9115. mask |= SPECIAL_INTERACTIVE_SIGS;
  9116. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9117. mask |= SPECIAL_JOBSTOP_SIGS;
  9118. }
  9119. /* Careful, do not re-install handlers we already installed */
  9120. if (G.special_sig_mask != mask) {
  9121. unsigned diff = mask & ~G.special_sig_mask;
  9122. G.special_sig_mask = mask;
  9123. install_sighandlers(diff);
  9124. }
  9125. }
  9126. #if ENABLE_HUSH_JOB
  9127. /* helper */
  9128. /* Set handlers to restore tty pgrp and exit */
  9129. static void install_fatal_sighandlers(void)
  9130. {
  9131. unsigned mask;
  9132. /* We will restore tty pgrp on these signals */
  9133. mask = 0
  9134. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9135. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9136. + (1 << SIGBUS ) * HUSH_DEBUG
  9137. + (1 << SIGSEGV) * HUSH_DEBUG
  9138. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9139. + (1 << SIGABRT)
  9140. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9141. + (1 << SIGPIPE)
  9142. + (1 << SIGALRM)
  9143. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9144. * if we aren't interactive... but in this case
  9145. * we never want to restore pgrp on exit, and this fn is not called
  9146. */
  9147. /*+ (1 << SIGHUP )*/
  9148. /*+ (1 << SIGTERM)*/
  9149. /*+ (1 << SIGINT )*/
  9150. ;
  9151. G_fatal_sig_mask = mask;
  9152. install_sighandlers(mask);
  9153. }
  9154. #endif
  9155. static int set_mode(int state, char mode, const char *o_opt)
  9156. {
  9157. int idx;
  9158. switch (mode) {
  9159. case 'n':
  9160. G.o_opt[OPT_O_NOEXEC] = state;
  9161. break;
  9162. case 'x':
  9163. IF_HUSH_MODE_X(G_x_mode = state;)
  9164. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9165. break;
  9166. case 'e':
  9167. G.o_opt[OPT_O_ERREXIT] = state;
  9168. break;
  9169. case 'o':
  9170. if (!o_opt) {
  9171. /* "set -o" or "set +o" without parameter.
  9172. * in bash, set -o produces this output:
  9173. * pipefail off
  9174. * and set +o:
  9175. * set +o pipefail
  9176. * We always use the second form.
  9177. */
  9178. const char *p = o_opt_strings;
  9179. idx = 0;
  9180. while (*p) {
  9181. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9182. idx++;
  9183. p += strlen(p) + 1;
  9184. }
  9185. break;
  9186. }
  9187. idx = index_in_strings(o_opt_strings, o_opt);
  9188. if (idx >= 0) {
  9189. G.o_opt[idx] = state;
  9190. break;
  9191. }
  9192. /* fall through to error */
  9193. default:
  9194. return EXIT_FAILURE;
  9195. }
  9196. return EXIT_SUCCESS;
  9197. }
  9198. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9199. int hush_main(int argc, char **argv)
  9200. {
  9201. enum {
  9202. OPT_login = (1 << 0),
  9203. };
  9204. unsigned flags;
  9205. unsigned builtin_argc;
  9206. char **e;
  9207. struct variable *cur_var;
  9208. struct variable *shell_ver;
  9209. INIT_G();
  9210. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9211. G.last_exitcode = EXIT_SUCCESS;
  9212. #if ENABLE_HUSH_FAST
  9213. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9214. #endif
  9215. #if !BB_MMU
  9216. G.argv0_for_re_execing = argv[0];
  9217. #endif
  9218. /* Deal with HUSH_VERSION */
  9219. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9220. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9221. shell_ver = xzalloc(sizeof(*shell_ver));
  9222. shell_ver->flg_export = 1;
  9223. shell_ver->flg_read_only = 1;
  9224. /* Code which handles ${var<op>...} needs writable values for all variables,
  9225. * therefore we xstrdup: */
  9226. shell_ver->varstr = xstrdup(hush_version_str);
  9227. /* Create shell local variables from the values
  9228. * currently living in the environment */
  9229. G.top_var = shell_ver;
  9230. cur_var = G.top_var;
  9231. e = environ;
  9232. if (e) while (*e) {
  9233. char *value = strchr(*e, '=');
  9234. if (value) { /* paranoia */
  9235. cur_var->next = xzalloc(sizeof(*cur_var));
  9236. cur_var = cur_var->next;
  9237. cur_var->varstr = *e;
  9238. cur_var->max_len = strlen(*e);
  9239. cur_var->flg_export = 1;
  9240. }
  9241. e++;
  9242. }
  9243. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9244. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9245. putenv(shell_ver->varstr);
  9246. /* Export PWD */
  9247. set_pwd_var(SETFLAG_EXPORT);
  9248. #if BASH_HOSTNAME_VAR
  9249. /* Set (but not export) HOSTNAME unless already set */
  9250. if (!get_local_var_value("HOSTNAME")) {
  9251. struct utsname uts;
  9252. uname(&uts);
  9253. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9254. }
  9255. #endif
  9256. /* IFS is not inherited from the parent environment */
  9257. set_local_var_from_halves("IFS", defifs);
  9258. if (!get_local_var_value("PATH"))
  9259. set_local_var_from_halves("PATH", bb_default_root_path);
  9260. /* PS1/PS2 are set later, if we determine that we are interactive */
  9261. /* bash also exports SHLVL and _,
  9262. * and sets (but doesn't export) the following variables:
  9263. * BASH=/bin/bash
  9264. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9265. * BASH_VERSION='3.2.0(1)-release'
  9266. * HOSTTYPE=i386
  9267. * MACHTYPE=i386-pc-linux-gnu
  9268. * OSTYPE=linux-gnu
  9269. * PPID=<NNNNN> - we also do it elsewhere
  9270. * EUID=<NNNNN>
  9271. * UID=<NNNNN>
  9272. * GROUPS=()
  9273. * LINES=<NNN>
  9274. * COLUMNS=<NNN>
  9275. * BASH_ARGC=()
  9276. * BASH_ARGV=()
  9277. * BASH_LINENO=()
  9278. * BASH_SOURCE=()
  9279. * DIRSTACK=()
  9280. * PIPESTATUS=([0]="0")
  9281. * HISTFILE=/<xxx>/.bash_history
  9282. * HISTFILESIZE=500
  9283. * HISTSIZE=500
  9284. * MAILCHECK=60
  9285. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9286. * SHELL=/bin/bash
  9287. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9288. * TERM=dumb
  9289. * OPTERR=1
  9290. * OPTIND=1
  9291. * PS4='+ '
  9292. */
  9293. /* Initialize some more globals to non-zero values */
  9294. die_func = restore_ttypgrp_and__exit;
  9295. /* Shell is non-interactive at first. We need to call
  9296. * install_special_sighandlers() if we are going to execute "sh <script>",
  9297. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9298. * If we later decide that we are interactive, we run install_special_sighandlers()
  9299. * in order to intercept (more) signals.
  9300. */
  9301. /* Parse options */
  9302. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9303. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9304. builtin_argc = 0;
  9305. #if NUM_SCRIPTS > 0
  9306. if (argc < 0) {
  9307. optarg = get_script_content(-argc - 1);
  9308. optind = 0;
  9309. argc = string_array_len(argv);
  9310. goto run_script;
  9311. }
  9312. #endif
  9313. while (1) {
  9314. int opt = getopt(argc, argv, "+c:exinsl"
  9315. #if !BB_MMU
  9316. "<:$:R:V:"
  9317. # if ENABLE_HUSH_FUNCTIONS
  9318. "F:"
  9319. # endif
  9320. #endif
  9321. );
  9322. if (opt <= 0)
  9323. break;
  9324. switch (opt) {
  9325. case 'c':
  9326. /* Possibilities:
  9327. * sh ... -c 'script'
  9328. * sh ... -c 'script' ARG0 [ARG1...]
  9329. * On NOMMU, if builtin_argc != 0,
  9330. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9331. * "" needs to be replaced with NULL
  9332. * and BARGV vector fed to builtin function.
  9333. * Note: the form without ARG0 never happens:
  9334. * sh ... -c 'builtin' BARGV... ""
  9335. */
  9336. #if NUM_SCRIPTS > 0
  9337. run_script:
  9338. #endif
  9339. if (!G.root_pid) {
  9340. G.root_pid = getpid();
  9341. G.root_ppid = getppid();
  9342. }
  9343. G.global_argv = argv + optind;
  9344. G.global_argc = argc - optind;
  9345. if (builtin_argc) {
  9346. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9347. const struct built_in_command *x;
  9348. install_special_sighandlers();
  9349. x = find_builtin(optarg);
  9350. if (x) { /* paranoia */
  9351. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9352. G.global_argv += builtin_argc;
  9353. G.global_argv[-1] = NULL; /* replace "" */
  9354. fflush_all();
  9355. G.last_exitcode = x->b_function(argv + optind - 1);
  9356. }
  9357. goto final_return;
  9358. }
  9359. G.opt_c = 1;
  9360. if (!G.global_argv[0]) {
  9361. /* -c 'script' (no params): prevent empty $0 */
  9362. G.global_argv--; /* points to argv[i] of 'script' */
  9363. G.global_argv[0] = argv[0];
  9364. G.global_argc++;
  9365. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9366. install_special_sighandlers();
  9367. parse_and_run_string(optarg);
  9368. goto final_return;
  9369. case 'i':
  9370. /* Well, we cannot just declare interactiveness,
  9371. * we have to have some stuff (ctty, etc) */
  9372. /* G_interactive_fd++; */
  9373. break;
  9374. case 's':
  9375. G.opt_s = 1;
  9376. break;
  9377. case 'l':
  9378. flags |= OPT_login;
  9379. break;
  9380. #if !BB_MMU
  9381. case '<': /* "big heredoc" support */
  9382. full_write1_str(optarg);
  9383. _exit(0);
  9384. case '$': {
  9385. unsigned long long empty_trap_mask;
  9386. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9387. optarg++;
  9388. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9389. optarg++;
  9390. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9391. optarg++;
  9392. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9393. optarg++;
  9394. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9395. optarg++;
  9396. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9397. if (empty_trap_mask != 0) {
  9398. IF_HUSH_TRAP(int sig;)
  9399. install_special_sighandlers();
  9400. # if ENABLE_HUSH_TRAP
  9401. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9402. for (sig = 1; sig < NSIG; sig++) {
  9403. if (empty_trap_mask & (1LL << sig)) {
  9404. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9405. install_sighandler(sig, SIG_IGN);
  9406. }
  9407. }
  9408. # endif
  9409. }
  9410. # if ENABLE_HUSH_LOOPS
  9411. optarg++;
  9412. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9413. # endif
  9414. # if ENABLE_HUSH_FUNCTIONS
  9415. /* nommu uses re-exec trick for "... | func | ...",
  9416. * should allow "return".
  9417. * This accidentally allows returns in subshells.
  9418. */
  9419. G_flag_return_in_progress = -1;
  9420. # endif
  9421. break;
  9422. }
  9423. case 'R':
  9424. case 'V':
  9425. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9426. break;
  9427. # if ENABLE_HUSH_FUNCTIONS
  9428. case 'F': {
  9429. struct function *funcp = new_function(optarg);
  9430. /* funcp->name is already set to optarg */
  9431. /* funcp->body is set to NULL. It's a special case. */
  9432. funcp->body_as_string = argv[optind];
  9433. optind++;
  9434. break;
  9435. }
  9436. # endif
  9437. #endif
  9438. case 'n':
  9439. case 'x':
  9440. case 'e':
  9441. if (set_mode(1, opt, NULL) == 0) /* no error */
  9442. break;
  9443. default:
  9444. #ifndef BB_VER
  9445. fprintf(stderr, "Usage: sh [FILE]...\n"
  9446. " or: sh -c command [args]...\n\n");
  9447. exit(EXIT_FAILURE);
  9448. #else
  9449. bb_show_usage();
  9450. #endif
  9451. }
  9452. } /* option parsing loop */
  9453. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9454. G.global_argc = argc - (optind - 1);
  9455. G.global_argv = argv + (optind - 1);
  9456. G.global_argv[0] = argv[0];
  9457. if (!G.root_pid) {
  9458. G.root_pid = getpid();
  9459. G.root_ppid = getppid();
  9460. }
  9461. /* If we are login shell... */
  9462. if (flags & OPT_login) {
  9463. HFILE *input;
  9464. debug_printf("sourcing /etc/profile\n");
  9465. input = hfopen("/etc/profile");
  9466. if (input != NULL) {
  9467. install_special_sighandlers();
  9468. parse_and_run_file(input);
  9469. hfclose(input);
  9470. }
  9471. /* bash: after sourcing /etc/profile,
  9472. * tries to source (in the given order):
  9473. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9474. * stopping on first found. --noprofile turns this off.
  9475. * bash also sources ~/.bash_logout on exit.
  9476. * If called as sh, skips .bash_XXX files.
  9477. */
  9478. }
  9479. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9480. if (!G.opt_s && G.global_argv[1]) {
  9481. HFILE *input;
  9482. /*
  9483. * "bash <script>" (which is never interactive (unless -i?))
  9484. * sources $BASH_ENV here (without scanning $PATH).
  9485. * If called as sh, does the same but with $ENV.
  9486. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9487. */
  9488. G.global_argc--;
  9489. G.global_argv++;
  9490. debug_printf("running script '%s'\n", G.global_argv[0]);
  9491. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9492. input = hfopen(G.global_argv[0]);
  9493. if (!input) {
  9494. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9495. }
  9496. xfunc_error_retval = 1;
  9497. install_special_sighandlers();
  9498. parse_and_run_file(input);
  9499. #if ENABLE_FEATURE_CLEAN_UP
  9500. hfclose(input);
  9501. #endif
  9502. goto final_return;
  9503. }
  9504. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9505. G.opt_s = 1;
  9506. /* Up to here, shell was non-interactive. Now it may become one.
  9507. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9508. */
  9509. /* A shell is interactive if the '-i' flag was given,
  9510. * or if all of the following conditions are met:
  9511. * no -c command
  9512. * no arguments remaining or the -s flag given
  9513. * standard input is a terminal
  9514. * standard output is a terminal
  9515. * Refer to Posix.2, the description of the 'sh' utility.
  9516. */
  9517. #if ENABLE_HUSH_JOB
  9518. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9519. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9520. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9521. if (G_saved_tty_pgrp < 0)
  9522. G_saved_tty_pgrp = 0;
  9523. /* try to dup stdin to high fd#, >= 255 */
  9524. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9525. if (G_interactive_fd < 0) {
  9526. /* try to dup to any fd */
  9527. G_interactive_fd = dup(STDIN_FILENO);
  9528. if (G_interactive_fd < 0) {
  9529. /* give up */
  9530. G_interactive_fd = 0;
  9531. G_saved_tty_pgrp = 0;
  9532. }
  9533. }
  9534. // TODO: track & disallow any attempts of user
  9535. // to (inadvertently) close/redirect G_interactive_fd
  9536. }
  9537. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9538. if (G_interactive_fd) {
  9539. close_on_exec_on(G_interactive_fd);
  9540. if (G_saved_tty_pgrp) {
  9541. /* If we were run as 'hush &', sleep until we are
  9542. * in the foreground (tty pgrp == our pgrp).
  9543. * If we get started under a job aware app (like bash),
  9544. * make sure we are now in charge so we don't fight over
  9545. * who gets the foreground */
  9546. while (1) {
  9547. pid_t shell_pgrp = getpgrp();
  9548. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9549. if (G_saved_tty_pgrp == shell_pgrp)
  9550. break;
  9551. /* send TTIN to ourself (should stop us) */
  9552. kill(- shell_pgrp, SIGTTIN);
  9553. }
  9554. }
  9555. /* Install more signal handlers */
  9556. install_special_sighandlers();
  9557. if (G_saved_tty_pgrp) {
  9558. /* Set other signals to restore saved_tty_pgrp */
  9559. install_fatal_sighandlers();
  9560. /* Put ourselves in our own process group
  9561. * (bash, too, does this only if ctty is available) */
  9562. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9563. /* Grab control of the terminal */
  9564. tcsetpgrp(G_interactive_fd, getpid());
  9565. }
  9566. enable_restore_tty_pgrp_on_exit();
  9567. # if ENABLE_FEATURE_EDITING
  9568. G.line_input_state = new_line_input_t(FOR_SHELL);
  9569. # endif
  9570. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9571. {
  9572. const char *hp = get_local_var_value("HISTFILE");
  9573. if (!hp) {
  9574. hp = get_local_var_value("HOME");
  9575. if (hp)
  9576. hp = concat_path_file(hp, ".hush_history");
  9577. } else {
  9578. hp = xstrdup(hp);
  9579. }
  9580. if (hp) {
  9581. G.line_input_state->hist_file = hp;
  9582. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9583. }
  9584. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9585. hp = get_local_var_value("HISTFILESIZE");
  9586. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9587. # endif
  9588. }
  9589. # endif
  9590. } else {
  9591. install_special_sighandlers();
  9592. }
  9593. #elif ENABLE_HUSH_INTERACTIVE
  9594. /* No job control compiled in, only prompt/line editing */
  9595. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9596. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9597. if (G_interactive_fd < 0) {
  9598. /* try to dup to any fd */
  9599. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9600. if (G_interactive_fd < 0)
  9601. /* give up */
  9602. G_interactive_fd = 0;
  9603. }
  9604. }
  9605. if (G_interactive_fd) {
  9606. close_on_exec_on(G_interactive_fd);
  9607. }
  9608. install_special_sighandlers();
  9609. #else
  9610. /* We have interactiveness code disabled */
  9611. install_special_sighandlers();
  9612. #endif
  9613. /* bash:
  9614. * if interactive but not a login shell, sources ~/.bashrc
  9615. * (--norc turns this off, --rcfile <file> overrides)
  9616. */
  9617. if (G_interactive_fd) {
  9618. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9619. /* Set (but not export) PS1/2 unless already set */
  9620. if (!get_local_var_value("PS1"))
  9621. set_local_var_from_halves("PS1", "\\w \\$ ");
  9622. if (!get_local_var_value("PS2"))
  9623. set_local_var_from_halves("PS2", "> ");
  9624. #endif
  9625. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9626. /* note: ash and hush share this string */
  9627. printf("\n\n%s %s\n"
  9628. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9629. "\n",
  9630. bb_banner,
  9631. "hush - the humble shell"
  9632. );
  9633. }
  9634. }
  9635. parse_and_run_file(hfopen(NULL)); /* stdin */
  9636. final_return:
  9637. hush_exit(G.last_exitcode);
  9638. }
  9639. /*
  9640. * Built-ins
  9641. */
  9642. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9643. {
  9644. return 0;
  9645. }
  9646. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9647. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9648. {
  9649. int argc = string_array_len(argv);
  9650. return applet_main_func(argc, argv);
  9651. }
  9652. #endif
  9653. #if ENABLE_HUSH_TEST || BASH_TEST2
  9654. static int FAST_FUNC builtin_test(char **argv)
  9655. {
  9656. return run_applet_main(argv, test_main);
  9657. }
  9658. #endif
  9659. #if ENABLE_HUSH_ECHO
  9660. static int FAST_FUNC builtin_echo(char **argv)
  9661. {
  9662. return run_applet_main(argv, echo_main);
  9663. }
  9664. #endif
  9665. #if ENABLE_HUSH_PRINTF
  9666. static int FAST_FUNC builtin_printf(char **argv)
  9667. {
  9668. return run_applet_main(argv, printf_main);
  9669. }
  9670. #endif
  9671. #if ENABLE_HUSH_HELP
  9672. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9673. {
  9674. const struct built_in_command *x;
  9675. printf(
  9676. "Built-in commands:\n"
  9677. "------------------\n");
  9678. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9679. if (x->b_descr)
  9680. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9681. }
  9682. return EXIT_SUCCESS;
  9683. }
  9684. #endif
  9685. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9686. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9687. {
  9688. if (G.line_input_state)
  9689. show_history(G.line_input_state);
  9690. return EXIT_SUCCESS;
  9691. }
  9692. #endif
  9693. static char **skip_dash_dash(char **argv)
  9694. {
  9695. argv++;
  9696. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9697. argv++;
  9698. return argv;
  9699. }
  9700. static int FAST_FUNC builtin_cd(char **argv)
  9701. {
  9702. const char *newdir;
  9703. argv = skip_dash_dash(argv);
  9704. newdir = argv[0];
  9705. if (newdir == NULL) {
  9706. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9707. * bash says "bash: cd: HOME not set" and does nothing
  9708. * (exitcode 1)
  9709. */
  9710. const char *home = get_local_var_value("HOME");
  9711. newdir = home ? home : "/";
  9712. }
  9713. if (chdir(newdir)) {
  9714. /* Mimic bash message exactly */
  9715. bb_perror_msg("cd: %s", newdir);
  9716. return EXIT_FAILURE;
  9717. }
  9718. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9719. * Note: do not enforce exporting. If PWD was unset or unexported,
  9720. * set it again, but do not export. bash does the same.
  9721. */
  9722. set_pwd_var(/*flag:*/ 0);
  9723. return EXIT_SUCCESS;
  9724. }
  9725. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9726. {
  9727. puts(get_cwd(0));
  9728. return EXIT_SUCCESS;
  9729. }
  9730. static int FAST_FUNC builtin_eval(char **argv)
  9731. {
  9732. argv = skip_dash_dash(argv);
  9733. if (!argv[0])
  9734. return EXIT_SUCCESS;
  9735. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9736. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9737. if (!argv[1]) {
  9738. /* bash:
  9739. * eval "echo Hi; done" ("done" is syntax error):
  9740. * "echo Hi" will not execute too.
  9741. */
  9742. parse_and_run_string(argv[0]);
  9743. } else {
  9744. /* "The eval utility shall construct a command by
  9745. * concatenating arguments together, separating
  9746. * each with a <space> character."
  9747. */
  9748. char *str, *p;
  9749. unsigned len = 0;
  9750. char **pp = argv;
  9751. do
  9752. len += strlen(*pp) + 1;
  9753. while (*++pp);
  9754. str = p = xmalloc(len);
  9755. pp = argv;
  9756. for (;;) {
  9757. p = stpcpy(p, *pp);
  9758. pp++;
  9759. if (!*pp)
  9760. break;
  9761. *p++ = ' ';
  9762. }
  9763. parse_and_run_string(str);
  9764. free(str);
  9765. }
  9766. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9767. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9768. return G.last_exitcode;
  9769. }
  9770. static int FAST_FUNC builtin_exec(char **argv)
  9771. {
  9772. argv = skip_dash_dash(argv);
  9773. if (argv[0] == NULL)
  9774. return EXIT_SUCCESS; /* bash does this */
  9775. /* Careful: we can end up here after [v]fork. Do not restore
  9776. * tty pgrp then, only top-level shell process does that */
  9777. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9778. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9779. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9780. * open here. However, they are all CLOEXEC, and execv below
  9781. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9782. * it should show no extra open fds in the "ls" process.
  9783. * If we'd try to run builtins/NOEXECs, this would need improving.
  9784. */
  9785. //close_saved_fds_and_FILE_fds();
  9786. /* TODO: if exec fails, bash does NOT exit! We do.
  9787. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9788. * and tcsetpgrp, and this is inherently racy.
  9789. */
  9790. execvp_or_die(argv);
  9791. }
  9792. static int FAST_FUNC builtin_exit(char **argv)
  9793. {
  9794. debug_printf_exec("%s()\n", __func__);
  9795. /* interactive bash:
  9796. * # trap "echo EEE" EXIT
  9797. * # exit
  9798. * exit
  9799. * There are stopped jobs.
  9800. * (if there are _stopped_ jobs, running ones don't count)
  9801. * # exit
  9802. * exit
  9803. * EEE (then bash exits)
  9804. *
  9805. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9806. */
  9807. /* note: EXIT trap is run by hush_exit */
  9808. argv = skip_dash_dash(argv);
  9809. if (argv[0] == NULL)
  9810. hush_exit(G.last_exitcode);
  9811. /* mimic bash: exit 123abc == exit 255 + error msg */
  9812. xfunc_error_retval = 255;
  9813. /* bash: exit -2 == exit 254, no error msg */
  9814. hush_exit(xatoi(argv[0]) & 0xff);
  9815. }
  9816. #if ENABLE_HUSH_TYPE
  9817. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9818. static int FAST_FUNC builtin_type(char **argv)
  9819. {
  9820. int ret = EXIT_SUCCESS;
  9821. while (*++argv) {
  9822. const char *type;
  9823. char *path = NULL;
  9824. if (0) {} /* make conditional compile easier below */
  9825. /*else if (find_alias(*argv))
  9826. type = "an alias";*/
  9827. #if ENABLE_HUSH_FUNCTIONS
  9828. else if (find_function(*argv))
  9829. type = "a function";
  9830. #endif
  9831. else if (find_builtin(*argv))
  9832. type = "a shell builtin";
  9833. else if ((path = find_in_path(*argv)) != NULL)
  9834. type = path;
  9835. else {
  9836. bb_error_msg("type: %s: not found", *argv);
  9837. ret = EXIT_FAILURE;
  9838. continue;
  9839. }
  9840. printf("%s is %s\n", *argv, type);
  9841. free(path);
  9842. }
  9843. return ret;
  9844. }
  9845. #endif
  9846. #if ENABLE_HUSH_READ
  9847. /* Interruptibility of read builtin in bash
  9848. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9849. *
  9850. * Empty trap makes read ignore corresponding signal, for any signal.
  9851. *
  9852. * SIGINT:
  9853. * - terminates non-interactive shell;
  9854. * - interrupts read in interactive shell;
  9855. * if it has non-empty trap:
  9856. * - executes trap and returns to command prompt in interactive shell;
  9857. * - executes trap and returns to read in non-interactive shell;
  9858. * SIGTERM:
  9859. * - is ignored (does not interrupt) read in interactive shell;
  9860. * - terminates non-interactive shell;
  9861. * if it has non-empty trap:
  9862. * - executes trap and returns to read;
  9863. * SIGHUP:
  9864. * - terminates shell (regardless of interactivity);
  9865. * if it has non-empty trap:
  9866. * - executes trap and returns to read;
  9867. * SIGCHLD from children:
  9868. * - does not interrupt read regardless of interactivity:
  9869. * try: sleep 1 & read x; echo $x
  9870. */
  9871. static int FAST_FUNC builtin_read(char **argv)
  9872. {
  9873. const char *r;
  9874. struct builtin_read_params params;
  9875. memset(&params, 0, sizeof(params));
  9876. /* "!": do not abort on errors.
  9877. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9878. */
  9879. params.read_flags = getopt32(argv,
  9880. #if BASH_READ_D
  9881. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9882. #else
  9883. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9884. #endif
  9885. );
  9886. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9887. return EXIT_FAILURE;
  9888. argv += optind;
  9889. params.argv = argv;
  9890. params.setvar = set_local_var_from_halves;
  9891. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9892. again:
  9893. r = shell_builtin_read(&params);
  9894. if ((uintptr_t)r == 1 && errno == EINTR) {
  9895. unsigned sig = check_and_run_traps();
  9896. if (sig != SIGINT)
  9897. goto again;
  9898. }
  9899. if ((uintptr_t)r > 1) {
  9900. bb_error_msg("%s", r);
  9901. r = (char*)(uintptr_t)1;
  9902. }
  9903. return (uintptr_t)r;
  9904. }
  9905. #endif
  9906. #if ENABLE_HUSH_UMASK
  9907. static int FAST_FUNC builtin_umask(char **argv)
  9908. {
  9909. int rc;
  9910. mode_t mask;
  9911. rc = 1;
  9912. mask = umask(0);
  9913. argv = skip_dash_dash(argv);
  9914. if (argv[0]) {
  9915. mode_t old_mask = mask;
  9916. /* numeric umasks are taken as-is */
  9917. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9918. if (!isdigit(argv[0][0]))
  9919. mask ^= 0777;
  9920. mask = bb_parse_mode(argv[0], mask);
  9921. if (!isdigit(argv[0][0]))
  9922. mask ^= 0777;
  9923. if ((unsigned)mask > 0777) {
  9924. mask = old_mask;
  9925. /* bash messages:
  9926. * bash: umask: 'q': invalid symbolic mode operator
  9927. * bash: umask: 999: octal number out of range
  9928. */
  9929. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9930. rc = 0;
  9931. }
  9932. } else {
  9933. /* Mimic bash */
  9934. printf("%04o\n", (unsigned) mask);
  9935. /* fall through and restore mask which we set to 0 */
  9936. }
  9937. umask(mask);
  9938. return !rc; /* rc != 0 - success */
  9939. }
  9940. #endif
  9941. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9942. static void print_escaped(const char *s)
  9943. {
  9944. if (*s == '\'')
  9945. goto squote;
  9946. do {
  9947. const char *p = strchrnul(s, '\'');
  9948. /* print 'xxxx', possibly just '' */
  9949. printf("'%.*s'", (int)(p - s), s);
  9950. if (*p == '\0')
  9951. break;
  9952. s = p;
  9953. squote:
  9954. /* s points to '; print "'''...'''" */
  9955. putchar('"');
  9956. do putchar('\''); while (*++s == '\'');
  9957. putchar('"');
  9958. } while (*s);
  9959. }
  9960. #endif
  9961. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9962. static int helper_export_local(char **argv, unsigned flags)
  9963. {
  9964. do {
  9965. char *name = *argv;
  9966. const char *name_end = endofname(name);
  9967. if (*name_end == '\0') {
  9968. struct variable *var, **vpp;
  9969. vpp = get_ptr_to_local_var(name, name_end - name);
  9970. var = vpp ? *vpp : NULL;
  9971. if (flags & SETFLAG_UNEXPORT) {
  9972. /* export -n NAME (without =VALUE) */
  9973. if (var) {
  9974. var->flg_export = 0;
  9975. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9976. unsetenv(name);
  9977. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9978. continue;
  9979. }
  9980. if (flags & SETFLAG_EXPORT) {
  9981. /* export NAME (without =VALUE) */
  9982. if (var) {
  9983. var->flg_export = 1;
  9984. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  9985. putenv(var->varstr);
  9986. continue;
  9987. }
  9988. }
  9989. if (flags & SETFLAG_MAKE_RO) {
  9990. /* readonly NAME (without =VALUE) */
  9991. if (var) {
  9992. var->flg_read_only = 1;
  9993. continue;
  9994. }
  9995. }
  9996. # if ENABLE_HUSH_LOCAL
  9997. /* Is this "local" bltin? */
  9998. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  9999. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10000. if (var && var->var_nest_level == lvl) {
  10001. /* "local x=abc; ...; local x" - ignore second local decl */
  10002. continue;
  10003. }
  10004. }
  10005. # endif
  10006. /* Exporting non-existing variable.
  10007. * bash does not put it in environment,
  10008. * but remembers that it is exported,
  10009. * and does put it in env when it is set later.
  10010. * We just set it to "" and export.
  10011. */
  10012. /* Or, it's "local NAME" (without =VALUE).
  10013. * bash sets the value to "".
  10014. */
  10015. /* Or, it's "readonly NAME" (without =VALUE).
  10016. * bash remembers NAME and disallows its creation
  10017. * in the future.
  10018. */
  10019. name = xasprintf("%s=", name);
  10020. } else {
  10021. if (*name_end != '=') {
  10022. bb_error_msg("'%s': bad variable name", name);
  10023. /* do not parse following argv[]s: */
  10024. return 1;
  10025. }
  10026. /* (Un)exporting/making local NAME=VALUE */
  10027. name = xstrdup(name);
  10028. /* Testcase: export PS1='\w \$ ' */
  10029. unbackslash(name);
  10030. }
  10031. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10032. if (set_local_var(name, flags))
  10033. return EXIT_FAILURE;
  10034. } while (*++argv);
  10035. return EXIT_SUCCESS;
  10036. }
  10037. #endif
  10038. #if ENABLE_HUSH_EXPORT
  10039. static int FAST_FUNC builtin_export(char **argv)
  10040. {
  10041. unsigned opt_unexport;
  10042. #if ENABLE_HUSH_EXPORT_N
  10043. /* "!": do not abort on errors */
  10044. opt_unexport = getopt32(argv, "!n");
  10045. if (opt_unexport == (uint32_t)-1)
  10046. return EXIT_FAILURE;
  10047. argv += optind;
  10048. #else
  10049. opt_unexport = 0;
  10050. argv++;
  10051. #endif
  10052. if (argv[0] == NULL) {
  10053. char **e = environ;
  10054. if (e) {
  10055. while (*e) {
  10056. #if 0
  10057. puts(*e++);
  10058. #else
  10059. /* ash emits: export VAR='VAL'
  10060. * bash: declare -x VAR="VAL"
  10061. * we follow ash example */
  10062. const char *s = *e++;
  10063. const char *p = strchr(s, '=');
  10064. if (!p) /* wtf? take next variable */
  10065. continue;
  10066. /* export var= */
  10067. printf("export %.*s", (int)(p - s) + 1, s);
  10068. print_escaped(p + 1);
  10069. putchar('\n');
  10070. #endif
  10071. }
  10072. /*fflush_all(); - done after each builtin anyway */
  10073. }
  10074. return EXIT_SUCCESS;
  10075. }
  10076. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10077. }
  10078. #endif
  10079. #if ENABLE_HUSH_LOCAL
  10080. static int FAST_FUNC builtin_local(char **argv)
  10081. {
  10082. if (G.func_nest_level == 0) {
  10083. bb_error_msg("%s: not in a function", argv[0]);
  10084. return EXIT_FAILURE; /* bash compat */
  10085. }
  10086. argv++;
  10087. /* Since all builtins run in a nested variable level,
  10088. * need to use level - 1 here. Or else the variable will be removed at once
  10089. * after builtin returns.
  10090. */
  10091. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10092. }
  10093. #endif
  10094. #if ENABLE_HUSH_READONLY
  10095. static int FAST_FUNC builtin_readonly(char **argv)
  10096. {
  10097. argv++;
  10098. if (*argv == NULL) {
  10099. /* bash: readonly [-p]: list all readonly VARs
  10100. * (-p has no effect in bash)
  10101. */
  10102. struct variable *e;
  10103. for (e = G.top_var; e; e = e->next) {
  10104. if (e->flg_read_only) {
  10105. //TODO: quote value: readonly VAR='VAL'
  10106. printf("readonly %s\n", e->varstr);
  10107. }
  10108. }
  10109. return EXIT_SUCCESS;
  10110. }
  10111. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10112. }
  10113. #endif
  10114. #if ENABLE_HUSH_UNSET
  10115. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10116. static int FAST_FUNC builtin_unset(char **argv)
  10117. {
  10118. int ret;
  10119. unsigned opts;
  10120. /* "!": do not abort on errors */
  10121. /* "+": stop at 1st non-option */
  10122. opts = getopt32(argv, "!+vf");
  10123. if (opts == (unsigned)-1)
  10124. return EXIT_FAILURE;
  10125. if (opts == 3) {
  10126. bb_error_msg("unset: -v and -f are exclusive");
  10127. return EXIT_FAILURE;
  10128. }
  10129. argv += optind;
  10130. ret = EXIT_SUCCESS;
  10131. while (*argv) {
  10132. if (!(opts & 2)) { /* not -f */
  10133. if (unset_local_var(*argv)) {
  10134. /* unset <nonexistent_var> doesn't fail.
  10135. * Error is when one tries to unset RO var.
  10136. * Message was printed by unset_local_var. */
  10137. ret = EXIT_FAILURE;
  10138. }
  10139. }
  10140. # if ENABLE_HUSH_FUNCTIONS
  10141. else {
  10142. unset_func(*argv);
  10143. }
  10144. # endif
  10145. argv++;
  10146. }
  10147. return ret;
  10148. }
  10149. #endif
  10150. #if ENABLE_HUSH_SET
  10151. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10152. * built-in 'set' handler
  10153. * SUSv3 says:
  10154. * set [-abCefhmnuvx] [-o option] [argument...]
  10155. * set [+abCefhmnuvx] [+o option] [argument...]
  10156. * set -- [argument...]
  10157. * set -o
  10158. * set +o
  10159. * Implementations shall support the options in both their hyphen and
  10160. * plus-sign forms. These options can also be specified as options to sh.
  10161. * Examples:
  10162. * Write out all variables and their values: set
  10163. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10164. * Turn on the -x and -v options: set -xv
  10165. * Unset all positional parameters: set --
  10166. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10167. * Set the positional parameters to the expansion of x, even if x expands
  10168. * with a leading '-' or '+': set -- $x
  10169. *
  10170. * So far, we only support "set -- [argument...]" and some of the short names.
  10171. */
  10172. static int FAST_FUNC builtin_set(char **argv)
  10173. {
  10174. int n;
  10175. char **pp, **g_argv;
  10176. char *arg = *++argv;
  10177. if (arg == NULL) {
  10178. struct variable *e;
  10179. for (e = G.top_var; e; e = e->next)
  10180. puts(e->varstr);
  10181. return EXIT_SUCCESS;
  10182. }
  10183. do {
  10184. if (strcmp(arg, "--") == 0) {
  10185. ++argv;
  10186. goto set_argv;
  10187. }
  10188. if (arg[0] != '+' && arg[0] != '-')
  10189. break;
  10190. for (n = 1; arg[n]; ++n) {
  10191. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10192. bb_error_msg("%s: %s: invalid option", "set", arg);
  10193. return EXIT_FAILURE;
  10194. }
  10195. if (arg[n] == 'o' && argv[1])
  10196. argv++;
  10197. }
  10198. } while ((arg = *++argv) != NULL);
  10199. /* Now argv[0] is 1st argument */
  10200. if (arg == NULL)
  10201. return EXIT_SUCCESS;
  10202. set_argv:
  10203. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10204. g_argv = G.global_argv;
  10205. if (G.global_args_malloced) {
  10206. pp = g_argv;
  10207. while (*++pp)
  10208. free(*pp);
  10209. g_argv[1] = NULL;
  10210. } else {
  10211. G.global_args_malloced = 1;
  10212. pp = xzalloc(sizeof(pp[0]) * 2);
  10213. pp[0] = g_argv[0]; /* retain $0 */
  10214. g_argv = pp;
  10215. }
  10216. /* This realloc's G.global_argv */
  10217. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10218. G.global_argc = 1 + string_array_len(pp + 1);
  10219. return EXIT_SUCCESS;
  10220. }
  10221. #endif
  10222. static int FAST_FUNC builtin_shift(char **argv)
  10223. {
  10224. int n = 1;
  10225. argv = skip_dash_dash(argv);
  10226. if (argv[0]) {
  10227. n = bb_strtou(argv[0], NULL, 10);
  10228. if (errno || n < 0) {
  10229. /* shared string with ash.c */
  10230. bb_error_msg("Illegal number: %s", argv[0]);
  10231. /*
  10232. * ash aborts in this case.
  10233. * bash prints error message and set $? to 1.
  10234. * Interestingly, for "shift 99999" bash does not
  10235. * print error message, but does set $? to 1
  10236. * (and does no shifting at all).
  10237. */
  10238. }
  10239. }
  10240. if (n >= 0 && n < G.global_argc) {
  10241. if (G_global_args_malloced) {
  10242. int m = 1;
  10243. while (m <= n)
  10244. free(G.global_argv[m++]);
  10245. }
  10246. G.global_argc -= n;
  10247. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10248. G.global_argc * sizeof(G.global_argv[0]));
  10249. return EXIT_SUCCESS;
  10250. }
  10251. return EXIT_FAILURE;
  10252. }
  10253. #if ENABLE_HUSH_GETOPTS
  10254. static int FAST_FUNC builtin_getopts(char **argv)
  10255. {
  10256. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10257. TODO:
  10258. If a required argument is not found, and getopts is not silent,
  10259. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10260. diagnostic message is printed. If getopts is silent, then a
  10261. colon (:) is placed in VAR and OPTARG is set to the option
  10262. character found.
  10263. Test that VAR is a valid variable name?
  10264. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10265. */
  10266. char cbuf[2];
  10267. const char *cp, *optstring, *var;
  10268. int c, n, exitcode, my_opterr;
  10269. unsigned count;
  10270. optstring = *++argv;
  10271. if (!optstring || !(var = *++argv)) {
  10272. bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10273. return EXIT_FAILURE;
  10274. }
  10275. if (argv[1])
  10276. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10277. else
  10278. argv = G.global_argv;
  10279. cbuf[1] = '\0';
  10280. my_opterr = 0;
  10281. if (optstring[0] != ':') {
  10282. cp = get_local_var_value("OPTERR");
  10283. /* 0 if "OPTERR=0", 1 otherwise */
  10284. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10285. }
  10286. /* getopts stops on first non-option. Add "+" to force that */
  10287. /*if (optstring[0] != '+')*/ {
  10288. char *s = alloca(strlen(optstring) + 2);
  10289. sprintf(s, "+%s", optstring);
  10290. optstring = s;
  10291. }
  10292. /* Naively, now we should just
  10293. * cp = get_local_var_value("OPTIND");
  10294. * optind = cp ? atoi(cp) : 0;
  10295. * optarg = NULL;
  10296. * opterr = my_opterr;
  10297. * c = getopt(string_array_len(argv), argv, optstring);
  10298. * and be done? Not so fast...
  10299. * Unlike normal getopt() usage in C programs, here
  10300. * each successive call will (usually) have the same argv[] CONTENTS,
  10301. * but not the ADDRESSES. Worse yet, it's possible that between
  10302. * invocations of "getopts", there will be calls to shell builtins
  10303. * which use getopt() internally. Example:
  10304. * while getopts "abc" RES -a -bc -abc de; do
  10305. * unset -ff func
  10306. * done
  10307. * This would not work correctly: getopt() call inside "unset"
  10308. * modifies internal libc state which is tracking position in
  10309. * multi-option strings ("-abc"). At best, it can skip options
  10310. * or return the same option infinitely. With glibc implementation
  10311. * of getopt(), it would use outright invalid pointers and return
  10312. * garbage even _without_ "unset" mangling internal state.
  10313. *
  10314. * We resort to resetting getopt() state and calling it N times,
  10315. * until we get Nth result (or failure).
  10316. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10317. */
  10318. GETOPT_RESET();
  10319. count = 0;
  10320. n = string_array_len(argv);
  10321. do {
  10322. optarg = NULL;
  10323. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10324. c = getopt(n, argv, optstring);
  10325. if (c < 0)
  10326. break;
  10327. count++;
  10328. } while (count <= G.getopt_count);
  10329. /* Set OPTIND. Prevent resetting of the magic counter! */
  10330. set_local_var_from_halves("OPTIND", utoa(optind));
  10331. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10332. GETOPT_RESET(); /* just in case */
  10333. /* Set OPTARG */
  10334. /* Always set or unset, never left as-is, even on exit/error:
  10335. * "If no option was found, or if the option that was found
  10336. * does not have an option-argument, OPTARG shall be unset."
  10337. */
  10338. cp = optarg;
  10339. if (c == '?') {
  10340. /* If ":optstring" and unknown option is seen,
  10341. * it is stored to OPTARG.
  10342. */
  10343. if (optstring[1] == ':') {
  10344. cbuf[0] = optopt;
  10345. cp = cbuf;
  10346. }
  10347. }
  10348. if (cp)
  10349. set_local_var_from_halves("OPTARG", cp);
  10350. else
  10351. unset_local_var("OPTARG");
  10352. /* Convert -1 to "?" */
  10353. exitcode = EXIT_SUCCESS;
  10354. if (c < 0) { /* -1: end of options */
  10355. exitcode = EXIT_FAILURE;
  10356. c = '?';
  10357. }
  10358. /* Set VAR */
  10359. cbuf[0] = c;
  10360. set_local_var_from_halves(var, cbuf);
  10361. return exitcode;
  10362. }
  10363. #endif
  10364. static int FAST_FUNC builtin_source(char **argv)
  10365. {
  10366. char *arg_path, *filename;
  10367. HFILE *input;
  10368. save_arg_t sv;
  10369. char *args_need_save;
  10370. #if ENABLE_HUSH_FUNCTIONS
  10371. smallint sv_flg;
  10372. #endif
  10373. argv = skip_dash_dash(argv);
  10374. filename = argv[0];
  10375. if (!filename) {
  10376. /* bash says: "bash: .: filename argument required" */
  10377. return 2; /* bash compat */
  10378. }
  10379. arg_path = NULL;
  10380. if (!strchr(filename, '/')) {
  10381. arg_path = find_in_path(filename);
  10382. if (arg_path)
  10383. filename = arg_path;
  10384. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10385. errno = ENOENT;
  10386. bb_simple_perror_msg(filename);
  10387. return EXIT_FAILURE;
  10388. }
  10389. }
  10390. input = hfopen(filename);
  10391. free(arg_path);
  10392. if (!input) {
  10393. bb_perror_msg("%s", filename);
  10394. /* POSIX: non-interactive shell should abort here,
  10395. * not merely fail. So far no one complained :)
  10396. */
  10397. return EXIT_FAILURE;
  10398. }
  10399. #if ENABLE_HUSH_FUNCTIONS
  10400. sv_flg = G_flag_return_in_progress;
  10401. /* "we are inside sourced file, ok to use return" */
  10402. G_flag_return_in_progress = -1;
  10403. #endif
  10404. args_need_save = argv[1]; /* used as a boolean variable */
  10405. if (args_need_save)
  10406. save_and_replace_G_args(&sv, argv);
  10407. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10408. G.last_exitcode = 0;
  10409. parse_and_run_file(input);
  10410. hfclose(input);
  10411. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10412. restore_G_args(&sv, argv);
  10413. #if ENABLE_HUSH_FUNCTIONS
  10414. G_flag_return_in_progress = sv_flg;
  10415. #endif
  10416. return G.last_exitcode;
  10417. }
  10418. #if ENABLE_HUSH_TRAP
  10419. static int FAST_FUNC builtin_trap(char **argv)
  10420. {
  10421. int sig;
  10422. char *new_cmd;
  10423. if (!G_traps)
  10424. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10425. argv++;
  10426. if (!*argv) {
  10427. int i;
  10428. /* No args: print all trapped */
  10429. for (i = 0; i < NSIG; ++i) {
  10430. if (G_traps[i]) {
  10431. printf("trap -- ");
  10432. print_escaped(G_traps[i]);
  10433. /* note: bash adds "SIG", but only if invoked
  10434. * as "bash". If called as "sh", or if set -o posix,
  10435. * then it prints short signal names.
  10436. * We are printing short names: */
  10437. printf(" %s\n", get_signame(i));
  10438. }
  10439. }
  10440. /*fflush_all(); - done after each builtin anyway */
  10441. return EXIT_SUCCESS;
  10442. }
  10443. new_cmd = NULL;
  10444. /* If first arg is a number: reset all specified signals */
  10445. sig = bb_strtou(*argv, NULL, 10);
  10446. if (errno == 0) {
  10447. int ret;
  10448. process_sig_list:
  10449. ret = EXIT_SUCCESS;
  10450. while (*argv) {
  10451. sighandler_t handler;
  10452. sig = get_signum(*argv++);
  10453. if (sig < 0) {
  10454. ret = EXIT_FAILURE;
  10455. /* Mimic bash message exactly */
  10456. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10457. continue;
  10458. }
  10459. free(G_traps[sig]);
  10460. G_traps[sig] = xstrdup(new_cmd);
  10461. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10462. get_signame(sig), sig, G_traps[sig]);
  10463. /* There is no signal for 0 (EXIT) */
  10464. if (sig == 0)
  10465. continue;
  10466. if (new_cmd)
  10467. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10468. else
  10469. /* We are removing trap handler */
  10470. handler = pick_sighandler(sig);
  10471. install_sighandler(sig, handler);
  10472. }
  10473. return ret;
  10474. }
  10475. if (!argv[1]) { /* no second arg */
  10476. bb_error_msg("trap: invalid arguments");
  10477. return EXIT_FAILURE;
  10478. }
  10479. /* First arg is "-": reset all specified to default */
  10480. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10481. /* Everything else: set arg as signal handler
  10482. * (includes "" case, which ignores signal) */
  10483. if (argv[0][0] == '-') {
  10484. if (argv[0][1] == '\0') { /* "-" */
  10485. /* new_cmd remains NULL: "reset these sigs" */
  10486. goto reset_traps;
  10487. }
  10488. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10489. argv++;
  10490. }
  10491. /* else: "-something", no special meaning */
  10492. }
  10493. new_cmd = *argv;
  10494. reset_traps:
  10495. argv++;
  10496. goto process_sig_list;
  10497. }
  10498. #endif
  10499. #if ENABLE_HUSH_JOB
  10500. static struct pipe *parse_jobspec(const char *str)
  10501. {
  10502. struct pipe *pi;
  10503. unsigned jobnum;
  10504. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10505. if (str[0] != '%'
  10506. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10507. ) {
  10508. bb_error_msg("bad argument '%s'", str);
  10509. return NULL;
  10510. }
  10511. /* It is "%%", "%+" or "%" - current job */
  10512. jobnum = G.last_jobid;
  10513. if (jobnum == 0) {
  10514. bb_error_msg("no current job");
  10515. return NULL;
  10516. }
  10517. }
  10518. for (pi = G.job_list; pi; pi = pi->next) {
  10519. if (pi->jobid == jobnum) {
  10520. return pi;
  10521. }
  10522. }
  10523. bb_error_msg("%u: no such job", jobnum);
  10524. return NULL;
  10525. }
  10526. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10527. {
  10528. struct pipe *job;
  10529. const char *status_string;
  10530. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10531. for (job = G.job_list; job; job = job->next) {
  10532. if (job->alive_cmds == job->stopped_cmds)
  10533. status_string = "Stopped";
  10534. else
  10535. status_string = "Running";
  10536. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10537. }
  10538. clean_up_last_dead_job();
  10539. return EXIT_SUCCESS;
  10540. }
  10541. /* built-in 'fg' and 'bg' handler */
  10542. static int FAST_FUNC builtin_fg_bg(char **argv)
  10543. {
  10544. int i;
  10545. struct pipe *pi;
  10546. if (!G_interactive_fd)
  10547. return EXIT_FAILURE;
  10548. /* If they gave us no args, assume they want the last backgrounded task */
  10549. if (!argv[1]) {
  10550. for (pi = G.job_list; pi; pi = pi->next) {
  10551. if (pi->jobid == G.last_jobid) {
  10552. goto found;
  10553. }
  10554. }
  10555. bb_error_msg("%s: no current job", argv[0]);
  10556. return EXIT_FAILURE;
  10557. }
  10558. pi = parse_jobspec(argv[1]);
  10559. if (!pi)
  10560. return EXIT_FAILURE;
  10561. found:
  10562. /* TODO: bash prints a string representation
  10563. * of job being foregrounded (like "sleep 1 | cat") */
  10564. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10565. /* Put the job into the foreground. */
  10566. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10567. }
  10568. /* Restart the processes in the job */
  10569. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10570. for (i = 0; i < pi->num_cmds; i++) {
  10571. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10572. }
  10573. pi->stopped_cmds = 0;
  10574. i = kill(- pi->pgrp, SIGCONT);
  10575. if (i < 0) {
  10576. if (errno == ESRCH) {
  10577. delete_finished_job(pi);
  10578. return EXIT_SUCCESS;
  10579. }
  10580. bb_perror_msg("kill (SIGCONT)");
  10581. }
  10582. if (argv[0][0] == 'f') {
  10583. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10584. return checkjobs_and_fg_shell(pi);
  10585. }
  10586. return EXIT_SUCCESS;
  10587. }
  10588. #endif
  10589. #if ENABLE_HUSH_KILL
  10590. static int FAST_FUNC builtin_kill(char **argv)
  10591. {
  10592. int ret = 0;
  10593. # if ENABLE_HUSH_JOB
  10594. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10595. int i = 1;
  10596. do {
  10597. struct pipe *pi;
  10598. char *dst;
  10599. int j, n;
  10600. if (argv[i][0] != '%')
  10601. continue;
  10602. /*
  10603. * "kill %N" - job kill
  10604. * Converting to pgrp / pid kill
  10605. */
  10606. pi = parse_jobspec(argv[i]);
  10607. if (!pi) {
  10608. /* Eat bad jobspec */
  10609. j = i;
  10610. do {
  10611. j++;
  10612. argv[j - 1] = argv[j];
  10613. } while (argv[j]);
  10614. ret = 1;
  10615. i--;
  10616. continue;
  10617. }
  10618. /*
  10619. * In jobs started under job control, we signal
  10620. * entire process group by kill -PGRP_ID.
  10621. * This happens, f.e., in interactive shell.
  10622. *
  10623. * Otherwise, we signal each child via
  10624. * kill PID1 PID2 PID3.
  10625. * Testcases:
  10626. * sh -c 'sleep 1|sleep 1 & kill %1'
  10627. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10628. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10629. */
  10630. n = G_interactive_fd ? 1 : pi->num_cmds;
  10631. dst = alloca(n * sizeof(int)*4);
  10632. argv[i] = dst;
  10633. if (G_interactive_fd)
  10634. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10635. else for (j = 0; j < n; j++) {
  10636. struct command *cmd = &pi->cmds[j];
  10637. /* Skip exited members of the job */
  10638. if (cmd->pid == 0)
  10639. continue;
  10640. /*
  10641. * kill_main has matching code to expect
  10642. * leading space. Needed to not confuse
  10643. * negative pids with "kill -SIGNAL_NO" syntax
  10644. */
  10645. dst += sprintf(dst, " %u", (int)cmd->pid);
  10646. }
  10647. *dst = '\0';
  10648. } while (argv[++i]);
  10649. }
  10650. # endif
  10651. if (argv[1] || ret == 0) {
  10652. ret = run_applet_main(argv, kill_main);
  10653. }
  10654. /* else: ret = 1, "kill %bad_jobspec" case */
  10655. return ret;
  10656. }
  10657. #endif
  10658. #if ENABLE_HUSH_WAIT
  10659. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10660. #if !ENABLE_HUSH_JOB
  10661. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10662. #endif
  10663. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10664. {
  10665. int ret = 0;
  10666. for (;;) {
  10667. int sig;
  10668. sigset_t oldset;
  10669. if (!sigisemptyset(&G.pending_set))
  10670. goto check_sig;
  10671. /* waitpid is not interruptible by SA_RESTARTed
  10672. * signals which we use. Thus, this ugly dance:
  10673. */
  10674. /* Make sure possible SIGCHLD is stored in kernel's
  10675. * pending signal mask before we call waitpid.
  10676. * Or else we may race with SIGCHLD, lose it,
  10677. * and get stuck in sigsuspend...
  10678. */
  10679. sigfillset(&oldset); /* block all signals, remember old set */
  10680. sigprocmask2(SIG_SETMASK, &oldset);
  10681. if (!sigisemptyset(&G.pending_set)) {
  10682. /* Crap! we raced with some signal! */
  10683. goto restore;
  10684. }
  10685. /*errno = 0; - checkjobs does this */
  10686. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10687. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10688. debug_printf_exec("checkjobs:%d\n", ret);
  10689. #if ENABLE_HUSH_JOB
  10690. if (waitfor_pipe) {
  10691. int rcode = job_exited_or_stopped(waitfor_pipe);
  10692. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10693. if (rcode >= 0) {
  10694. ret = rcode;
  10695. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10696. break;
  10697. }
  10698. }
  10699. #endif
  10700. /* if ECHILD, there are no children (ret is -1 or 0) */
  10701. /* if ret == 0, no children changed state */
  10702. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10703. if (errno == ECHILD || ret) {
  10704. ret--;
  10705. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10706. ret = 0;
  10707. #if ENABLE_HUSH_BASH_COMPAT
  10708. if (waitfor_pid == -1 && errno == ECHILD) {
  10709. /* exitcode of "wait -n" with no children is 127, not 0 */
  10710. ret = 127;
  10711. }
  10712. #endif
  10713. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10714. break;
  10715. }
  10716. /* Wait for SIGCHLD or any other signal */
  10717. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10718. /* Note: sigsuspend invokes signal handler */
  10719. sigsuspend(&oldset);
  10720. restore:
  10721. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10722. check_sig:
  10723. /* So, did we get a signal? */
  10724. sig = check_and_run_traps();
  10725. if (sig /*&& sig != SIGCHLD - always true */) {
  10726. /* Do this for any (non-ignored) signal, not only for ^C */
  10727. ret = 128 + sig;
  10728. break;
  10729. }
  10730. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10731. }
  10732. return ret;
  10733. }
  10734. static int FAST_FUNC builtin_wait(char **argv)
  10735. {
  10736. int ret;
  10737. int status;
  10738. argv = skip_dash_dash(argv);
  10739. #if ENABLE_HUSH_BASH_COMPAT
  10740. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10741. /* wait -n */
  10742. /* (bash accepts "wait -n PID" too and ignores PID) */
  10743. G.dead_job_exitcode = -1;
  10744. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10745. }
  10746. #endif
  10747. if (argv[0] == NULL) {
  10748. /* Don't care about wait results */
  10749. /* Note 1: must wait until there are no more children */
  10750. /* Note 2: must be interruptible */
  10751. /* Examples:
  10752. * $ sleep 3 & sleep 6 & wait
  10753. * [1] 30934 sleep 3
  10754. * [2] 30935 sleep 6
  10755. * [1] Done sleep 3
  10756. * [2] Done sleep 6
  10757. * $ sleep 3 & sleep 6 & wait
  10758. * [1] 30936 sleep 3
  10759. * [2] 30937 sleep 6
  10760. * [1] Done sleep 3
  10761. * ^C <-- after ~4 sec from keyboard
  10762. * $
  10763. */
  10764. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10765. }
  10766. do {
  10767. pid_t pid = bb_strtou(*argv, NULL, 10);
  10768. if (errno || pid <= 0) {
  10769. #if ENABLE_HUSH_JOB
  10770. if (argv[0][0] == '%') {
  10771. struct pipe *wait_pipe;
  10772. ret = 127; /* bash compat for bad jobspecs */
  10773. wait_pipe = parse_jobspec(*argv);
  10774. if (wait_pipe) {
  10775. ret = job_exited_or_stopped(wait_pipe);
  10776. if (ret < 0) {
  10777. ret = wait_for_child_or_signal(wait_pipe, 0);
  10778. } else {
  10779. /* waiting on "last dead job" removes it */
  10780. clean_up_last_dead_job();
  10781. }
  10782. }
  10783. /* else: parse_jobspec() already emitted error msg */
  10784. continue;
  10785. }
  10786. #endif
  10787. /* mimic bash message */
  10788. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10789. ret = EXIT_FAILURE;
  10790. continue; /* bash checks all argv[] */
  10791. }
  10792. /* Do we have such child? */
  10793. ret = waitpid(pid, &status, WNOHANG);
  10794. if (ret < 0) {
  10795. /* No */
  10796. ret = 127;
  10797. if (errno == ECHILD) {
  10798. if (pid == G.last_bg_pid) {
  10799. /* "wait $!" but last bg task has already exited. Try:
  10800. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10801. * In bash it prints exitcode 0, then 3.
  10802. * In dash, it is 127.
  10803. */
  10804. ret = G.last_bg_pid_exitcode;
  10805. } else {
  10806. /* Example: "wait 1". mimic bash message */
  10807. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10808. }
  10809. } else {
  10810. /* ??? */
  10811. bb_perror_msg("wait %s", *argv);
  10812. }
  10813. continue; /* bash checks all argv[] */
  10814. }
  10815. if (ret == 0) {
  10816. /* Yes, and it still runs */
  10817. ret = wait_for_child_or_signal(NULL, pid);
  10818. } else {
  10819. /* Yes, and it just exited */
  10820. process_wait_result(NULL, pid, status);
  10821. ret = WEXITSTATUS(status);
  10822. if (WIFSIGNALED(status))
  10823. ret = 128 + WTERMSIG(status);
  10824. }
  10825. } while (*++argv);
  10826. return ret;
  10827. }
  10828. #endif
  10829. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10830. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10831. {
  10832. if (argv[1]) {
  10833. def = bb_strtou(argv[1], NULL, 10);
  10834. if (errno || def < def_min || argv[2]) {
  10835. bb_error_msg("%s: bad arguments", argv[0]);
  10836. def = UINT_MAX;
  10837. }
  10838. }
  10839. return def;
  10840. }
  10841. #endif
  10842. #if ENABLE_HUSH_LOOPS
  10843. static int FAST_FUNC builtin_break(char **argv)
  10844. {
  10845. unsigned depth;
  10846. if (G.depth_of_loop == 0) {
  10847. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10848. /* if we came from builtin_continue(), need to undo "= 1" */
  10849. G.flag_break_continue = 0;
  10850. return EXIT_SUCCESS; /* bash compat */
  10851. }
  10852. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10853. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10854. if (depth == UINT_MAX)
  10855. G.flag_break_continue = BC_BREAK;
  10856. if (G.depth_of_loop < depth)
  10857. G.depth_break_continue = G.depth_of_loop;
  10858. return EXIT_SUCCESS;
  10859. }
  10860. static int FAST_FUNC builtin_continue(char **argv)
  10861. {
  10862. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10863. return builtin_break(argv);
  10864. }
  10865. #endif
  10866. #if ENABLE_HUSH_FUNCTIONS
  10867. static int FAST_FUNC builtin_return(char **argv)
  10868. {
  10869. int rc;
  10870. if (G_flag_return_in_progress != -1) {
  10871. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10872. return EXIT_FAILURE; /* bash compat */
  10873. }
  10874. G_flag_return_in_progress = 1;
  10875. /* bash:
  10876. * out of range: wraps around at 256, does not error out
  10877. * non-numeric param:
  10878. * f() { false; return qwe; }; f; echo $?
  10879. * bash: return: qwe: numeric argument required <== we do this
  10880. * 255 <== we also do this
  10881. */
  10882. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10883. return rc;
  10884. }
  10885. #endif
  10886. #if ENABLE_HUSH_TIMES
  10887. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10888. {
  10889. static const uint8_t times_tbl[] ALIGN1 = {
  10890. ' ', offsetof(struct tms, tms_utime),
  10891. '\n', offsetof(struct tms, tms_stime),
  10892. ' ', offsetof(struct tms, tms_cutime),
  10893. '\n', offsetof(struct tms, tms_cstime),
  10894. 0
  10895. };
  10896. const uint8_t *p;
  10897. unsigned clk_tck;
  10898. struct tms buf;
  10899. clk_tck = bb_clk_tck();
  10900. times(&buf);
  10901. p = times_tbl;
  10902. do {
  10903. unsigned sec, frac;
  10904. unsigned long t;
  10905. t = *(clock_t *)(((char *) &buf) + p[1]);
  10906. sec = t / clk_tck;
  10907. frac = t % clk_tck;
  10908. printf("%um%u.%03us%c",
  10909. sec / 60, sec % 60,
  10910. (frac * 1000) / clk_tck,
  10911. p[0]);
  10912. p += 2;
  10913. } while (*p);
  10914. return EXIT_SUCCESS;
  10915. }
  10916. #endif
  10917. #if ENABLE_HUSH_MEMLEAK
  10918. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10919. {
  10920. void *p;
  10921. unsigned long l;
  10922. # ifdef M_TRIM_THRESHOLD
  10923. /* Optional. Reduces probability of false positives */
  10924. malloc_trim(0);
  10925. # endif
  10926. /* Crude attempt to find where "free memory" starts,
  10927. * sans fragmentation. */
  10928. p = malloc(240);
  10929. l = (unsigned long)p;
  10930. free(p);
  10931. p = malloc(3400);
  10932. if (l < (unsigned long)p) l = (unsigned long)p;
  10933. free(p);
  10934. # if 0 /* debug */
  10935. {
  10936. struct mallinfo mi = mallinfo();
  10937. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10938. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10939. }
  10940. # endif
  10941. if (!G.memleak_value)
  10942. G.memleak_value = l;
  10943. l -= G.memleak_value;
  10944. if ((long)l < 0)
  10945. l = 0;
  10946. l /= 1024;
  10947. if (l > 127)
  10948. l = 127;
  10949. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10950. return l;
  10951. }
  10952. #endif