3
0

hush.c 249 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179
  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. * special variables (done: PWD, PPID, RANDOM)
  45. * tilde expansion
  46. * aliases
  47. * follow IFS rules more precisely, including update semantics
  48. * builtins mandated by standards we don't support:
  49. * [un]alias, command, fc, getopts, newgrp, readonly, times
  50. * make complex ${var%...} constructs support optional
  51. * make here documents optional
  52. *
  53. * Bash compat TODO:
  54. * redirection of stdout+stderr: &> and >&
  55. * reserved words: function select
  56. * advanced test: [[ ]]
  57. * process substitution: <(list) and >(list)
  58. * =~: regex operator
  59. * let EXPR [EXPR...]
  60. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  61. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  62. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  63. * ((EXPR))
  64. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  65. * This is exactly equivalent to let "EXPR".
  66. * $[EXPR]: synonym for $((EXPR))
  67. *
  68. * Won't do:
  69. * In bash, export builtin is special, its arguments are assignments
  70. * and therefore expansion of them should be "one-word" expansion:
  71. * $ export i=`echo 'a b'` # export has one arg: "i=a b"
  72. * compare with:
  73. * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
  74. * ls: cannot access i=a: No such file or directory
  75. * ls: cannot access b: No such file or directory
  76. * Note1: same applies to local builtin.
  77. * Note2: bash 3.2.33(1) does this only if export word itself
  78. * is not quoted:
  79. * $ export i=`echo 'aaa bbb'`; echo "$i"
  80. * aaa bbb
  81. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  82. * aaa
  83. */
  84. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  85. || defined(__APPLE__) \
  86. )
  87. # include <malloc.h> /* for malloc_trim */
  88. #endif
  89. #include <glob.h>
  90. /* #include <dmalloc.h> */
  91. #if ENABLE_HUSH_CASE
  92. # include <fnmatch.h>
  93. #endif
  94. #include <sys/utsname.h> /* for setting $HOSTNAME */
  95. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  96. #include "unicode.h"
  97. #include "shell_common.h"
  98. #include "math.h"
  99. #include "match.h"
  100. #if ENABLE_HUSH_RANDOM_SUPPORT
  101. # include "random.h"
  102. #else
  103. # define CLEAR_RANDOM_T(rnd) ((void)0)
  104. #endif
  105. #ifndef PIPE_BUF
  106. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  107. #endif
  108. //config:config HUSH
  109. //config: bool "hush"
  110. //config: default y
  111. //config: help
  112. //config: hush is a small shell (25k). It handles the normal flow control
  113. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  114. //config: case/esac. Redirections, here documents, $((arithmetic))
  115. //config: and functions are supported.
  116. //config:
  117. //config: It will compile and work on no-mmu systems.
  118. //config:
  119. //config: It does not handle select, aliases, tilde expansion,
  120. //config: &>file and >&file redirection of stdout+stderr.
  121. //config:
  122. //config:config HUSH_BASH_COMPAT
  123. //config: bool "bash-compatible extensions"
  124. //config: default y
  125. //config: depends on HUSH
  126. //config: help
  127. //config: Enable bash-compatible extensions.
  128. //config:
  129. //config:config HUSH_BRACE_EXPANSION
  130. //config: bool "Brace expansion"
  131. //config: default y
  132. //config: depends on HUSH_BASH_COMPAT
  133. //config: help
  134. //config: Enable {abc,def} extension.
  135. //config:
  136. //config:config HUSH_HELP
  137. //config: bool "help builtin"
  138. //config: default y
  139. //config: depends on HUSH
  140. //config: help
  141. //config: Enable help builtin in hush. Code size + ~1 kbyte.
  142. //config:
  143. //config:config HUSH_INTERACTIVE
  144. //config: bool "Interactive mode"
  145. //config: default y
  146. //config: depends on HUSH
  147. //config: help
  148. //config: Enable interactive mode (prompt and command editing).
  149. //config: Without this, hush simply reads and executes commands
  150. //config: from stdin just like a shell script from a file.
  151. //config: No prompt, no PS1/PS2 magic shell variables.
  152. //config:
  153. //config:config HUSH_SAVEHISTORY
  154. //config: bool "Save command history to .hush_history"
  155. //config: default y
  156. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  157. //config: help
  158. //config: Enable history saving in hush.
  159. //config:
  160. //config:config HUSH_JOB
  161. //config: bool "Job control"
  162. //config: default y
  163. //config: depends on HUSH_INTERACTIVE
  164. //config: help
  165. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  166. //config: command (not entire shell), fg/bg builtins work. Without this option,
  167. //config: "cmd &" still works by simply spawning a process and immediately
  168. //config: prompting for next command (or executing next command in a script),
  169. //config: but no separate process group is formed.
  170. //config:
  171. //config:config HUSH_TICK
  172. //config: bool "Process substitution"
  173. //config: default y
  174. //config: depends on HUSH
  175. //config: help
  176. //config: Enable process substitution `command` and $(command) in hush.
  177. //config:
  178. //config:config HUSH_IF
  179. //config: bool "Support if/then/elif/else/fi"
  180. //config: default y
  181. //config: depends on HUSH
  182. //config: help
  183. //config: Enable if/then/elif/else/fi in hush.
  184. //config:
  185. //config:config HUSH_LOOPS
  186. //config: bool "Support for, while and until loops"
  187. //config: default y
  188. //config: depends on HUSH
  189. //config: help
  190. //config: Enable for, while and until loops in hush.
  191. //config:
  192. //config:config HUSH_CASE
  193. //config: bool "Support case ... esac statement"
  194. //config: default y
  195. //config: depends on HUSH
  196. //config: help
  197. //config: Enable case ... esac statement in hush. +400 bytes.
  198. //config:
  199. //config:config HUSH_FUNCTIONS
  200. //config: bool "Support funcname() { commands; } syntax"
  201. //config: default y
  202. //config: depends on HUSH
  203. //config: help
  204. //config: Enable support for shell functions in hush. +800 bytes.
  205. //config:
  206. //config:config HUSH_LOCAL
  207. //config: bool "Support local builtin"
  208. //config: default y
  209. //config: depends on HUSH_FUNCTIONS
  210. //config: help
  211. //config: Enable support for local variables in functions.
  212. //config:
  213. //config:config HUSH_RANDOM_SUPPORT
  214. //config: bool "Pseudorandom generator and $RANDOM variable"
  215. //config: default y
  216. //config: depends on HUSH
  217. //config: help
  218. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  219. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  220. //config:
  221. //config:config HUSH_EXPORT_N
  222. //config: bool "Support 'export -n' option"
  223. //config: default y
  224. //config: depends on HUSH
  225. //config: help
  226. //config: export -n unexports variables. It is a bash extension.
  227. //config:
  228. //config:config HUSH_MODE_X
  229. //config: bool "Support 'hush -x' option and 'set -x' command"
  230. //config: default y
  231. //config: depends on HUSH
  232. //config: help
  233. //config: This instructs hush to print commands before execution.
  234. //config: Adds ~300 bytes.
  235. //config:
  236. //config:config MSH
  237. //config: bool "msh (deprecated: aliased to hush)"
  238. //config: default n
  239. //config: select HUSH
  240. //config: help
  241. //config: msh is deprecated and will be removed, please migrate to hush.
  242. //config:
  243. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  244. //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
  245. //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
  246. //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
  247. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  248. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  249. /* -i (interactive) and -s (read stdin) are also accepted,
  250. * but currently do nothing, therefore aren't shown in help.
  251. * NOMMU-specific options are not meant to be used by users,
  252. * therefore we don't show them either.
  253. */
  254. //usage:#define hush_trivial_usage
  255. //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  256. //usage:#define hush_full_usage "\n\n"
  257. //usage: "Unix shell interpreter"
  258. //usage:#define msh_trivial_usage hush_trivial_usage
  259. //usage:#define msh_full_usage hush_full_usage
  260. //usage:#if ENABLE_FEATURE_SH_IS_HUSH
  261. //usage:# define sh_trivial_usage hush_trivial_usage
  262. //usage:# define sh_full_usage hush_full_usage
  263. //usage:#endif
  264. //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
  265. //usage:# define bash_trivial_usage hush_trivial_usage
  266. //usage:# define bash_full_usage hush_full_usage
  267. //usage:#endif
  268. /* Build knobs */
  269. #define LEAK_HUNTING 0
  270. #define BUILD_AS_NOMMU 0
  271. /* Enable/disable sanity checks. Ok to enable in production,
  272. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  273. * Keeping 1 for now even in released versions.
  274. */
  275. #define HUSH_DEBUG 1
  276. /* Slightly bigger (+200 bytes), but faster hush.
  277. * So far it only enables a trick with counting SIGCHLDs and forks,
  278. * which allows us to do fewer waitpid's.
  279. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  280. * and therefore waitpid will return the same result as last time)
  281. */
  282. #define ENABLE_HUSH_FAST 0
  283. /* TODO: implement simplified code for users which do not need ${var%...} ops
  284. * So far ${var%...} ops are always enabled:
  285. */
  286. #define ENABLE_HUSH_DOLLAR_OPS 1
  287. #if BUILD_AS_NOMMU
  288. # undef BB_MMU
  289. # undef USE_FOR_NOMMU
  290. # undef USE_FOR_MMU
  291. # define BB_MMU 0
  292. # define USE_FOR_NOMMU(...) __VA_ARGS__
  293. # define USE_FOR_MMU(...)
  294. #endif
  295. #include "NUM_APPLETS.h"
  296. #if NUM_APPLETS == 1
  297. /* STANDALONE does not make sense, and won't compile */
  298. # undef CONFIG_FEATURE_SH_STANDALONE
  299. # undef ENABLE_FEATURE_SH_STANDALONE
  300. # undef IF_FEATURE_SH_STANDALONE
  301. # undef IF_NOT_FEATURE_SH_STANDALONE
  302. # define ENABLE_FEATURE_SH_STANDALONE 0
  303. # define IF_FEATURE_SH_STANDALONE(...)
  304. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  305. #endif
  306. #if !ENABLE_HUSH_INTERACTIVE
  307. # undef ENABLE_FEATURE_EDITING
  308. # define ENABLE_FEATURE_EDITING 0
  309. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  310. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  311. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  312. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  313. #endif
  314. /* Do we support ANY keywords? */
  315. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  316. # define HAS_KEYWORDS 1
  317. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  318. # define IF_HAS_NO_KEYWORDS(...)
  319. #else
  320. # define HAS_KEYWORDS 0
  321. # define IF_HAS_KEYWORDS(...)
  322. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  323. #endif
  324. /* If you comment out one of these below, it will be #defined later
  325. * to perform debug printfs to stderr: */
  326. #define debug_printf(...) do {} while (0)
  327. /* Finer-grained debug switches */
  328. #define debug_printf_parse(...) do {} while (0)
  329. #define debug_print_tree(a, b) do {} while (0)
  330. #define debug_printf_exec(...) do {} while (0)
  331. #define debug_printf_env(...) do {} while (0)
  332. #define debug_printf_jobs(...) do {} while (0)
  333. #define debug_printf_expand(...) do {} while (0)
  334. #define debug_printf_varexp(...) do {} while (0)
  335. #define debug_printf_glob(...) do {} while (0)
  336. #define debug_printf_list(...) do {} while (0)
  337. #define debug_printf_subst(...) do {} while (0)
  338. #define debug_printf_clean(...) do {} while (0)
  339. #define ERR_PTR ((void*)(long)1)
  340. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  341. #define _SPECIAL_VARS_STR "_*@$!?#"
  342. #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
  343. #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
  344. #if ENABLE_HUSH_BASH_COMPAT
  345. /* Support / and // replace ops */
  346. /* Note that // is stored as \ in "encoded" string representation */
  347. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  348. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  349. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  350. #else
  351. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  352. # define VAR_SUBST_OPS "%#:-=+?"
  353. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  354. #endif
  355. #define SPECIAL_VAR_SYMBOL 3
  356. struct variable;
  357. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  358. /* This supports saving pointers malloced in vfork child,
  359. * to be freed in the parent.
  360. */
  361. #if !BB_MMU
  362. typedef struct nommu_save_t {
  363. char **new_env;
  364. struct variable *old_vars;
  365. char **argv;
  366. char **argv_from_re_execing;
  367. } nommu_save_t;
  368. #endif
  369. enum {
  370. RES_NONE = 0,
  371. #if ENABLE_HUSH_IF
  372. RES_IF ,
  373. RES_THEN ,
  374. RES_ELIF ,
  375. RES_ELSE ,
  376. RES_FI ,
  377. #endif
  378. #if ENABLE_HUSH_LOOPS
  379. RES_FOR ,
  380. RES_WHILE ,
  381. RES_UNTIL ,
  382. RES_DO ,
  383. RES_DONE ,
  384. #endif
  385. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  386. RES_IN ,
  387. #endif
  388. #if ENABLE_HUSH_CASE
  389. RES_CASE ,
  390. /* three pseudo-keywords support contrived "case" syntax: */
  391. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  392. RES_MATCH , /* "word)" */
  393. RES_CASE_BODY, /* "this command is inside CASE" */
  394. RES_ESAC ,
  395. #endif
  396. RES_XXXX ,
  397. RES_SNTX
  398. };
  399. typedef struct o_string {
  400. char *data;
  401. int length; /* position where data is appended */
  402. int maxlen;
  403. int o_expflags;
  404. /* At least some part of the string was inside '' or "",
  405. * possibly empty one: word"", wo''rd etc. */
  406. smallint has_quoted_part;
  407. smallint has_empty_slot;
  408. smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
  409. } o_string;
  410. enum {
  411. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  412. EXP_FLAG_GLOB = 0x2,
  413. /* Protect newly added chars against globbing
  414. * by prepending \ to *, ?, [, \ */
  415. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  416. };
  417. enum {
  418. MAYBE_ASSIGNMENT = 0,
  419. DEFINITELY_ASSIGNMENT = 1,
  420. NOT_ASSIGNMENT = 2,
  421. /* Not an assigment, but next word may be: "if v=xyz cmd;" */
  422. WORD_IS_KEYWORD = 3,
  423. };
  424. /* Used for initialization: o_string foo = NULL_O_STRING; */
  425. #define NULL_O_STRING { NULL }
  426. #ifndef debug_printf_parse
  427. static const char *const assignment_flag[] = {
  428. "MAYBE_ASSIGNMENT",
  429. "DEFINITELY_ASSIGNMENT",
  430. "NOT_ASSIGNMENT",
  431. "WORD_IS_KEYWORD",
  432. };
  433. #endif
  434. typedef struct in_str {
  435. const char *p;
  436. /* eof_flag=1: last char in ->p is really an EOF */
  437. char eof_flag; /* meaningless if ->p == NULL */
  438. char peek_buf[2];
  439. #if ENABLE_HUSH_INTERACTIVE
  440. smallint promptmode; /* 0: PS1, 1: PS2 */
  441. #endif
  442. int last_char;
  443. FILE *file;
  444. int (*get) (struct in_str *) FAST_FUNC;
  445. int (*peek) (struct in_str *) FAST_FUNC;
  446. } in_str;
  447. #define i_getch(input) ((input)->get(input))
  448. #define i_peek(input) ((input)->peek(input))
  449. /* The descrip member of this structure is only used to make
  450. * debugging output pretty */
  451. static const struct {
  452. int mode;
  453. signed char default_fd;
  454. char descrip[3];
  455. } redir_table[] = {
  456. { O_RDONLY, 0, "<" },
  457. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  458. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  459. { O_CREAT|O_RDWR, 1, "<>" },
  460. { O_RDONLY, 0, "<<" },
  461. /* Should not be needed. Bogus default_fd helps in debugging */
  462. /* { O_RDONLY, 77, "<<" }, */
  463. };
  464. struct redir_struct {
  465. struct redir_struct *next;
  466. char *rd_filename; /* filename */
  467. int rd_fd; /* fd to redirect */
  468. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  469. int rd_dup;
  470. smallint rd_type; /* (enum redir_type) */
  471. /* note: for heredocs, rd_filename contains heredoc delimiter,
  472. * and subsequently heredoc itself; and rd_dup is a bitmask:
  473. * bit 0: do we need to trim leading tabs?
  474. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  475. */
  476. };
  477. typedef enum redir_type {
  478. REDIRECT_INPUT = 0,
  479. REDIRECT_OVERWRITE = 1,
  480. REDIRECT_APPEND = 2,
  481. REDIRECT_IO = 3,
  482. REDIRECT_HEREDOC = 4,
  483. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  484. REDIRFD_CLOSE = -3,
  485. REDIRFD_SYNTAX_ERR = -2,
  486. REDIRFD_TO_FILE = -1,
  487. /* otherwise, rd_fd is redirected to rd_dup */
  488. HEREDOC_SKIPTABS = 1,
  489. HEREDOC_QUOTED = 2,
  490. } redir_type;
  491. struct command {
  492. pid_t pid; /* 0 if exited */
  493. int assignment_cnt; /* how many argv[i] are assignments? */
  494. smallint cmd_type; /* CMD_xxx */
  495. #define CMD_NORMAL 0
  496. #define CMD_SUBSHELL 1
  497. #if ENABLE_HUSH_BASH_COMPAT
  498. /* used for "[[ EXPR ]]" */
  499. # define CMD_SINGLEWORD_NOGLOB 2
  500. #endif
  501. #if ENABLE_HUSH_FUNCTIONS
  502. # define CMD_FUNCDEF 3
  503. #endif
  504. smalluint cmd_exitcode;
  505. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  506. struct pipe *group;
  507. #if !BB_MMU
  508. char *group_as_string;
  509. #endif
  510. #if ENABLE_HUSH_FUNCTIONS
  511. struct function *child_func;
  512. /* This field is used to prevent a bug here:
  513. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  514. * When we execute "f1() {a;}" cmd, we create new function and clear
  515. * cmd->group, cmd->group_as_string, cmd->argv[0].
  516. * When we execute "f1() {b;}", we notice that f1 exists,
  517. * and that its "parent cmd" struct is still "alive",
  518. * we put those fields back into cmd->xxx
  519. * (struct function has ->parent_cmd ptr to facilitate that).
  520. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  521. * Without this trick, loop would execute a;b;b;b;...
  522. * instead of correct sequence a;b;a;b;...
  523. * When command is freed, it severs the link
  524. * (sets ->child_func->parent_cmd to NULL).
  525. */
  526. #endif
  527. char **argv; /* command name and arguments */
  528. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  529. * and on execution these are substituted with their values.
  530. * Substitution can make _several_ words out of one argv[n]!
  531. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  532. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  533. */
  534. struct redir_struct *redirects; /* I/O redirections */
  535. };
  536. /* Is there anything in this command at all? */
  537. #define IS_NULL_CMD(cmd) \
  538. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  539. struct pipe {
  540. struct pipe *next;
  541. int num_cmds; /* total number of commands in pipe */
  542. int alive_cmds; /* number of commands running (not exited) */
  543. int stopped_cmds; /* number of commands alive, but stopped */
  544. #if ENABLE_HUSH_JOB
  545. int jobid; /* job number */
  546. pid_t pgrp; /* process group ID for the job */
  547. char *cmdtext; /* name of job */
  548. #endif
  549. struct command *cmds; /* array of commands in pipe */
  550. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  551. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  552. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  553. };
  554. typedef enum pipe_style {
  555. PIPE_SEQ = 1,
  556. PIPE_AND = 2,
  557. PIPE_OR = 3,
  558. PIPE_BG = 4,
  559. } pipe_style;
  560. /* Is there anything in this pipe at all? */
  561. #define IS_NULL_PIPE(pi) \
  562. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  563. /* This holds pointers to the various results of parsing */
  564. struct parse_context {
  565. /* linked list of pipes */
  566. struct pipe *list_head;
  567. /* last pipe (being constructed right now) */
  568. struct pipe *pipe;
  569. /* last command in pipe (being constructed right now) */
  570. struct command *command;
  571. /* last redirect in command->redirects list */
  572. struct redir_struct *pending_redirect;
  573. #if !BB_MMU
  574. o_string as_string;
  575. #endif
  576. #if HAS_KEYWORDS
  577. smallint ctx_res_w;
  578. smallint ctx_inverted; /* "! cmd | cmd" */
  579. #if ENABLE_HUSH_CASE
  580. smallint ctx_dsemicolon; /* ";;" seen */
  581. #endif
  582. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  583. int old_flag;
  584. /* group we are enclosed in:
  585. * example: "if pipe1; pipe2; then pipe3; fi"
  586. * when we see "if" or "then", we malloc and copy current context,
  587. * and make ->stack point to it. then we parse pipeN.
  588. * when closing "then" / fi" / whatever is found,
  589. * we move list_head into ->stack->command->group,
  590. * copy ->stack into current context, and delete ->stack.
  591. * (parsing of { list } and ( list ) doesn't use this method)
  592. */
  593. struct parse_context *stack;
  594. #endif
  595. };
  596. /* On program start, environ points to initial environment.
  597. * putenv adds new pointers into it, unsetenv removes them.
  598. * Neither of these (de)allocates the strings.
  599. * setenv allocates new strings in malloc space and does putenv,
  600. * and thus setenv is unusable (leaky) for shell's purposes */
  601. #define setenv(...) setenv_is_leaky_dont_use()
  602. struct variable {
  603. struct variable *next;
  604. char *varstr; /* points to "name=" portion */
  605. #if ENABLE_HUSH_LOCAL
  606. unsigned func_nest_level;
  607. #endif
  608. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  609. smallint flg_export; /* putenv should be done on this var */
  610. smallint flg_read_only;
  611. };
  612. enum {
  613. BC_BREAK = 1,
  614. BC_CONTINUE = 2,
  615. };
  616. #if ENABLE_HUSH_FUNCTIONS
  617. struct function {
  618. struct function *next;
  619. char *name;
  620. struct command *parent_cmd;
  621. struct pipe *body;
  622. # if !BB_MMU
  623. char *body_as_string;
  624. # endif
  625. };
  626. #endif
  627. /* set -/+o OPT support. (TODO: make it optional)
  628. * bash supports the following opts:
  629. * allexport off
  630. * braceexpand on
  631. * emacs on
  632. * errexit off
  633. * errtrace off
  634. * functrace off
  635. * hashall on
  636. * histexpand off
  637. * history on
  638. * ignoreeof off
  639. * interactive-comments on
  640. * keyword off
  641. * monitor on
  642. * noclobber off
  643. * noexec off
  644. * noglob off
  645. * nolog off
  646. * notify off
  647. * nounset off
  648. * onecmd off
  649. * physical off
  650. * pipefail off
  651. * posix off
  652. * privileged off
  653. * verbose off
  654. * vi off
  655. * xtrace off
  656. */
  657. static const char o_opt_strings[] ALIGN1 =
  658. "pipefail\0"
  659. "noexec\0"
  660. #if ENABLE_HUSH_MODE_X
  661. "xtrace\0"
  662. #endif
  663. ;
  664. enum {
  665. OPT_O_PIPEFAIL,
  666. OPT_O_NOEXEC,
  667. #if ENABLE_HUSH_MODE_X
  668. OPT_O_XTRACE,
  669. #endif
  670. NUM_OPT_O
  671. };
  672. /* "Globals" within this file */
  673. /* Sorted roughly by size (smaller offsets == smaller code) */
  674. struct globals {
  675. /* interactive_fd != 0 means we are an interactive shell.
  676. * If we are, then saved_tty_pgrp can also be != 0, meaning
  677. * that controlling tty is available. With saved_tty_pgrp == 0,
  678. * job control still works, but terminal signals
  679. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  680. * process groups can only be created with "cmd &".
  681. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  682. * to give tty to the foreground process group,
  683. * and will take it back when the group is stopped (^Z)
  684. * or killed (^C).
  685. */
  686. #if ENABLE_HUSH_INTERACTIVE
  687. /* 'interactive_fd' is a fd# open to ctty, if we have one
  688. * _AND_ if we decided to act interactively */
  689. int interactive_fd;
  690. const char *PS1;
  691. const char *PS2;
  692. # define G_interactive_fd (G.interactive_fd)
  693. #else
  694. # define G_interactive_fd 0
  695. #endif
  696. #if ENABLE_FEATURE_EDITING
  697. line_input_t *line_input_state;
  698. #endif
  699. pid_t root_pid;
  700. pid_t root_ppid;
  701. pid_t last_bg_pid;
  702. #if ENABLE_HUSH_RANDOM_SUPPORT
  703. random_t random_gen;
  704. #endif
  705. #if ENABLE_HUSH_JOB
  706. int run_list_level;
  707. int last_jobid;
  708. pid_t saved_tty_pgrp;
  709. struct pipe *job_list;
  710. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  711. #else
  712. # define G_saved_tty_pgrp 0
  713. #endif
  714. char o_opt[NUM_OPT_O];
  715. #if ENABLE_HUSH_MODE_X
  716. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  717. #else
  718. # define G_x_mode 0
  719. #endif
  720. smallint flag_SIGINT;
  721. #if ENABLE_HUSH_LOOPS
  722. smallint flag_break_continue;
  723. #endif
  724. #if ENABLE_HUSH_FUNCTIONS
  725. /* 0: outside of a function (or sourced file)
  726. * -1: inside of a function, ok to use return builtin
  727. * 1: return is invoked, skip all till end of func
  728. */
  729. smallint flag_return_in_progress;
  730. #endif
  731. smallint exiting; /* used to prevent EXIT trap recursion */
  732. /* These four support $?, $#, and $1 */
  733. smalluint last_exitcode;
  734. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  735. smalluint global_args_malloced;
  736. /* how many non-NULL argv's we have. NB: $# + 1 */
  737. int global_argc;
  738. char **global_argv;
  739. #if !BB_MMU
  740. char *argv0_for_re_execing;
  741. #endif
  742. #if ENABLE_HUSH_LOOPS
  743. unsigned depth_break_continue;
  744. unsigned depth_of_loop;
  745. #endif
  746. const char *ifs;
  747. const char *cwd;
  748. struct variable *top_var;
  749. char **expanded_assignments;
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function *top_func;
  752. # if ENABLE_HUSH_LOCAL
  753. struct variable **shadowed_vars_pp;
  754. unsigned func_nest_level;
  755. # endif
  756. #endif
  757. /* Signal and trap handling */
  758. #if ENABLE_HUSH_FAST
  759. unsigned count_SIGCHLD;
  760. unsigned handled_SIGCHLD;
  761. smallint we_have_children;
  762. #endif
  763. /* Which signals have non-DFL handler (even with no traps set)?
  764. * Set at the start to:
  765. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  766. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  767. * The rest is cleared right before execv syscalls.
  768. * Other than these two times, never modified.
  769. */
  770. unsigned special_sig_mask;
  771. #if ENABLE_HUSH_JOB
  772. unsigned fatal_sig_mask;
  773. # define G_fatal_sig_mask G.fatal_sig_mask
  774. #else
  775. # define G_fatal_sig_mask 0
  776. #endif
  777. char **traps; /* char *traps[NSIG] */
  778. sigset_t pending_set;
  779. #if HUSH_DEBUG
  780. unsigned long memleak_value;
  781. int debug_indent;
  782. #endif
  783. struct sigaction sa;
  784. char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
  785. };
  786. #define G (*ptr_to_globals)
  787. /* Not #defining name to G.name - this quickly gets unwieldy
  788. * (too many defines). Also, I actually prefer to see when a variable
  789. * is global, thus "G." prefix is a useful hint */
  790. #define INIT_G() do { \
  791. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  792. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  793. sigfillset(&G.sa.sa_mask); \
  794. G.sa.sa_flags = SA_RESTART; \
  795. } while (0)
  796. /* Function prototypes for builtins */
  797. static int builtin_cd(char **argv) FAST_FUNC;
  798. static int builtin_echo(char **argv) FAST_FUNC;
  799. static int builtin_eval(char **argv) FAST_FUNC;
  800. static int builtin_exec(char **argv) FAST_FUNC;
  801. static int builtin_exit(char **argv) FAST_FUNC;
  802. static int builtin_export(char **argv) FAST_FUNC;
  803. #if ENABLE_HUSH_JOB
  804. static int builtin_fg_bg(char **argv) FAST_FUNC;
  805. static int builtin_jobs(char **argv) FAST_FUNC;
  806. #endif
  807. #if ENABLE_HUSH_HELP
  808. static int builtin_help(char **argv) FAST_FUNC;
  809. #endif
  810. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  811. static int builtin_history(char **argv) FAST_FUNC;
  812. #endif
  813. #if ENABLE_HUSH_LOCAL
  814. static int builtin_local(char **argv) FAST_FUNC;
  815. #endif
  816. #if HUSH_DEBUG
  817. static int builtin_memleak(char **argv) FAST_FUNC;
  818. #endif
  819. #if ENABLE_PRINTF
  820. static int builtin_printf(char **argv) FAST_FUNC;
  821. #endif
  822. static int builtin_pwd(char **argv) FAST_FUNC;
  823. static int builtin_read(char **argv) FAST_FUNC;
  824. static int builtin_set(char **argv) FAST_FUNC;
  825. static int builtin_shift(char **argv) FAST_FUNC;
  826. static int builtin_source(char **argv) FAST_FUNC;
  827. static int builtin_test(char **argv) FAST_FUNC;
  828. static int builtin_trap(char **argv) FAST_FUNC;
  829. static int builtin_type(char **argv) FAST_FUNC;
  830. static int builtin_true(char **argv) FAST_FUNC;
  831. static int builtin_umask(char **argv) FAST_FUNC;
  832. static int builtin_unset(char **argv) FAST_FUNC;
  833. static int builtin_wait(char **argv) FAST_FUNC;
  834. #if ENABLE_HUSH_LOOPS
  835. static int builtin_break(char **argv) FAST_FUNC;
  836. static int builtin_continue(char **argv) FAST_FUNC;
  837. #endif
  838. #if ENABLE_HUSH_FUNCTIONS
  839. static int builtin_return(char **argv) FAST_FUNC;
  840. #endif
  841. /* Table of built-in functions. They can be forked or not, depending on
  842. * context: within pipes, they fork. As simple commands, they do not.
  843. * When used in non-forking context, they can change global variables
  844. * in the parent shell process. If forked, of course they cannot.
  845. * For example, 'unset foo | whatever' will parse and run, but foo will
  846. * still be set at the end. */
  847. struct built_in_command {
  848. const char *b_cmd;
  849. int (*b_function)(char **argv) FAST_FUNC;
  850. #if ENABLE_HUSH_HELP
  851. const char *b_descr;
  852. # define BLTIN(cmd, func, help) { cmd, func, help }
  853. #else
  854. # define BLTIN(cmd, func, help) { cmd, func }
  855. #endif
  856. };
  857. static const struct built_in_command bltins1[] = {
  858. BLTIN("." , builtin_source , "Run commands in a file"),
  859. BLTIN(":" , builtin_true , NULL),
  860. #if ENABLE_HUSH_JOB
  861. BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
  862. #endif
  863. #if ENABLE_HUSH_LOOPS
  864. BLTIN("break" , builtin_break , "Exit from a loop"),
  865. #endif
  866. BLTIN("cd" , builtin_cd , "Change directory"),
  867. #if ENABLE_HUSH_LOOPS
  868. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  869. #endif
  870. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  871. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  872. BLTIN("exit" , builtin_exit , "Exit"),
  873. BLTIN("export" , builtin_export , "Set environment variables"),
  874. #if ENABLE_HUSH_JOB
  875. BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
  876. #endif
  877. #if ENABLE_HUSH_HELP
  878. BLTIN("help" , builtin_help , NULL),
  879. #endif
  880. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  881. BLTIN("history" , builtin_history , "Show command history"),
  882. #endif
  883. #if ENABLE_HUSH_JOB
  884. BLTIN("jobs" , builtin_jobs , "List jobs"),
  885. #endif
  886. #if ENABLE_HUSH_LOCAL
  887. BLTIN("local" , builtin_local , "Set local variables"),
  888. #endif
  889. #if HUSH_DEBUG
  890. BLTIN("memleak" , builtin_memleak , NULL),
  891. #endif
  892. BLTIN("read" , builtin_read , "Input into variable"),
  893. #if ENABLE_HUSH_FUNCTIONS
  894. BLTIN("return" , builtin_return , "Return from a function"),
  895. #endif
  896. BLTIN("set" , builtin_set , "Set/unset positional parameters"),
  897. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  898. #if ENABLE_HUSH_BASH_COMPAT
  899. BLTIN("source" , builtin_source , "Run commands in a file"),
  900. #endif
  901. BLTIN("trap" , builtin_trap , "Trap signals"),
  902. BLTIN("true" , builtin_true , NULL),
  903. BLTIN("type" , builtin_type , "Show command type"),
  904. BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
  905. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  906. BLTIN("unset" , builtin_unset , "Unset variables"),
  907. BLTIN("wait" , builtin_wait , "Wait for process"),
  908. };
  909. /* For now, echo and test are unconditionally enabled.
  910. * Maybe make it configurable? */
  911. static const struct built_in_command bltins2[] = {
  912. BLTIN("[" , builtin_test , NULL),
  913. BLTIN("echo" , builtin_echo , NULL),
  914. #if ENABLE_PRINTF
  915. BLTIN("printf" , builtin_printf , NULL),
  916. #endif
  917. BLTIN("pwd" , builtin_pwd , NULL),
  918. BLTIN("test" , builtin_test , NULL),
  919. };
  920. /* Debug printouts.
  921. */
  922. #if HUSH_DEBUG
  923. /* prevent disasters with G.debug_indent < 0 */
  924. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  925. # define debug_enter() (G.debug_indent++)
  926. # define debug_leave() (G.debug_indent--)
  927. #else
  928. # define indent() ((void)0)
  929. # define debug_enter() ((void)0)
  930. # define debug_leave() ((void)0)
  931. #endif
  932. #ifndef debug_printf
  933. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  934. #endif
  935. #ifndef debug_printf_parse
  936. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  937. #endif
  938. #ifndef debug_printf_exec
  939. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  940. #endif
  941. #ifndef debug_printf_env
  942. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  943. #endif
  944. #ifndef debug_printf_jobs
  945. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  946. # define DEBUG_JOBS 1
  947. #else
  948. # define DEBUG_JOBS 0
  949. #endif
  950. #ifndef debug_printf_expand
  951. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  952. # define DEBUG_EXPAND 1
  953. #else
  954. # define DEBUG_EXPAND 0
  955. #endif
  956. #ifndef debug_printf_varexp
  957. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  958. #endif
  959. #ifndef debug_printf_glob
  960. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  961. # define DEBUG_GLOB 1
  962. #else
  963. # define DEBUG_GLOB 0
  964. #endif
  965. #ifndef debug_printf_list
  966. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  967. #endif
  968. #ifndef debug_printf_subst
  969. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  970. #endif
  971. #ifndef debug_printf_clean
  972. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  973. # define DEBUG_CLEAN 1
  974. #else
  975. # define DEBUG_CLEAN 0
  976. #endif
  977. #if DEBUG_EXPAND
  978. static void debug_print_strings(const char *prefix, char **vv)
  979. {
  980. indent();
  981. fdprintf(2, "%s:\n", prefix);
  982. while (*vv)
  983. fdprintf(2, " '%s'\n", *vv++);
  984. }
  985. #else
  986. # define debug_print_strings(prefix, vv) ((void)0)
  987. #endif
  988. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  989. */
  990. #if LEAK_HUNTING
  991. static void *xxmalloc(int lineno, size_t size)
  992. {
  993. void *ptr = xmalloc((size + 0xff) & ~0xff);
  994. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  995. return ptr;
  996. }
  997. static void *xxrealloc(int lineno, void *ptr, size_t size)
  998. {
  999. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1000. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1001. return ptr;
  1002. }
  1003. static char *xxstrdup(int lineno, const char *str)
  1004. {
  1005. char *ptr = xstrdup(str);
  1006. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1007. return ptr;
  1008. }
  1009. static void xxfree(void *ptr)
  1010. {
  1011. fdprintf(2, "free %p\n", ptr);
  1012. free(ptr);
  1013. }
  1014. # define xmalloc(s) xxmalloc(__LINE__, s)
  1015. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1016. # define xstrdup(s) xxstrdup(__LINE__, s)
  1017. # define free(p) xxfree(p)
  1018. #endif
  1019. /* Syntax and runtime errors. They always abort scripts.
  1020. * In interactive use they usually discard unparsed and/or unexecuted commands
  1021. * and return to the prompt.
  1022. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1023. */
  1024. #if HUSH_DEBUG < 2
  1025. # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
  1026. # define syntax_error(lineno, msg) syntax_error(msg)
  1027. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1028. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1029. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1030. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1031. #endif
  1032. static void die_if_script(unsigned lineno, const char *fmt, ...)
  1033. {
  1034. va_list p;
  1035. #if HUSH_DEBUG >= 2
  1036. bb_error_msg("hush.c:%u", lineno);
  1037. #endif
  1038. va_start(p, fmt);
  1039. bb_verror_msg(fmt, p, NULL);
  1040. va_end(p);
  1041. if (!G_interactive_fd)
  1042. xfunc_die();
  1043. }
  1044. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1045. {
  1046. if (msg)
  1047. bb_error_msg("syntax error: %s", msg);
  1048. else
  1049. bb_error_msg("syntax error");
  1050. }
  1051. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1052. {
  1053. bb_error_msg("syntax error at '%s'", msg);
  1054. }
  1055. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1056. {
  1057. bb_error_msg("syntax error: unterminated %s", s);
  1058. }
  1059. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1060. {
  1061. char msg[2] = { ch, '\0' };
  1062. syntax_error_unterm_str(lineno, msg);
  1063. }
  1064. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1065. {
  1066. char msg[2];
  1067. msg[0] = ch;
  1068. msg[1] = '\0';
  1069. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1070. }
  1071. #if HUSH_DEBUG < 2
  1072. # undef die_if_script
  1073. # undef syntax_error
  1074. # undef syntax_error_at
  1075. # undef syntax_error_unterm_ch
  1076. # undef syntax_error_unterm_str
  1077. # undef syntax_error_unexpected_ch
  1078. #else
  1079. # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
  1080. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1081. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1082. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1083. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1084. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1085. #endif
  1086. #if ENABLE_HUSH_INTERACTIVE
  1087. static void cmdedit_update_prompt(void);
  1088. #else
  1089. # define cmdedit_update_prompt() ((void)0)
  1090. #endif
  1091. /* Utility functions
  1092. */
  1093. /* Replace each \x with x in place, return ptr past NUL. */
  1094. static char *unbackslash(char *src)
  1095. {
  1096. char *dst = src = strchrnul(src, '\\');
  1097. while (1) {
  1098. if (*src == '\\')
  1099. src++;
  1100. if ((*dst++ = *src++) == '\0')
  1101. break;
  1102. }
  1103. return dst;
  1104. }
  1105. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1106. {
  1107. int i;
  1108. unsigned count1;
  1109. unsigned count2;
  1110. char **v;
  1111. v = strings;
  1112. count1 = 0;
  1113. if (v) {
  1114. while (*v) {
  1115. count1++;
  1116. v++;
  1117. }
  1118. }
  1119. count2 = 0;
  1120. v = add;
  1121. while (*v) {
  1122. count2++;
  1123. v++;
  1124. }
  1125. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1126. v[count1 + count2] = NULL;
  1127. i = count2;
  1128. while (--i >= 0)
  1129. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1130. return v;
  1131. }
  1132. #if LEAK_HUNTING
  1133. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1134. {
  1135. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1136. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1137. return ptr;
  1138. }
  1139. #define add_strings_to_strings(strings, add, need_to_dup) \
  1140. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1141. #endif
  1142. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1143. static char **add_string_to_strings(char **strings, char *add)
  1144. {
  1145. char *v[2];
  1146. v[0] = add;
  1147. v[1] = NULL;
  1148. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1149. }
  1150. #if LEAK_HUNTING
  1151. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1152. {
  1153. char **ptr = add_string_to_strings(strings, add);
  1154. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1155. return ptr;
  1156. }
  1157. #define add_string_to_strings(strings, add) \
  1158. xx_add_string_to_strings(__LINE__, strings, add)
  1159. #endif
  1160. static void free_strings(char **strings)
  1161. {
  1162. char **v;
  1163. if (!strings)
  1164. return;
  1165. v = strings;
  1166. while (*v) {
  1167. free(*v);
  1168. v++;
  1169. }
  1170. free(strings);
  1171. }
  1172. /* Helpers for setting new $n and restoring them back
  1173. */
  1174. typedef struct save_arg_t {
  1175. char *sv_argv0;
  1176. char **sv_g_argv;
  1177. int sv_g_argc;
  1178. smallint sv_g_malloced;
  1179. } save_arg_t;
  1180. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1181. {
  1182. int n;
  1183. sv->sv_argv0 = argv[0];
  1184. sv->sv_g_argv = G.global_argv;
  1185. sv->sv_g_argc = G.global_argc;
  1186. sv->sv_g_malloced = G.global_args_malloced;
  1187. argv[0] = G.global_argv[0]; /* retain $0 */
  1188. G.global_argv = argv;
  1189. G.global_args_malloced = 0;
  1190. n = 1;
  1191. while (*++argv)
  1192. n++;
  1193. G.global_argc = n;
  1194. }
  1195. static void restore_G_args(save_arg_t *sv, char **argv)
  1196. {
  1197. char **pp;
  1198. if (G.global_args_malloced) {
  1199. /* someone ran "set -- arg1 arg2 ...", undo */
  1200. pp = G.global_argv;
  1201. while (*++pp) /* note: does not free $0 */
  1202. free(*pp);
  1203. free(G.global_argv);
  1204. }
  1205. argv[0] = sv->sv_argv0;
  1206. G.global_argv = sv->sv_g_argv;
  1207. G.global_argc = sv->sv_g_argc;
  1208. G.global_args_malloced = sv->sv_g_malloced;
  1209. }
  1210. /* Basic theory of signal handling in shell
  1211. * ========================================
  1212. * This does not describe what hush does, rather, it is current understanding
  1213. * what it _should_ do. If it doesn't, it's a bug.
  1214. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1215. *
  1216. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1217. * is finished or backgrounded. It is the same in interactive and
  1218. * non-interactive shells, and is the same regardless of whether
  1219. * a user trap handler is installed or a shell special one is in effect.
  1220. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1221. * backgrounds (i.e. stops) or kills all members of currently running
  1222. * pipe.
  1223. *
  1224. * Wait builtin is interruptible by signals for which user trap is set
  1225. * or by SIGINT in interactive shell.
  1226. *
  1227. * Trap handlers will execute even within trap handlers. (right?)
  1228. *
  1229. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1230. * except for handlers set to '' (empty string).
  1231. *
  1232. * If job control is off, backgrounded commands ("cmd &")
  1233. * have SIGINT, SIGQUIT set to SIG_IGN.
  1234. *
  1235. * Commands which are run in command substitution ("`cmd`")
  1236. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1237. *
  1238. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1239. * by the shell from its parent.
  1240. *
  1241. * Signals which differ from SIG_DFL action
  1242. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1243. *
  1244. * SIGQUIT: ignore
  1245. * SIGTERM (interactive): ignore
  1246. * SIGHUP (interactive):
  1247. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1248. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1249. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1250. * that all pipe members are stopped. Try this in bash:
  1251. * while :; do :; done - ^Z does not background it
  1252. * (while :; do :; done) - ^Z backgrounds it
  1253. * SIGINT (interactive): wait for last pipe, ignore the rest
  1254. * of the command line, show prompt. NB: ^C does not send SIGINT
  1255. * to interactive shell while shell is waiting for a pipe,
  1256. * since shell is bg'ed (is not in foreground process group).
  1257. * Example 1: this waits 5 sec, but does not execute ls:
  1258. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1259. * Example 2: this does not wait and does not execute ls:
  1260. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1261. * Example 3: this does not wait 5 sec, but executes ls:
  1262. * "sleep 5; ls -l" + press ^C
  1263. * Example 4: this does not wait and does not execute ls:
  1264. * "sleep 5 & wait; ls -l" + press ^C
  1265. *
  1266. * (What happens to signals which are IGN on shell start?)
  1267. * (What happens with signal mask on shell start?)
  1268. *
  1269. * Old implementation
  1270. * ==================
  1271. * We use in-kernel pending signal mask to determine which signals were sent.
  1272. * We block all signals which we don't want to take action immediately,
  1273. * i.e. we block all signals which need to have special handling as described
  1274. * above, and all signals which have traps set.
  1275. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1276. * and act on them.
  1277. *
  1278. * unsigned special_sig_mask: a mask of such "special" signals
  1279. * sigset_t blocked_set: current blocked signal set
  1280. *
  1281. * "trap - SIGxxx":
  1282. * clear bit in blocked_set unless it is also in special_sig_mask
  1283. * "trap 'cmd' SIGxxx":
  1284. * set bit in blocked_set (even if 'cmd' is '')
  1285. * after [v]fork, if we plan to be a shell:
  1286. * unblock signals with special interactive handling
  1287. * (child shell is not interactive),
  1288. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1289. * after [v]fork, if we plan to exec:
  1290. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1291. * Restore blocked signal set to one inherited by shell just prior to exec.
  1292. *
  1293. * Note: as a result, we do not use signal handlers much. The only uses
  1294. * are to count SIGCHLDs
  1295. * and to restore tty pgrp on signal-induced exit.
  1296. *
  1297. * Note 2 (compat):
  1298. * Standard says "When a subshell is entered, traps that are not being ignored
  1299. * are set to the default actions". bash interprets it so that traps which
  1300. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1301. *
  1302. * Problem: the above approach makes it unwieldy to catch signals while
  1303. * we are in read builtin, or while we read commands from stdin:
  1304. * masked signals are not visible!
  1305. *
  1306. * New implementation
  1307. * ==================
  1308. * We record each signal we are interested in by installing signal handler
  1309. * for them - a bit like emulating kernel pending signal mask in userspace.
  1310. * We are interested in: signals which need to have special handling
  1311. * as described above, and all signals which have traps set.
  1312. * Signals are recorded in pending_set.
  1313. * After each pipe execution, we extract any pending signals
  1314. * and act on them.
  1315. *
  1316. * unsigned special_sig_mask: a mask of shell-special signals.
  1317. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1318. * char *traps[sig] if trap for sig is set (even if it's '').
  1319. * sigset_t pending_set: set of sigs we received.
  1320. *
  1321. * "trap - SIGxxx":
  1322. * if sig is in special_sig_mask, set handler back to:
  1323. * record_pending_signo, or to IGN if it's a tty stop signal
  1324. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1325. * else: set handler back to SIG_DFL
  1326. * "trap 'cmd' SIGxxx":
  1327. * set handler to record_pending_signo.
  1328. * "trap '' SIGxxx":
  1329. * set handler to SIG_IGN.
  1330. * after [v]fork, if we plan to be a shell:
  1331. * set signals with special interactive handling to SIG_DFL
  1332. * (because child shell is not interactive),
  1333. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1334. * after [v]fork, if we plan to exec:
  1335. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1336. *
  1337. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1338. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1339. *
  1340. * Note (compat):
  1341. * Standard says "When a subshell is entered, traps that are not being ignored
  1342. * are set to the default actions". bash interprets it so that traps which
  1343. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1344. */
  1345. enum {
  1346. SPECIAL_INTERACTIVE_SIGS = 0
  1347. | (1 << SIGTERM)
  1348. | (1 << SIGINT)
  1349. | (1 << SIGHUP)
  1350. ,
  1351. SPECIAL_JOBSTOP_SIGS = 0
  1352. #if ENABLE_HUSH_JOB
  1353. | (1 << SIGTTIN)
  1354. | (1 << SIGTTOU)
  1355. | (1 << SIGTSTP)
  1356. #endif
  1357. ,
  1358. };
  1359. static void record_pending_signo(int sig)
  1360. {
  1361. sigaddset(&G.pending_set, sig);
  1362. #if ENABLE_HUSH_FAST
  1363. if (sig == SIGCHLD) {
  1364. G.count_SIGCHLD++;
  1365. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1366. }
  1367. #endif
  1368. }
  1369. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1370. {
  1371. struct sigaction old_sa;
  1372. /* We could use signal() to install handlers... almost:
  1373. * except that we need to mask ALL signals while handlers run.
  1374. * I saw signal nesting in strace, race window isn't small.
  1375. * SA_RESTART is also needed, but in Linux, signal()
  1376. * sets SA_RESTART too.
  1377. */
  1378. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1379. /* sigfillset(&G.sa.sa_mask); - already done */
  1380. /* G.sa.sa_flags = SA_RESTART; - already done */
  1381. G.sa.sa_handler = handler;
  1382. sigaction(sig, &G.sa, &old_sa);
  1383. return old_sa.sa_handler;
  1384. }
  1385. #if ENABLE_HUSH_JOB
  1386. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1387. # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
  1388. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1389. # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
  1390. /* Restores tty foreground process group, and exits.
  1391. * May be called as signal handler for fatal signal
  1392. * (will resend signal to itself, producing correct exit state)
  1393. * or called directly with -EXITCODE.
  1394. * We also call it if xfunc is exiting. */
  1395. static void sigexit(int sig) NORETURN;
  1396. static void sigexit(int sig)
  1397. {
  1398. /* Careful: we can end up here after [v]fork. Do not restore
  1399. * tty pgrp then, only top-level shell process does that */
  1400. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1401. /* Disable all signals: job control, SIGPIPE, etc.
  1402. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1403. */
  1404. sigprocmask_allsigs(SIG_BLOCK);
  1405. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1406. }
  1407. /* Not a signal, just exit */
  1408. if (sig <= 0)
  1409. _exit(- sig);
  1410. kill_myself_with_sig(sig); /* does not return */
  1411. }
  1412. #else
  1413. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1414. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1415. #endif
  1416. static sighandler_t pick_sighandler(unsigned sig)
  1417. {
  1418. sighandler_t handler = SIG_DFL;
  1419. if (sig < sizeof(unsigned)*8) {
  1420. unsigned sigmask = (1 << sig);
  1421. #if ENABLE_HUSH_JOB
  1422. /* is sig fatal? */
  1423. if (G_fatal_sig_mask & sigmask)
  1424. handler = sigexit;
  1425. else
  1426. #endif
  1427. /* sig has special handling? */
  1428. if (G.special_sig_mask & sigmask) {
  1429. handler = record_pending_signo;
  1430. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1431. * in order to ignore them: they will be raised
  1432. * in an endless loop when we try to do some
  1433. * terminal ioctls! We do have to _ignore_ these.
  1434. */
  1435. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1436. handler = SIG_IGN;
  1437. }
  1438. }
  1439. return handler;
  1440. }
  1441. /* Restores tty foreground process group, and exits. */
  1442. static void hush_exit(int exitcode) NORETURN;
  1443. static void hush_exit(int exitcode)
  1444. {
  1445. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1446. save_history(G.line_input_state);
  1447. #endif
  1448. fflush_all();
  1449. if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
  1450. char *argv[3];
  1451. /* argv[0] is unused */
  1452. argv[1] = G.traps[0];
  1453. argv[2] = NULL;
  1454. G.exiting = 1; /* prevent EXIT trap recursion */
  1455. /* Note: G.traps[0] is not cleared!
  1456. * "trap" will still show it, if executed
  1457. * in the handler */
  1458. builtin_eval(argv);
  1459. }
  1460. #if ENABLE_FEATURE_CLEAN_UP
  1461. {
  1462. struct variable *cur_var;
  1463. if (G.cwd != bb_msg_unknown)
  1464. free((char*)G.cwd);
  1465. cur_var = G.top_var;
  1466. while (cur_var) {
  1467. struct variable *tmp = cur_var;
  1468. if (!cur_var->max_len)
  1469. free(cur_var->varstr);
  1470. cur_var = cur_var->next;
  1471. free(tmp);
  1472. }
  1473. }
  1474. #endif
  1475. #if ENABLE_HUSH_JOB
  1476. fflush_all();
  1477. sigexit(- (exitcode & 0xff));
  1478. #else
  1479. exit(exitcode);
  1480. #endif
  1481. }
  1482. //TODO: return a mask of ALL handled sigs?
  1483. static int check_and_run_traps(void)
  1484. {
  1485. int last_sig = 0;
  1486. while (1) {
  1487. int sig;
  1488. if (sigisemptyset(&G.pending_set))
  1489. break;
  1490. sig = 0;
  1491. do {
  1492. sig++;
  1493. if (sigismember(&G.pending_set, sig)) {
  1494. sigdelset(&G.pending_set, sig);
  1495. goto got_sig;
  1496. }
  1497. } while (sig < NSIG);
  1498. break;
  1499. got_sig:
  1500. if (G.traps && G.traps[sig]) {
  1501. if (G.traps[sig][0]) {
  1502. /* We have user-defined handler */
  1503. smalluint save_rcode;
  1504. char *argv[3];
  1505. /* argv[0] is unused */
  1506. argv[1] = G.traps[sig];
  1507. argv[2] = NULL;
  1508. save_rcode = G.last_exitcode;
  1509. builtin_eval(argv);
  1510. G.last_exitcode = save_rcode;
  1511. last_sig = sig;
  1512. } /* else: "" trap, ignoring signal */
  1513. continue;
  1514. }
  1515. /* not a trap: special action */
  1516. switch (sig) {
  1517. case SIGINT:
  1518. /* Builtin was ^C'ed, make it look prettier: */
  1519. bb_putchar('\n');
  1520. G.flag_SIGINT = 1;
  1521. last_sig = sig;
  1522. break;
  1523. #if ENABLE_HUSH_JOB
  1524. case SIGHUP: {
  1525. struct pipe *job;
  1526. /* bash is observed to signal whole process groups,
  1527. * not individual processes */
  1528. for (job = G.job_list; job; job = job->next) {
  1529. if (job->pgrp <= 0)
  1530. continue;
  1531. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  1532. if (kill(- job->pgrp, SIGHUP) == 0)
  1533. kill(- job->pgrp, SIGCONT);
  1534. }
  1535. sigexit(SIGHUP);
  1536. }
  1537. #endif
  1538. #if ENABLE_HUSH_FAST
  1539. case SIGCHLD:
  1540. G.count_SIGCHLD++;
  1541. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1542. /* Note:
  1543. * We dont do 'last_sig = sig' here -> NOT returning this sig.
  1544. * This simplifies wait builtin a bit.
  1545. */
  1546. break;
  1547. #endif
  1548. default: /* ignored: */
  1549. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  1550. /* Note:
  1551. * We dont do 'last_sig = sig' here -> NOT returning this sig.
  1552. * Example: wait is not interrupted by TERM
  1553. * in interactive shell, because TERM is ignored.
  1554. */
  1555. break;
  1556. }
  1557. }
  1558. return last_sig;
  1559. }
  1560. static const char *get_cwd(int force)
  1561. {
  1562. if (force || G.cwd == NULL) {
  1563. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  1564. * we must not try to free(bb_msg_unknown) */
  1565. if (G.cwd == bb_msg_unknown)
  1566. G.cwd = NULL;
  1567. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  1568. if (!G.cwd)
  1569. G.cwd = bb_msg_unknown;
  1570. }
  1571. return G.cwd;
  1572. }
  1573. /*
  1574. * Shell and environment variable support
  1575. */
  1576. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  1577. {
  1578. struct variable **pp;
  1579. struct variable *cur;
  1580. pp = &G.top_var;
  1581. while ((cur = *pp) != NULL) {
  1582. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  1583. return pp;
  1584. pp = &cur->next;
  1585. }
  1586. return NULL;
  1587. }
  1588. static const char* FAST_FUNC get_local_var_value(const char *name)
  1589. {
  1590. struct variable **vpp;
  1591. unsigned len = strlen(name);
  1592. if (G.expanded_assignments) {
  1593. char **cpp = G.expanded_assignments;
  1594. while (*cpp) {
  1595. char *cp = *cpp;
  1596. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  1597. return cp + len + 1;
  1598. cpp++;
  1599. }
  1600. }
  1601. vpp = get_ptr_to_local_var(name, len);
  1602. if (vpp)
  1603. return (*vpp)->varstr + len + 1;
  1604. if (strcmp(name, "PPID") == 0)
  1605. return utoa(G.root_ppid);
  1606. // bash compat: UID? EUID?
  1607. #if ENABLE_HUSH_RANDOM_SUPPORT
  1608. if (strcmp(name, "RANDOM") == 0)
  1609. return utoa(next_random(&G.random_gen));
  1610. #endif
  1611. return NULL;
  1612. }
  1613. /* str holds "NAME=VAL" and is expected to be malloced.
  1614. * We take ownership of it.
  1615. * flg_export:
  1616. * 0: do not change export flag
  1617. * (if creating new variable, flag will be 0)
  1618. * 1: set export flag and putenv the variable
  1619. * -1: clear export flag and unsetenv the variable
  1620. * flg_read_only is set only when we handle -R var=val
  1621. */
  1622. #if !BB_MMU && ENABLE_HUSH_LOCAL
  1623. /* all params are used */
  1624. #elif BB_MMU && ENABLE_HUSH_LOCAL
  1625. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1626. set_local_var(str, flg_export, local_lvl)
  1627. #elif BB_MMU && !ENABLE_HUSH_LOCAL
  1628. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1629. set_local_var(str, flg_export)
  1630. #elif !BB_MMU && !ENABLE_HUSH_LOCAL
  1631. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1632. set_local_var(str, flg_export, flg_read_only)
  1633. #endif
  1634. static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
  1635. {
  1636. struct variable **var_pp;
  1637. struct variable *cur;
  1638. char *eq_sign;
  1639. int name_len;
  1640. eq_sign = strchr(str, '=');
  1641. if (!eq_sign) { /* not expected to ever happen? */
  1642. free(str);
  1643. return -1;
  1644. }
  1645. name_len = eq_sign - str + 1; /* including '=' */
  1646. var_pp = &G.top_var;
  1647. while ((cur = *var_pp) != NULL) {
  1648. if (strncmp(cur->varstr, str, name_len) != 0) {
  1649. var_pp = &cur->next;
  1650. continue;
  1651. }
  1652. /* We found an existing var with this name */
  1653. if (cur->flg_read_only) {
  1654. #if !BB_MMU
  1655. if (!flg_read_only)
  1656. #endif
  1657. bb_error_msg("%s: readonly variable", str);
  1658. free(str);
  1659. return -1;
  1660. }
  1661. if (flg_export == -1) { // "&& cur->flg_export" ?
  1662. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  1663. *eq_sign = '\0';
  1664. unsetenv(str);
  1665. *eq_sign = '=';
  1666. }
  1667. #if ENABLE_HUSH_LOCAL
  1668. if (cur->func_nest_level < local_lvl) {
  1669. /* New variable is declared as local,
  1670. * and existing one is global, or local
  1671. * from enclosing function.
  1672. * Remove and save old one: */
  1673. *var_pp = cur->next;
  1674. cur->next = *G.shadowed_vars_pp;
  1675. *G.shadowed_vars_pp = cur;
  1676. /* bash 3.2.33(1) and exported vars:
  1677. * # export z=z
  1678. * # f() { local z=a; env | grep ^z; }
  1679. * # f
  1680. * z=a
  1681. * # env | grep ^z
  1682. * z=z
  1683. */
  1684. if (cur->flg_export)
  1685. flg_export = 1;
  1686. break;
  1687. }
  1688. #endif
  1689. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  1690. free_and_exp:
  1691. free(str);
  1692. goto exp;
  1693. }
  1694. if (cur->max_len != 0) {
  1695. if (cur->max_len >= strlen(str)) {
  1696. /* This one is from startup env, reuse space */
  1697. strcpy(cur->varstr, str);
  1698. goto free_and_exp;
  1699. }
  1700. } else {
  1701. /* max_len == 0 signifies "malloced" var, which we can
  1702. * (and has to) free */
  1703. free(cur->varstr);
  1704. }
  1705. cur->max_len = 0;
  1706. goto set_str_and_exp;
  1707. }
  1708. /* Not found - create new variable struct */
  1709. cur = xzalloc(sizeof(*cur));
  1710. #if ENABLE_HUSH_LOCAL
  1711. cur->func_nest_level = local_lvl;
  1712. #endif
  1713. cur->next = *var_pp;
  1714. *var_pp = cur;
  1715. set_str_and_exp:
  1716. cur->varstr = str;
  1717. #if !BB_MMU
  1718. cur->flg_read_only = flg_read_only;
  1719. #endif
  1720. exp:
  1721. if (flg_export == 1)
  1722. cur->flg_export = 1;
  1723. if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
  1724. cmdedit_update_prompt();
  1725. if (cur->flg_export) {
  1726. if (flg_export == -1) {
  1727. cur->flg_export = 0;
  1728. /* unsetenv was already done */
  1729. } else {
  1730. debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
  1731. return putenv(cur->varstr);
  1732. }
  1733. }
  1734. return 0;
  1735. }
  1736. /* Used at startup and after each cd */
  1737. static void set_pwd_var(int exp)
  1738. {
  1739. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
  1740. /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
  1741. }
  1742. static int unset_local_var_len(const char *name, int name_len)
  1743. {
  1744. struct variable *cur;
  1745. struct variable **var_pp;
  1746. if (!name)
  1747. return EXIT_SUCCESS;
  1748. var_pp = &G.top_var;
  1749. while ((cur = *var_pp) != NULL) {
  1750. if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
  1751. if (cur->flg_read_only) {
  1752. bb_error_msg("%s: readonly variable", name);
  1753. return EXIT_FAILURE;
  1754. }
  1755. *var_pp = cur->next;
  1756. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  1757. bb_unsetenv(cur->varstr);
  1758. if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
  1759. cmdedit_update_prompt();
  1760. if (!cur->max_len)
  1761. free(cur->varstr);
  1762. free(cur);
  1763. return EXIT_SUCCESS;
  1764. }
  1765. var_pp = &cur->next;
  1766. }
  1767. return EXIT_SUCCESS;
  1768. }
  1769. static int unset_local_var(const char *name)
  1770. {
  1771. return unset_local_var_len(name, strlen(name));
  1772. }
  1773. static void unset_vars(char **strings)
  1774. {
  1775. char **v;
  1776. if (!strings)
  1777. return;
  1778. v = strings;
  1779. while (*v) {
  1780. const char *eq = strchrnul(*v, '=');
  1781. unset_local_var_len(*v, (int)(eq - *v));
  1782. v++;
  1783. }
  1784. free(strings);
  1785. }
  1786. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  1787. {
  1788. char *var = xasprintf("%s=%s", name, val);
  1789. set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  1790. }
  1791. /*
  1792. * Helpers for "var1=val1 var2=val2 cmd" feature
  1793. */
  1794. static void add_vars(struct variable *var)
  1795. {
  1796. struct variable *next;
  1797. while (var) {
  1798. next = var->next;
  1799. var->next = G.top_var;
  1800. G.top_var = var;
  1801. if (var->flg_export) {
  1802. debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
  1803. putenv(var->varstr);
  1804. } else {
  1805. debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
  1806. }
  1807. var = next;
  1808. }
  1809. }
  1810. static struct variable *set_vars_and_save_old(char **strings)
  1811. {
  1812. char **s;
  1813. struct variable *old = NULL;
  1814. if (!strings)
  1815. return old;
  1816. s = strings;
  1817. while (*s) {
  1818. struct variable *var_p;
  1819. struct variable **var_pp;
  1820. char *eq;
  1821. eq = strchr(*s, '=');
  1822. if (eq) {
  1823. var_pp = get_ptr_to_local_var(*s, eq - *s);
  1824. if (var_pp) {
  1825. /* Remove variable from global linked list */
  1826. var_p = *var_pp;
  1827. debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
  1828. *var_pp = var_p->next;
  1829. /* Add it to returned list */
  1830. var_p->next = old;
  1831. old = var_p;
  1832. }
  1833. set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
  1834. }
  1835. s++;
  1836. }
  1837. return old;
  1838. }
  1839. /*
  1840. * Unicode helper
  1841. */
  1842. static void reinit_unicode_for_hush(void)
  1843. {
  1844. /* Unicode support should be activated even if LANG is set
  1845. * _during_ shell execution, not only if it was set when
  1846. * shell was started. Therefore, re-check LANG every time:
  1847. */
  1848. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1849. || ENABLE_UNICODE_USING_LOCALE
  1850. ) {
  1851. const char *s = get_local_var_value("LC_ALL");
  1852. if (!s) s = get_local_var_value("LC_CTYPE");
  1853. if (!s) s = get_local_var_value("LANG");
  1854. reinit_unicode(s);
  1855. }
  1856. }
  1857. /*
  1858. * in_str support
  1859. */
  1860. static int FAST_FUNC static_get(struct in_str *i)
  1861. {
  1862. int ch = *i->p;
  1863. if (ch != '\0') {
  1864. i->p++;
  1865. i->last_char = ch;
  1866. return ch;
  1867. }
  1868. return EOF;
  1869. }
  1870. static int FAST_FUNC static_peek(struct in_str *i)
  1871. {
  1872. return *i->p;
  1873. }
  1874. #if ENABLE_HUSH_INTERACTIVE
  1875. static void cmdedit_update_prompt(void)
  1876. {
  1877. if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1878. G.PS1 = get_local_var_value("PS1");
  1879. if (G.PS1 == NULL)
  1880. G.PS1 = "\\w \\$ ";
  1881. G.PS2 = get_local_var_value("PS2");
  1882. } else {
  1883. G.PS1 = NULL;
  1884. }
  1885. if (G.PS2 == NULL)
  1886. G.PS2 = "> ";
  1887. }
  1888. static const char *setup_prompt_string(int promptmode)
  1889. {
  1890. const char *prompt_str;
  1891. debug_printf("setup_prompt_string %d ", promptmode);
  1892. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1893. /* Set up the prompt */
  1894. if (promptmode == 0) { /* PS1 */
  1895. free((char*)G.PS1);
  1896. /* bash uses $PWD value, even if it is set by user.
  1897. * It uses current dir only if PWD is unset.
  1898. * We always use current dir. */
  1899. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  1900. prompt_str = G.PS1;
  1901. } else
  1902. prompt_str = G.PS2;
  1903. } else
  1904. prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
  1905. debug_printf("result '%s'\n", prompt_str);
  1906. return prompt_str;
  1907. }
  1908. static void get_user_input(struct in_str *i)
  1909. {
  1910. int r;
  1911. const char *prompt_str;
  1912. prompt_str = setup_prompt_string(i->promptmode);
  1913. # if ENABLE_FEATURE_EDITING
  1914. /* Enable command line editing only while a command line
  1915. * is actually being read */
  1916. do {
  1917. reinit_unicode_for_hush();
  1918. G.flag_SIGINT = 0;
  1919. /* buglet: SIGINT will not make new prompt to appear _at once_,
  1920. * only after <Enter>. (^C will work) */
  1921. r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
  1922. /* catch *SIGINT* etc (^C is handled by read_line_input) */
  1923. check_and_run_traps();
  1924. } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
  1925. i->eof_flag = (r < 0);
  1926. if (i->eof_flag) { /* EOF/error detected */
  1927. G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
  1928. G.user_input_buf[1] = '\0';
  1929. }
  1930. # else
  1931. do {
  1932. G.flag_SIGINT = 0;
  1933. if (i->last_char == '\0' || i->last_char == '\n') {
  1934. /* Why check_and_run_traps here? Try this interactively:
  1935. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  1936. * $ <[enter], repeatedly...>
  1937. * Without check_and_run_traps, handler never runs.
  1938. */
  1939. check_and_run_traps();
  1940. fputs(prompt_str, stdout);
  1941. }
  1942. fflush_all();
  1943. G.user_input_buf[0] = r = fgetc(i->file);
  1944. /*G.user_input_buf[1] = '\0'; - already is and never changed */
  1945. } while (G.flag_SIGINT);
  1946. i->eof_flag = (r == EOF);
  1947. # endif
  1948. i->p = G.user_input_buf;
  1949. }
  1950. #endif /* INTERACTIVE */
  1951. /* This is the magic location that prints prompts
  1952. * and gets data back from the user */
  1953. static int FAST_FUNC file_get(struct in_str *i)
  1954. {
  1955. int ch;
  1956. /* If there is data waiting, eat it up */
  1957. if (i->p && *i->p) {
  1958. #if ENABLE_HUSH_INTERACTIVE
  1959. take_cached:
  1960. #endif
  1961. ch = *i->p++;
  1962. if (i->eof_flag && !*i->p)
  1963. ch = EOF;
  1964. /* note: ch is never NUL */
  1965. } else {
  1966. /* need to double check i->file because we might be doing something
  1967. * more complicated by now, like sourcing or substituting. */
  1968. #if ENABLE_HUSH_INTERACTIVE
  1969. if (G_interactive_fd && i->file == stdin) {
  1970. do {
  1971. get_user_input(i);
  1972. } while (!*i->p); /* need non-empty line */
  1973. i->promptmode = 1; /* PS2 */
  1974. goto take_cached;
  1975. }
  1976. #endif
  1977. do ch = fgetc(i->file); while (ch == '\0');
  1978. }
  1979. debug_printf("file_get: got '%c' %d\n", ch, ch);
  1980. i->last_char = ch;
  1981. return ch;
  1982. }
  1983. /* All callers guarantee this routine will never
  1984. * be used right after a newline, so prompting is not needed.
  1985. */
  1986. static int FAST_FUNC file_peek(struct in_str *i)
  1987. {
  1988. int ch;
  1989. if (i->p && *i->p) {
  1990. if (i->eof_flag && !i->p[1])
  1991. return EOF;
  1992. return *i->p;
  1993. /* note: ch is never NUL */
  1994. }
  1995. do ch = fgetc(i->file); while (ch == '\0');
  1996. i->eof_flag = (ch == EOF);
  1997. i->peek_buf[0] = ch;
  1998. i->peek_buf[1] = '\0';
  1999. i->p = i->peek_buf;
  2000. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2001. return ch;
  2002. }
  2003. static void setup_file_in_str(struct in_str *i, FILE *f)
  2004. {
  2005. memset(i, 0, sizeof(*i));
  2006. i->peek = file_peek;
  2007. i->get = file_get;
  2008. /* i->promptmode = 0; - PS1 (memset did it) */
  2009. i->file = f;
  2010. /* i->p = NULL; */
  2011. }
  2012. static void setup_string_in_str(struct in_str *i, const char *s)
  2013. {
  2014. memset(i, 0, sizeof(*i));
  2015. i->peek = static_peek;
  2016. i->get = static_get;
  2017. /* i->promptmode = 0; - PS1 (memset did it) */
  2018. i->p = s;
  2019. /* i->eof_flag = 0; */
  2020. }
  2021. /*
  2022. * o_string support
  2023. */
  2024. #define B_CHUNK (32 * sizeof(char*))
  2025. static void o_reset_to_empty_unquoted(o_string *o)
  2026. {
  2027. o->length = 0;
  2028. o->has_quoted_part = 0;
  2029. if (o->data)
  2030. o->data[0] = '\0';
  2031. }
  2032. static void o_free(o_string *o)
  2033. {
  2034. free(o->data);
  2035. memset(o, 0, sizeof(*o));
  2036. }
  2037. static ALWAYS_INLINE void o_free_unsafe(o_string *o)
  2038. {
  2039. free(o->data);
  2040. }
  2041. static void o_grow_by(o_string *o, int len)
  2042. {
  2043. if (o->length + len > o->maxlen) {
  2044. o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
  2045. o->data = xrealloc(o->data, 1 + o->maxlen);
  2046. }
  2047. }
  2048. static void o_addchr(o_string *o, int ch)
  2049. {
  2050. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2051. o_grow_by(o, 1);
  2052. o->data[o->length] = ch;
  2053. o->length++;
  2054. o->data[o->length] = '\0';
  2055. }
  2056. static void o_addblock(o_string *o, const char *str, int len)
  2057. {
  2058. o_grow_by(o, len);
  2059. memcpy(&o->data[o->length], str, len);
  2060. o->length += len;
  2061. o->data[o->length] = '\0';
  2062. }
  2063. static void o_addstr(o_string *o, const char *str)
  2064. {
  2065. o_addblock(o, str, strlen(str));
  2066. }
  2067. #if !BB_MMU
  2068. static void nommu_addchr(o_string *o, int ch)
  2069. {
  2070. if (o)
  2071. o_addchr(o, ch);
  2072. }
  2073. #else
  2074. # define nommu_addchr(o, str) ((void)0)
  2075. #endif
  2076. static void o_addstr_with_NUL(o_string *o, const char *str)
  2077. {
  2078. o_addblock(o, str, strlen(str) + 1);
  2079. }
  2080. /*
  2081. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2082. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2083. * Apparently, on unquoted $v bash still does globbing
  2084. * ("v='*.txt'; echo $v" prints all .txt files),
  2085. * but NOT brace expansion! Thus, there should be TWO independent
  2086. * quoting mechanisms on $v expansion side: one protects
  2087. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2088. * We have only second one.
  2089. */
  2090. #if ENABLE_HUSH_BRACE_EXPANSION
  2091. # define MAYBE_BRACES "{}"
  2092. #else
  2093. # define MAYBE_BRACES ""
  2094. #endif
  2095. /* My analysis of quoting semantics tells me that state information
  2096. * is associated with a destination, not a source.
  2097. */
  2098. static void o_addqchr(o_string *o, int ch)
  2099. {
  2100. int sz = 1;
  2101. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2102. if (found)
  2103. sz++;
  2104. o_grow_by(o, sz);
  2105. if (found) {
  2106. o->data[o->length] = '\\';
  2107. o->length++;
  2108. }
  2109. o->data[o->length] = ch;
  2110. o->length++;
  2111. o->data[o->length] = '\0';
  2112. }
  2113. static void o_addQchr(o_string *o, int ch)
  2114. {
  2115. int sz = 1;
  2116. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2117. && strchr("*?[\\" MAYBE_BRACES, ch)
  2118. ) {
  2119. sz++;
  2120. o->data[o->length] = '\\';
  2121. o->length++;
  2122. }
  2123. o_grow_by(o, sz);
  2124. o->data[o->length] = ch;
  2125. o->length++;
  2126. o->data[o->length] = '\0';
  2127. }
  2128. static void o_addqblock(o_string *o, const char *str, int len)
  2129. {
  2130. while (len) {
  2131. char ch;
  2132. int sz;
  2133. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2134. if (ordinary_cnt > len) /* paranoia */
  2135. ordinary_cnt = len;
  2136. o_addblock(o, str, ordinary_cnt);
  2137. if (ordinary_cnt == len)
  2138. return; /* NUL is already added by o_addblock */
  2139. str += ordinary_cnt;
  2140. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2141. ch = *str++;
  2142. sz = 1;
  2143. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2144. sz++;
  2145. o->data[o->length] = '\\';
  2146. o->length++;
  2147. }
  2148. o_grow_by(o, sz);
  2149. o->data[o->length] = ch;
  2150. o->length++;
  2151. }
  2152. o->data[o->length] = '\0';
  2153. }
  2154. static void o_addQblock(o_string *o, const char *str, int len)
  2155. {
  2156. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2157. o_addblock(o, str, len);
  2158. return;
  2159. }
  2160. o_addqblock(o, str, len);
  2161. }
  2162. static void o_addQstr(o_string *o, const char *str)
  2163. {
  2164. o_addQblock(o, str, strlen(str));
  2165. }
  2166. /* A special kind of o_string for $VAR and `cmd` expansion.
  2167. * It contains char* list[] at the beginning, which is grown in 16 element
  2168. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2169. * list[i] contains an INDEX (int!) into this string data.
  2170. * It means that if list[] needs to grow, data needs to be moved higher up
  2171. * but list[i]'s need not be modified.
  2172. * NB: remembering how many list[i]'s you have there is crucial.
  2173. * o_finalize_list() operation post-processes this structure - calculates
  2174. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2175. */
  2176. #if DEBUG_EXPAND || DEBUG_GLOB
  2177. static void debug_print_list(const char *prefix, o_string *o, int n)
  2178. {
  2179. char **list = (char**)o->data;
  2180. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2181. int i = 0;
  2182. indent();
  2183. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2184. prefix, list, n, string_start, o->length, o->maxlen,
  2185. !!(o->o_expflags & EXP_FLAG_GLOB),
  2186. o->has_quoted_part,
  2187. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2188. while (i < n) {
  2189. indent();
  2190. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2191. o->data + (int)(uintptr_t)list[i] + string_start,
  2192. o->data + (int)(uintptr_t)list[i] + string_start);
  2193. i++;
  2194. }
  2195. if (n) {
  2196. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2197. indent();
  2198. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2199. }
  2200. }
  2201. #else
  2202. # define debug_print_list(prefix, o, n) ((void)0)
  2203. #endif
  2204. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2205. * in list[n] so that it points past last stored byte so far.
  2206. * It returns n+1. */
  2207. static int o_save_ptr_helper(o_string *o, int n)
  2208. {
  2209. char **list = (char**)o->data;
  2210. int string_start;
  2211. int string_len;
  2212. if (!o->has_empty_slot) {
  2213. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2214. string_len = o->length - string_start;
  2215. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2216. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2217. /* list[n] points to string_start, make space for 16 more pointers */
  2218. o->maxlen += 0x10 * sizeof(list[0]);
  2219. o->data = xrealloc(o->data, o->maxlen + 1);
  2220. list = (char**)o->data;
  2221. memmove(list + n + 0x10, list + n, string_len);
  2222. o->length += 0x10 * sizeof(list[0]);
  2223. } else {
  2224. debug_printf_list("list[%d]=%d string_start=%d\n",
  2225. n, string_len, string_start);
  2226. }
  2227. } else {
  2228. /* We have empty slot at list[n], reuse without growth */
  2229. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2230. string_len = o->length - string_start;
  2231. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2232. n, string_len, string_start);
  2233. o->has_empty_slot = 0;
  2234. }
  2235. o->has_quoted_part = 0;
  2236. list[n] = (char*)(uintptr_t)string_len;
  2237. return n + 1;
  2238. }
  2239. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2240. static int o_get_last_ptr(o_string *o, int n)
  2241. {
  2242. char **list = (char**)o->data;
  2243. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2244. return ((int)(uintptr_t)list[n-1]) + string_start;
  2245. }
  2246. #if ENABLE_HUSH_BRACE_EXPANSION
  2247. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2248. * first, it processes even {a} (no commas), second,
  2249. * I didn't manage to make it return strings when they don't match
  2250. * existing files. Need to re-implement it.
  2251. */
  2252. /* Helper */
  2253. static int glob_needed(const char *s)
  2254. {
  2255. while (*s) {
  2256. if (*s == '\\') {
  2257. if (!s[1])
  2258. return 0;
  2259. s += 2;
  2260. continue;
  2261. }
  2262. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2263. return 1;
  2264. s++;
  2265. }
  2266. return 0;
  2267. }
  2268. /* Return pointer to next closing brace or to comma */
  2269. static const char *next_brace_sub(const char *cp)
  2270. {
  2271. unsigned depth = 0;
  2272. cp++;
  2273. while (*cp != '\0') {
  2274. if (*cp == '\\') {
  2275. if (*++cp == '\0')
  2276. break;
  2277. cp++;
  2278. continue;
  2279. }
  2280. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  2281. break;
  2282. if (*cp++ == '{')
  2283. depth++;
  2284. }
  2285. return *cp != '\0' ? cp : NULL;
  2286. }
  2287. /* Recursive brace globber. Note: may garble pattern[]. */
  2288. static int glob_brace(char *pattern, o_string *o, int n)
  2289. {
  2290. char *new_pattern_buf;
  2291. const char *begin;
  2292. const char *next;
  2293. const char *rest;
  2294. const char *p;
  2295. size_t rest_len;
  2296. debug_printf_glob("glob_brace('%s')\n", pattern);
  2297. begin = pattern;
  2298. while (1) {
  2299. if (*begin == '\0')
  2300. goto simple_glob;
  2301. if (*begin == '{') {
  2302. /* Find the first sub-pattern and at the same time
  2303. * find the rest after the closing brace */
  2304. next = next_brace_sub(begin);
  2305. if (next == NULL) {
  2306. /* An illegal expression */
  2307. goto simple_glob;
  2308. }
  2309. if (*next == '}') {
  2310. /* "{abc}" with no commas - illegal
  2311. * brace expr, disregard and skip it */
  2312. begin = next + 1;
  2313. continue;
  2314. }
  2315. break;
  2316. }
  2317. if (*begin == '\\' && begin[1] != '\0')
  2318. begin++;
  2319. begin++;
  2320. }
  2321. debug_printf_glob("begin:%s\n", begin);
  2322. debug_printf_glob("next:%s\n", next);
  2323. /* Now find the end of the whole brace expression */
  2324. rest = next;
  2325. while (*rest != '}') {
  2326. rest = next_brace_sub(rest);
  2327. if (rest == NULL) {
  2328. /* An illegal expression */
  2329. goto simple_glob;
  2330. }
  2331. debug_printf_glob("rest:%s\n", rest);
  2332. }
  2333. rest_len = strlen(++rest) + 1;
  2334. /* We are sure the brace expression is well-formed */
  2335. /* Allocate working buffer large enough for our work */
  2336. new_pattern_buf = xmalloc(strlen(pattern));
  2337. /* We have a brace expression. BEGIN points to the opening {,
  2338. * NEXT points past the terminator of the first element, and REST
  2339. * points past the final }. We will accumulate result names from
  2340. * recursive runs for each brace alternative in the buffer using
  2341. * GLOB_APPEND. */
  2342. p = begin + 1;
  2343. while (1) {
  2344. /* Construct the new glob expression */
  2345. memcpy(
  2346. mempcpy(
  2347. mempcpy(new_pattern_buf,
  2348. /* We know the prefix for all sub-patterns */
  2349. pattern, begin - pattern),
  2350. p, next - p),
  2351. rest, rest_len);
  2352. /* Note: glob_brace() may garble new_pattern_buf[].
  2353. * That's why we re-copy prefix every time (1st memcpy above).
  2354. */
  2355. n = glob_brace(new_pattern_buf, o, n);
  2356. if (*next == '}') {
  2357. /* We saw the last entry */
  2358. break;
  2359. }
  2360. p = next + 1;
  2361. next = next_brace_sub(next);
  2362. }
  2363. free(new_pattern_buf);
  2364. return n;
  2365. simple_glob:
  2366. {
  2367. int gr;
  2368. glob_t globdata;
  2369. memset(&globdata, 0, sizeof(globdata));
  2370. gr = glob(pattern, 0, NULL, &globdata);
  2371. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  2372. if (gr != 0) {
  2373. if (gr == GLOB_NOMATCH) {
  2374. globfree(&globdata);
  2375. /* NB: garbles parameter */
  2376. unbackslash(pattern);
  2377. o_addstr_with_NUL(o, pattern);
  2378. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2379. return o_save_ptr_helper(o, n);
  2380. }
  2381. if (gr == GLOB_NOSPACE)
  2382. bb_error_msg_and_die(bb_msg_memory_exhausted);
  2383. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  2384. * but we didn't specify it. Paranoia again. */
  2385. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  2386. }
  2387. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  2388. char **argv = globdata.gl_pathv;
  2389. while (1) {
  2390. o_addstr_with_NUL(o, *argv);
  2391. n = o_save_ptr_helper(o, n);
  2392. argv++;
  2393. if (!*argv)
  2394. break;
  2395. }
  2396. }
  2397. globfree(&globdata);
  2398. }
  2399. return n;
  2400. }
  2401. /* Performs globbing on last list[],
  2402. * saving each result as a new list[].
  2403. */
  2404. static int perform_glob(o_string *o, int n)
  2405. {
  2406. char *pattern, *copy;
  2407. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  2408. if (!o->data)
  2409. return o_save_ptr_helper(o, n);
  2410. pattern = o->data + o_get_last_ptr(o, n);
  2411. debug_printf_glob("glob pattern '%s'\n", pattern);
  2412. if (!glob_needed(pattern)) {
  2413. /* unbackslash last string in o in place, fix length */
  2414. o->length = unbackslash(pattern) - o->data;
  2415. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2416. return o_save_ptr_helper(o, n);
  2417. }
  2418. copy = xstrdup(pattern);
  2419. /* "forget" pattern in o */
  2420. o->length = pattern - o->data;
  2421. n = glob_brace(copy, o, n);
  2422. free(copy);
  2423. if (DEBUG_GLOB)
  2424. debug_print_list("perform_glob returning", o, n);
  2425. return n;
  2426. }
  2427. #else /* !HUSH_BRACE_EXPANSION */
  2428. /* Helper */
  2429. static int glob_needed(const char *s)
  2430. {
  2431. while (*s) {
  2432. if (*s == '\\') {
  2433. if (!s[1])
  2434. return 0;
  2435. s += 2;
  2436. continue;
  2437. }
  2438. if (*s == '*' || *s == '[' || *s == '?')
  2439. return 1;
  2440. s++;
  2441. }
  2442. return 0;
  2443. }
  2444. /* Performs globbing on last list[],
  2445. * saving each result as a new list[].
  2446. */
  2447. static int perform_glob(o_string *o, int n)
  2448. {
  2449. glob_t globdata;
  2450. int gr;
  2451. char *pattern;
  2452. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  2453. if (!o->data)
  2454. return o_save_ptr_helper(o, n);
  2455. pattern = o->data + o_get_last_ptr(o, n);
  2456. debug_printf_glob("glob pattern '%s'\n", pattern);
  2457. if (!glob_needed(pattern)) {
  2458. literal:
  2459. /* unbackslash last string in o in place, fix length */
  2460. o->length = unbackslash(pattern) - o->data;
  2461. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2462. return o_save_ptr_helper(o, n);
  2463. }
  2464. memset(&globdata, 0, sizeof(globdata));
  2465. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  2466. * If we glob "*.\*" and don't find anything, we need
  2467. * to fall back to using literal "*.*", but GLOB_NOCHECK
  2468. * will return "*.\*"!
  2469. */
  2470. gr = glob(pattern, 0, NULL, &globdata);
  2471. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  2472. if (gr != 0) {
  2473. if (gr == GLOB_NOMATCH) {
  2474. globfree(&globdata);
  2475. goto literal;
  2476. }
  2477. if (gr == GLOB_NOSPACE)
  2478. bb_error_msg_and_die(bb_msg_memory_exhausted);
  2479. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  2480. * but we didn't specify it. Paranoia again. */
  2481. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  2482. }
  2483. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  2484. char **argv = globdata.gl_pathv;
  2485. /* "forget" pattern in o */
  2486. o->length = pattern - o->data;
  2487. while (1) {
  2488. o_addstr_with_NUL(o, *argv);
  2489. n = o_save_ptr_helper(o, n);
  2490. argv++;
  2491. if (!*argv)
  2492. break;
  2493. }
  2494. }
  2495. globfree(&globdata);
  2496. if (DEBUG_GLOB)
  2497. debug_print_list("perform_glob returning", o, n);
  2498. return n;
  2499. }
  2500. #endif /* !HUSH_BRACE_EXPANSION */
  2501. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  2502. * Otherwise, just finish current list[] and start new */
  2503. static int o_save_ptr(o_string *o, int n)
  2504. {
  2505. if (o->o_expflags & EXP_FLAG_GLOB) {
  2506. /* If o->has_empty_slot, list[n] was already globbed
  2507. * (if it was requested back then when it was filled)
  2508. * so don't do that again! */
  2509. if (!o->has_empty_slot)
  2510. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  2511. }
  2512. return o_save_ptr_helper(o, n);
  2513. }
  2514. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  2515. static char **o_finalize_list(o_string *o, int n)
  2516. {
  2517. char **list;
  2518. int string_start;
  2519. n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
  2520. if (DEBUG_EXPAND)
  2521. debug_print_list("finalized", o, n);
  2522. debug_printf_expand("finalized n:%d\n", n);
  2523. list = (char**)o->data;
  2524. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2525. list[--n] = NULL;
  2526. while (n) {
  2527. n--;
  2528. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  2529. }
  2530. return list;
  2531. }
  2532. static void free_pipe_list(struct pipe *pi);
  2533. /* Returns pi->next - next pipe in the list */
  2534. static struct pipe *free_pipe(struct pipe *pi)
  2535. {
  2536. struct pipe *next;
  2537. int i;
  2538. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  2539. for (i = 0; i < pi->num_cmds; i++) {
  2540. struct command *command;
  2541. struct redir_struct *r, *rnext;
  2542. command = &pi->cmds[i];
  2543. debug_printf_clean(" command %d:\n", i);
  2544. if (command->argv) {
  2545. if (DEBUG_CLEAN) {
  2546. int a;
  2547. char **p;
  2548. for (a = 0, p = command->argv; *p; a++, p++) {
  2549. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  2550. }
  2551. }
  2552. free_strings(command->argv);
  2553. //command->argv = NULL;
  2554. }
  2555. /* not "else if": on syntax error, we may have both! */
  2556. if (command->group) {
  2557. debug_printf_clean(" begin group (cmd_type:%d)\n",
  2558. command->cmd_type);
  2559. free_pipe_list(command->group);
  2560. debug_printf_clean(" end group\n");
  2561. //command->group = NULL;
  2562. }
  2563. /* else is crucial here.
  2564. * If group != NULL, child_func is meaningless */
  2565. #if ENABLE_HUSH_FUNCTIONS
  2566. else if (command->child_func) {
  2567. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  2568. command->child_func->parent_cmd = NULL;
  2569. }
  2570. #endif
  2571. #if !BB_MMU
  2572. free(command->group_as_string);
  2573. //command->group_as_string = NULL;
  2574. #endif
  2575. for (r = command->redirects; r; r = rnext) {
  2576. debug_printf_clean(" redirect %d%s",
  2577. r->rd_fd, redir_table[r->rd_type].descrip);
  2578. /* guard against the case >$FOO, where foo is unset or blank */
  2579. if (r->rd_filename) {
  2580. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  2581. free(r->rd_filename);
  2582. //r->rd_filename = NULL;
  2583. }
  2584. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  2585. rnext = r->next;
  2586. free(r);
  2587. }
  2588. //command->redirects = NULL;
  2589. }
  2590. free(pi->cmds); /* children are an array, they get freed all at once */
  2591. //pi->cmds = NULL;
  2592. #if ENABLE_HUSH_JOB
  2593. free(pi->cmdtext);
  2594. //pi->cmdtext = NULL;
  2595. #endif
  2596. next = pi->next;
  2597. free(pi);
  2598. return next;
  2599. }
  2600. static void free_pipe_list(struct pipe *pi)
  2601. {
  2602. while (pi) {
  2603. #if HAS_KEYWORDS
  2604. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  2605. #endif
  2606. debug_printf_clean("pipe followup code %d\n", pi->followup);
  2607. pi = free_pipe(pi);
  2608. }
  2609. }
  2610. /*** Parsing routines ***/
  2611. #ifndef debug_print_tree
  2612. static void debug_print_tree(struct pipe *pi, int lvl)
  2613. {
  2614. static const char *const PIPE[] = {
  2615. [PIPE_SEQ] = "SEQ",
  2616. [PIPE_AND] = "AND",
  2617. [PIPE_OR ] = "OR" ,
  2618. [PIPE_BG ] = "BG" ,
  2619. };
  2620. static const char *RES[] = {
  2621. [RES_NONE ] = "NONE" ,
  2622. # if ENABLE_HUSH_IF
  2623. [RES_IF ] = "IF" ,
  2624. [RES_THEN ] = "THEN" ,
  2625. [RES_ELIF ] = "ELIF" ,
  2626. [RES_ELSE ] = "ELSE" ,
  2627. [RES_FI ] = "FI" ,
  2628. # endif
  2629. # if ENABLE_HUSH_LOOPS
  2630. [RES_FOR ] = "FOR" ,
  2631. [RES_WHILE] = "WHILE",
  2632. [RES_UNTIL] = "UNTIL",
  2633. [RES_DO ] = "DO" ,
  2634. [RES_DONE ] = "DONE" ,
  2635. # endif
  2636. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  2637. [RES_IN ] = "IN" ,
  2638. # endif
  2639. # if ENABLE_HUSH_CASE
  2640. [RES_CASE ] = "CASE" ,
  2641. [RES_CASE_IN ] = "CASE_IN" ,
  2642. [RES_MATCH] = "MATCH",
  2643. [RES_CASE_BODY] = "CASE_BODY",
  2644. [RES_ESAC ] = "ESAC" ,
  2645. # endif
  2646. [RES_XXXX ] = "XXXX" ,
  2647. [RES_SNTX ] = "SNTX" ,
  2648. };
  2649. static const char *const CMDTYPE[] = {
  2650. "{}",
  2651. "()",
  2652. "[noglob]",
  2653. # if ENABLE_HUSH_FUNCTIONS
  2654. "func()",
  2655. # endif
  2656. };
  2657. int pin, prn;
  2658. pin = 0;
  2659. while (pi) {
  2660. fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
  2661. pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
  2662. prn = 0;
  2663. while (prn < pi->num_cmds) {
  2664. struct command *command = &pi->cmds[prn];
  2665. char **argv = command->argv;
  2666. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  2667. lvl*2, "", prn,
  2668. command->assignment_cnt);
  2669. if (command->group) {
  2670. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  2671. CMDTYPE[command->cmd_type],
  2672. argv
  2673. # if !BB_MMU
  2674. , " group_as_string:", command->group_as_string
  2675. # else
  2676. , "", ""
  2677. # endif
  2678. );
  2679. debug_print_tree(command->group, lvl+1);
  2680. prn++;
  2681. continue;
  2682. }
  2683. if (argv) while (*argv) {
  2684. fdprintf(2, " '%s'", *argv);
  2685. argv++;
  2686. }
  2687. fdprintf(2, "\n");
  2688. prn++;
  2689. }
  2690. pi = pi->next;
  2691. pin++;
  2692. }
  2693. }
  2694. #endif /* debug_print_tree */
  2695. static struct pipe *new_pipe(void)
  2696. {
  2697. struct pipe *pi;
  2698. pi = xzalloc(sizeof(struct pipe));
  2699. /*pi->followup = 0; - deliberately invalid value */
  2700. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  2701. return pi;
  2702. }
  2703. /* Command (member of a pipe) is complete, or we start a new pipe
  2704. * if ctx->command is NULL.
  2705. * No errors possible here.
  2706. */
  2707. static int done_command(struct parse_context *ctx)
  2708. {
  2709. /* The command is really already in the pipe structure, so
  2710. * advance the pipe counter and make a new, null command. */
  2711. struct pipe *pi = ctx->pipe;
  2712. struct command *command = ctx->command;
  2713. if (command) {
  2714. if (IS_NULL_CMD(command)) {
  2715. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  2716. goto clear_and_ret;
  2717. }
  2718. pi->num_cmds++;
  2719. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  2720. //debug_print_tree(ctx->list_head, 20);
  2721. } else {
  2722. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  2723. }
  2724. /* Only real trickiness here is that the uncommitted
  2725. * command structure is not counted in pi->num_cmds. */
  2726. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  2727. ctx->command = command = &pi->cmds[pi->num_cmds];
  2728. clear_and_ret:
  2729. memset(command, 0, sizeof(*command));
  2730. return pi->num_cmds; /* used only for 0/nonzero check */
  2731. }
  2732. static void done_pipe(struct parse_context *ctx, pipe_style type)
  2733. {
  2734. int not_null;
  2735. debug_printf_parse("done_pipe entered, followup %d\n", type);
  2736. /* Close previous command */
  2737. not_null = done_command(ctx);
  2738. ctx->pipe->followup = type;
  2739. #if HAS_KEYWORDS
  2740. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  2741. ctx->ctx_inverted = 0;
  2742. ctx->pipe->res_word = ctx->ctx_res_w;
  2743. #endif
  2744. /* Without this check, even just <enter> on command line generates
  2745. * tree of three NOPs (!). Which is harmless but annoying.
  2746. * IOW: it is safe to do it unconditionally. */
  2747. if (not_null
  2748. #if ENABLE_HUSH_IF
  2749. || ctx->ctx_res_w == RES_FI
  2750. #endif
  2751. #if ENABLE_HUSH_LOOPS
  2752. || ctx->ctx_res_w == RES_DONE
  2753. || ctx->ctx_res_w == RES_FOR
  2754. || ctx->ctx_res_w == RES_IN
  2755. #endif
  2756. #if ENABLE_HUSH_CASE
  2757. || ctx->ctx_res_w == RES_ESAC
  2758. #endif
  2759. ) {
  2760. struct pipe *new_p;
  2761. debug_printf_parse("done_pipe: adding new pipe: "
  2762. "not_null:%d ctx->ctx_res_w:%d\n",
  2763. not_null, ctx->ctx_res_w);
  2764. new_p = new_pipe();
  2765. ctx->pipe->next = new_p;
  2766. ctx->pipe = new_p;
  2767. /* RES_THEN, RES_DO etc are "sticky" -
  2768. * they remain set for pipes inside if/while.
  2769. * This is used to control execution.
  2770. * RES_FOR and RES_IN are NOT sticky (needed to support
  2771. * cases where variable or value happens to match a keyword):
  2772. */
  2773. #if ENABLE_HUSH_LOOPS
  2774. if (ctx->ctx_res_w == RES_FOR
  2775. || ctx->ctx_res_w == RES_IN)
  2776. ctx->ctx_res_w = RES_NONE;
  2777. #endif
  2778. #if ENABLE_HUSH_CASE
  2779. if (ctx->ctx_res_w == RES_MATCH)
  2780. ctx->ctx_res_w = RES_CASE_BODY;
  2781. if (ctx->ctx_res_w == RES_CASE)
  2782. ctx->ctx_res_w = RES_CASE_IN;
  2783. #endif
  2784. ctx->command = NULL; /* trick done_command below */
  2785. /* Create the memory for command, roughly:
  2786. * ctx->pipe->cmds = new struct command;
  2787. * ctx->command = &ctx->pipe->cmds[0];
  2788. */
  2789. done_command(ctx);
  2790. //debug_print_tree(ctx->list_head, 10);
  2791. }
  2792. debug_printf_parse("done_pipe return\n");
  2793. }
  2794. static void initialize_context(struct parse_context *ctx)
  2795. {
  2796. memset(ctx, 0, sizeof(*ctx));
  2797. ctx->pipe = ctx->list_head = new_pipe();
  2798. /* Create the memory for command, roughly:
  2799. * ctx->pipe->cmds = new struct command;
  2800. * ctx->command = &ctx->pipe->cmds[0];
  2801. */
  2802. done_command(ctx);
  2803. }
  2804. /* If a reserved word is found and processed, parse context is modified
  2805. * and 1 is returned.
  2806. */
  2807. #if HAS_KEYWORDS
  2808. struct reserved_combo {
  2809. char literal[6];
  2810. unsigned char res;
  2811. unsigned char assignment_flag;
  2812. int flag;
  2813. };
  2814. enum {
  2815. FLAG_END = (1 << RES_NONE ),
  2816. # if ENABLE_HUSH_IF
  2817. FLAG_IF = (1 << RES_IF ),
  2818. FLAG_THEN = (1 << RES_THEN ),
  2819. FLAG_ELIF = (1 << RES_ELIF ),
  2820. FLAG_ELSE = (1 << RES_ELSE ),
  2821. FLAG_FI = (1 << RES_FI ),
  2822. # endif
  2823. # if ENABLE_HUSH_LOOPS
  2824. FLAG_FOR = (1 << RES_FOR ),
  2825. FLAG_WHILE = (1 << RES_WHILE),
  2826. FLAG_UNTIL = (1 << RES_UNTIL),
  2827. FLAG_DO = (1 << RES_DO ),
  2828. FLAG_DONE = (1 << RES_DONE ),
  2829. FLAG_IN = (1 << RES_IN ),
  2830. # endif
  2831. # if ENABLE_HUSH_CASE
  2832. FLAG_MATCH = (1 << RES_MATCH),
  2833. FLAG_ESAC = (1 << RES_ESAC ),
  2834. # endif
  2835. FLAG_START = (1 << RES_XXXX ),
  2836. };
  2837. static const struct reserved_combo* match_reserved_word(o_string *word)
  2838. {
  2839. /* Mostly a list of accepted follow-up reserved words.
  2840. * FLAG_END means we are done with the sequence, and are ready
  2841. * to turn the compound list into a command.
  2842. * FLAG_START means the word must start a new compound list.
  2843. */
  2844. static const struct reserved_combo reserved_list[] = {
  2845. # if ENABLE_HUSH_IF
  2846. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  2847. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  2848. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  2849. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  2850. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  2851. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  2852. # endif
  2853. # if ENABLE_HUSH_LOOPS
  2854. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  2855. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  2856. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  2857. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  2858. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  2859. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  2860. # endif
  2861. # if ENABLE_HUSH_CASE
  2862. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  2863. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  2864. # endif
  2865. };
  2866. const struct reserved_combo *r;
  2867. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  2868. if (strcmp(word->data, r->literal) == 0)
  2869. return r;
  2870. }
  2871. return NULL;
  2872. }
  2873. /* Return 0: not a keyword, 1: keyword
  2874. */
  2875. static int reserved_word(o_string *word, struct parse_context *ctx)
  2876. {
  2877. # if ENABLE_HUSH_CASE
  2878. static const struct reserved_combo reserved_match = {
  2879. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  2880. };
  2881. # endif
  2882. const struct reserved_combo *r;
  2883. if (word->has_quoted_part)
  2884. return 0;
  2885. r = match_reserved_word(word);
  2886. if (!r)
  2887. return 0;
  2888. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  2889. # if ENABLE_HUSH_CASE
  2890. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  2891. /* "case word IN ..." - IN part starts first MATCH part */
  2892. r = &reserved_match;
  2893. } else
  2894. # endif
  2895. if (r->flag == 0) { /* '!' */
  2896. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  2897. syntax_error("! ! command");
  2898. ctx->ctx_res_w = RES_SNTX;
  2899. }
  2900. ctx->ctx_inverted = 1;
  2901. return 1;
  2902. }
  2903. if (r->flag & FLAG_START) {
  2904. struct parse_context *old;
  2905. old = xmalloc(sizeof(*old));
  2906. debug_printf_parse("push stack %p\n", old);
  2907. *old = *ctx; /* physical copy */
  2908. initialize_context(ctx);
  2909. ctx->stack = old;
  2910. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  2911. syntax_error_at(word->data);
  2912. ctx->ctx_res_w = RES_SNTX;
  2913. return 1;
  2914. } else {
  2915. /* "{...} fi" is ok. "{...} if" is not
  2916. * Example:
  2917. * if { echo foo; } then { echo bar; } fi */
  2918. if (ctx->command->group)
  2919. done_pipe(ctx, PIPE_SEQ);
  2920. }
  2921. ctx->ctx_res_w = r->res;
  2922. ctx->old_flag = r->flag;
  2923. word->o_assignment = r->assignment_flag;
  2924. debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
  2925. if (ctx->old_flag & FLAG_END) {
  2926. struct parse_context *old;
  2927. done_pipe(ctx, PIPE_SEQ);
  2928. debug_printf_parse("pop stack %p\n", ctx->stack);
  2929. old = ctx->stack;
  2930. old->command->group = ctx->list_head;
  2931. old->command->cmd_type = CMD_NORMAL;
  2932. # if !BB_MMU
  2933. o_addstr(&old->as_string, ctx->as_string.data);
  2934. o_free_unsafe(&ctx->as_string);
  2935. old->command->group_as_string = xstrdup(old->as_string.data);
  2936. debug_printf_parse("pop, remembering as:'%s'\n",
  2937. old->command->group_as_string);
  2938. # endif
  2939. *ctx = *old; /* physical copy */
  2940. free(old);
  2941. }
  2942. return 1;
  2943. }
  2944. #endif /* HAS_KEYWORDS */
  2945. /* Word is complete, look at it and update parsing context.
  2946. * Normal return is 0. Syntax errors return 1.
  2947. * Note: on return, word is reset, but not o_free'd!
  2948. */
  2949. static int done_word(o_string *word, struct parse_context *ctx)
  2950. {
  2951. struct command *command = ctx->command;
  2952. debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
  2953. if (word->length == 0 && !word->has_quoted_part) {
  2954. debug_printf_parse("done_word return 0: true null, ignored\n");
  2955. return 0;
  2956. }
  2957. if (ctx->pending_redirect) {
  2958. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  2959. * only if run as "bash", not "sh" */
  2960. /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  2961. * "2.7 Redirection
  2962. * ...the word that follows the redirection operator
  2963. * shall be subjected to tilde expansion, parameter expansion,
  2964. * command substitution, arithmetic expansion, and quote
  2965. * removal. Pathname expansion shall not be performed
  2966. * on the word by a non-interactive shell; an interactive
  2967. * shell may perform it, but shall do so only when
  2968. * the expansion would result in one word."
  2969. */
  2970. ctx->pending_redirect->rd_filename = xstrdup(word->data);
  2971. /* Cater for >\file case:
  2972. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  2973. * Same with heredocs:
  2974. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  2975. */
  2976. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  2977. unbackslash(ctx->pending_redirect->rd_filename);
  2978. /* Is it <<"HEREDOC"? */
  2979. if (word->has_quoted_part) {
  2980. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  2981. }
  2982. }
  2983. debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
  2984. ctx->pending_redirect = NULL;
  2985. } else {
  2986. #if HAS_KEYWORDS
  2987. # if ENABLE_HUSH_CASE
  2988. if (ctx->ctx_dsemicolon
  2989. && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  2990. ) {
  2991. /* already done when ctx_dsemicolon was set to 1: */
  2992. /* ctx->ctx_res_w = RES_MATCH; */
  2993. ctx->ctx_dsemicolon = 0;
  2994. } else
  2995. # endif
  2996. if (!command->argv /* if it's the first word... */
  2997. # if ENABLE_HUSH_LOOPS
  2998. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  2999. && ctx->ctx_res_w != RES_IN
  3000. # endif
  3001. # if ENABLE_HUSH_CASE
  3002. && ctx->ctx_res_w != RES_CASE
  3003. # endif
  3004. ) {
  3005. int reserved = reserved_word(word, ctx);
  3006. debug_printf_parse("checking for reserved-ness: %d\n", reserved);
  3007. if (reserved) {
  3008. o_reset_to_empty_unquoted(word);
  3009. debug_printf_parse("done_word return %d\n",
  3010. (ctx->ctx_res_w == RES_SNTX));
  3011. return (ctx->ctx_res_w == RES_SNTX);
  3012. }
  3013. # if ENABLE_HUSH_BASH_COMPAT
  3014. if (strcmp(word->data, "[[") == 0) {
  3015. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3016. }
  3017. /* fall through */
  3018. # endif
  3019. }
  3020. #endif
  3021. if (command->group) {
  3022. /* "{ echo foo; } echo bar" - bad */
  3023. syntax_error_at(word->data);
  3024. debug_printf_parse("done_word return 1: syntax error, "
  3025. "groups and arglists don't mix\n");
  3026. return 1;
  3027. }
  3028. /* If this word wasn't an assignment, next ones definitely
  3029. * can't be assignments. Even if they look like ones. */
  3030. if (word->o_assignment != DEFINITELY_ASSIGNMENT
  3031. && word->o_assignment != WORD_IS_KEYWORD
  3032. ) {
  3033. word->o_assignment = NOT_ASSIGNMENT;
  3034. } else {
  3035. if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
  3036. command->assignment_cnt++;
  3037. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3038. }
  3039. debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
  3040. word->o_assignment = MAYBE_ASSIGNMENT;
  3041. }
  3042. debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
  3043. if (word->has_quoted_part
  3044. /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
  3045. && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
  3046. /* (otherwise it's known to be not empty and is already safe) */
  3047. ) {
  3048. /* exclude "$@" - it can expand to no word despite "" */
  3049. char *p = word->data;
  3050. while (p[0] == SPECIAL_VAR_SYMBOL
  3051. && (p[1] & 0x7f) == '@'
  3052. && p[2] == SPECIAL_VAR_SYMBOL
  3053. ) {
  3054. p += 3;
  3055. }
  3056. }
  3057. command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
  3058. debug_print_strings("word appended to argv", command->argv);
  3059. }
  3060. #if ENABLE_HUSH_LOOPS
  3061. if (ctx->ctx_res_w == RES_FOR) {
  3062. if (word->has_quoted_part
  3063. || !is_well_formed_var_name(command->argv[0], '\0')
  3064. ) {
  3065. /* bash says just "not a valid identifier" */
  3066. syntax_error("not a valid identifier in for");
  3067. return 1;
  3068. }
  3069. /* Force FOR to have just one word (variable name) */
  3070. /* NB: basically, this makes hush see "for v in ..."
  3071. * syntax as if it is "for v; in ...". FOR and IN become
  3072. * two pipe structs in parse tree. */
  3073. done_pipe(ctx, PIPE_SEQ);
  3074. }
  3075. #endif
  3076. #if ENABLE_HUSH_CASE
  3077. /* Force CASE to have just one word */
  3078. if (ctx->ctx_res_w == RES_CASE) {
  3079. done_pipe(ctx, PIPE_SEQ);
  3080. }
  3081. #endif
  3082. o_reset_to_empty_unquoted(word);
  3083. debug_printf_parse("done_word return 0\n");
  3084. return 0;
  3085. }
  3086. /* Peek ahead in the input to find out if we have a "&n" construct,
  3087. * as in "2>&1", that represents duplicating a file descriptor.
  3088. * Return:
  3089. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3090. * REDIRFD_SYNTAX_ERR if syntax error,
  3091. * REDIRFD_TO_FILE if no & was seen,
  3092. * or the number found.
  3093. */
  3094. #if BB_MMU
  3095. #define parse_redir_right_fd(as_string, input) \
  3096. parse_redir_right_fd(input)
  3097. #endif
  3098. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3099. {
  3100. int ch, d, ok;
  3101. ch = i_peek(input);
  3102. if (ch != '&')
  3103. return REDIRFD_TO_FILE;
  3104. ch = i_getch(input); /* get the & */
  3105. nommu_addchr(as_string, ch);
  3106. ch = i_peek(input);
  3107. if (ch == '-') {
  3108. ch = i_getch(input);
  3109. nommu_addchr(as_string, ch);
  3110. return REDIRFD_CLOSE;
  3111. }
  3112. d = 0;
  3113. ok = 0;
  3114. while (ch != EOF && isdigit(ch)) {
  3115. d = d*10 + (ch-'0');
  3116. ok = 1;
  3117. ch = i_getch(input);
  3118. nommu_addchr(as_string, ch);
  3119. ch = i_peek(input);
  3120. }
  3121. if (ok) return d;
  3122. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3123. bb_error_msg("ambiguous redirect");
  3124. return REDIRFD_SYNTAX_ERR;
  3125. }
  3126. /* Return code is 0 normal, 1 if a syntax error is detected
  3127. */
  3128. static int parse_redirect(struct parse_context *ctx,
  3129. int fd,
  3130. redir_type style,
  3131. struct in_str *input)
  3132. {
  3133. struct command *command = ctx->command;
  3134. struct redir_struct *redir;
  3135. struct redir_struct **redirp;
  3136. int dup_num;
  3137. dup_num = REDIRFD_TO_FILE;
  3138. if (style != REDIRECT_HEREDOC) {
  3139. /* Check for a '>&1' type redirect */
  3140. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3141. if (dup_num == REDIRFD_SYNTAX_ERR)
  3142. return 1;
  3143. } else {
  3144. int ch = i_peek(input);
  3145. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3146. if (dup_num) { /* <<-... */
  3147. ch = i_getch(input);
  3148. nommu_addchr(&ctx->as_string, ch);
  3149. ch = i_peek(input);
  3150. }
  3151. }
  3152. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3153. int ch = i_peek(input);
  3154. if (ch == '|') {
  3155. /* >|FILE redirect ("clobbering" >).
  3156. * Since we do not support "set -o noclobber" yet,
  3157. * >| and > are the same for now. Just eat |.
  3158. */
  3159. ch = i_getch(input);
  3160. nommu_addchr(&ctx->as_string, ch);
  3161. }
  3162. }
  3163. /* Create a new redir_struct and append it to the linked list */
  3164. redirp = &command->redirects;
  3165. while ((redir = *redirp) != NULL) {
  3166. redirp = &(redir->next);
  3167. }
  3168. *redirp = redir = xzalloc(sizeof(*redir));
  3169. /* redir->next = NULL; */
  3170. /* redir->rd_filename = NULL; */
  3171. redir->rd_type = style;
  3172. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  3173. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  3174. redir_table[style].descrip);
  3175. redir->rd_dup = dup_num;
  3176. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  3177. /* Erik had a check here that the file descriptor in question
  3178. * is legit; I postpone that to "run time"
  3179. * A "-" representation of "close me" shows up as a -3 here */
  3180. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  3181. redir->rd_fd, redir->rd_dup);
  3182. } else {
  3183. /* Set ctx->pending_redirect, so we know what to do at the
  3184. * end of the next parsed word. */
  3185. ctx->pending_redirect = redir;
  3186. }
  3187. return 0;
  3188. }
  3189. /* If a redirect is immediately preceded by a number, that number is
  3190. * supposed to tell which file descriptor to redirect. This routine
  3191. * looks for such preceding numbers. In an ideal world this routine
  3192. * needs to handle all the following classes of redirects...
  3193. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  3194. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  3195. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  3196. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  3197. *
  3198. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  3199. * "2.7 Redirection
  3200. * ... If n is quoted, the number shall not be recognized as part of
  3201. * the redirection expression. For example:
  3202. * echo \2>a
  3203. * writes the character 2 into file a"
  3204. * We are getting it right by setting ->has_quoted_part on any \<char>
  3205. *
  3206. * A -1 return means no valid number was found,
  3207. * the caller should use the appropriate default for this redirection.
  3208. */
  3209. static int redirect_opt_num(o_string *o)
  3210. {
  3211. int num;
  3212. if (o->data == NULL)
  3213. return -1;
  3214. num = bb_strtou(o->data, NULL, 10);
  3215. if (errno || num < 0)
  3216. return -1;
  3217. o_reset_to_empty_unquoted(o);
  3218. return num;
  3219. }
  3220. #if BB_MMU
  3221. #define fetch_till_str(as_string, input, word, skip_tabs) \
  3222. fetch_till_str(input, word, skip_tabs)
  3223. #endif
  3224. static char *fetch_till_str(o_string *as_string,
  3225. struct in_str *input,
  3226. const char *word,
  3227. int heredoc_flags)
  3228. {
  3229. o_string heredoc = NULL_O_STRING;
  3230. unsigned past_EOL;
  3231. int prev = 0; /* not \ */
  3232. int ch;
  3233. goto jump_in;
  3234. while (1) {
  3235. ch = i_getch(input);
  3236. if (ch != EOF)
  3237. nommu_addchr(as_string, ch);
  3238. if ((ch == '\n' || ch == EOF)
  3239. && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
  3240. ) {
  3241. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  3242. heredoc.data[past_EOL] = '\0';
  3243. debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
  3244. return heredoc.data;
  3245. }
  3246. while (ch == '\n') {
  3247. o_addchr(&heredoc, ch);
  3248. prev = ch;
  3249. jump_in:
  3250. past_EOL = heredoc.length;
  3251. do {
  3252. ch = i_getch(input);
  3253. if (ch != EOF)
  3254. nommu_addchr(as_string, ch);
  3255. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  3256. }
  3257. }
  3258. if (ch == EOF) {
  3259. o_free_unsafe(&heredoc);
  3260. return NULL;
  3261. }
  3262. o_addchr(&heredoc, ch);
  3263. nommu_addchr(as_string, ch);
  3264. if (prev == '\\' && ch == '\\')
  3265. /* Correctly handle foo\\<eol> (not a line cont.) */
  3266. prev = 0; /* not \ */
  3267. else
  3268. prev = ch;
  3269. }
  3270. }
  3271. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  3272. * and load them all. There should be exactly heredoc_cnt of them.
  3273. */
  3274. static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
  3275. {
  3276. struct pipe *pi = ctx->list_head;
  3277. while (pi && heredoc_cnt) {
  3278. int i;
  3279. struct command *cmd = pi->cmds;
  3280. debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  3281. pi->num_cmds,
  3282. cmd->argv ? cmd->argv[0] : "NONE");
  3283. for (i = 0; i < pi->num_cmds; i++) {
  3284. struct redir_struct *redir = cmd->redirects;
  3285. debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
  3286. i, cmd->argv ? cmd->argv[0] : "NONE");
  3287. while (redir) {
  3288. if (redir->rd_type == REDIRECT_HEREDOC) {
  3289. char *p;
  3290. redir->rd_type = REDIRECT_HEREDOC2;
  3291. /* redir->rd_dup is (ab)used to indicate <<- */
  3292. p = fetch_till_str(&ctx->as_string, input,
  3293. redir->rd_filename, redir->rd_dup);
  3294. if (!p) {
  3295. syntax_error("unexpected EOF in here document");
  3296. return 1;
  3297. }
  3298. free(redir->rd_filename);
  3299. redir->rd_filename = p;
  3300. heredoc_cnt--;
  3301. }
  3302. redir = redir->next;
  3303. }
  3304. cmd++;
  3305. }
  3306. pi = pi->next;
  3307. }
  3308. #if 0
  3309. /* Should be 0. If it isn't, it's a parse error */
  3310. if (heredoc_cnt)
  3311. bb_error_msg_and_die("heredoc BUG 2");
  3312. #endif
  3313. return 0;
  3314. }
  3315. static int run_list(struct pipe *pi);
  3316. #if BB_MMU
  3317. #define parse_stream(pstring, input, end_trigger) \
  3318. parse_stream(input, end_trigger)
  3319. #endif
  3320. static struct pipe *parse_stream(char **pstring,
  3321. struct in_str *input,
  3322. int end_trigger);
  3323. #if !ENABLE_HUSH_FUNCTIONS
  3324. #define parse_group(dest, ctx, input, ch) \
  3325. parse_group(ctx, input, ch)
  3326. #endif
  3327. static int parse_group(o_string *dest, struct parse_context *ctx,
  3328. struct in_str *input, int ch)
  3329. {
  3330. /* dest contains characters seen prior to ( or {.
  3331. * Typically it's empty, but for function defs,
  3332. * it contains function name (without '()'). */
  3333. struct pipe *pipe_list;
  3334. int endch;
  3335. struct command *command = ctx->command;
  3336. debug_printf_parse("parse_group entered\n");
  3337. #if ENABLE_HUSH_FUNCTIONS
  3338. if (ch == '(' && !dest->has_quoted_part) {
  3339. if (dest->length)
  3340. if (done_word(dest, ctx))
  3341. return 1;
  3342. if (!command->argv)
  3343. goto skip; /* (... */
  3344. if (command->argv[1]) { /* word word ... (... */
  3345. syntax_error_unexpected_ch('(');
  3346. return 1;
  3347. }
  3348. /* it is "word(..." or "word (..." */
  3349. do
  3350. ch = i_getch(input);
  3351. while (ch == ' ' || ch == '\t');
  3352. if (ch != ')') {
  3353. syntax_error_unexpected_ch(ch);
  3354. return 1;
  3355. }
  3356. nommu_addchr(&ctx->as_string, ch);
  3357. do
  3358. ch = i_getch(input);
  3359. while (ch == ' ' || ch == '\t' || ch == '\n');
  3360. if (ch != '{') {
  3361. syntax_error_unexpected_ch(ch);
  3362. return 1;
  3363. }
  3364. nommu_addchr(&ctx->as_string, ch);
  3365. command->cmd_type = CMD_FUNCDEF;
  3366. goto skip;
  3367. }
  3368. #endif
  3369. #if 0 /* Prevented by caller */
  3370. if (command->argv /* word [word]{... */
  3371. || dest->length /* word{... */
  3372. || dest->has_quoted_part /* ""{... */
  3373. ) {
  3374. syntax_error(NULL);
  3375. debug_printf_parse("parse_group return 1: "
  3376. "syntax error, groups and arglists don't mix\n");
  3377. return 1;
  3378. }
  3379. #endif
  3380. #if ENABLE_HUSH_FUNCTIONS
  3381. skip:
  3382. #endif
  3383. endch = '}';
  3384. if (ch == '(') {
  3385. endch = ')';
  3386. command->cmd_type = CMD_SUBSHELL;
  3387. } else {
  3388. /* bash does not allow "{echo...", requires whitespace */
  3389. ch = i_getch(input);
  3390. if (ch != ' ' && ch != '\t' && ch != '\n') {
  3391. syntax_error_unexpected_ch(ch);
  3392. return 1;
  3393. }
  3394. nommu_addchr(&ctx->as_string, ch);
  3395. }
  3396. {
  3397. #if BB_MMU
  3398. # define as_string NULL
  3399. #else
  3400. char *as_string = NULL;
  3401. #endif
  3402. pipe_list = parse_stream(&as_string, input, endch);
  3403. #if !BB_MMU
  3404. if (as_string)
  3405. o_addstr(&ctx->as_string, as_string);
  3406. #endif
  3407. /* empty ()/{} or parse error? */
  3408. if (!pipe_list || pipe_list == ERR_PTR) {
  3409. /* parse_stream already emitted error msg */
  3410. if (!BB_MMU)
  3411. free(as_string);
  3412. debug_printf_parse("parse_group return 1: "
  3413. "parse_stream returned %p\n", pipe_list);
  3414. return 1;
  3415. }
  3416. command->group = pipe_list;
  3417. #if !BB_MMU
  3418. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  3419. command->group_as_string = as_string;
  3420. debug_printf_parse("end of group, remembering as:'%s'\n",
  3421. command->group_as_string);
  3422. #endif
  3423. #undef as_string
  3424. }
  3425. debug_printf_parse("parse_group return 0\n");
  3426. return 0;
  3427. /* command remains "open", available for possible redirects */
  3428. }
  3429. #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
  3430. /* Subroutines for copying $(...) and `...` things */
  3431. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  3432. /* '...' */
  3433. static int add_till_single_quote(o_string *dest, struct in_str *input)
  3434. {
  3435. while (1) {
  3436. int ch = i_getch(input);
  3437. if (ch == EOF) {
  3438. syntax_error_unterm_ch('\'');
  3439. return 0;
  3440. }
  3441. if (ch == '\'')
  3442. return 1;
  3443. o_addchr(dest, ch);
  3444. }
  3445. }
  3446. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  3447. static int add_till_double_quote(o_string *dest, struct in_str *input)
  3448. {
  3449. while (1) {
  3450. int ch = i_getch(input);
  3451. if (ch == EOF) {
  3452. syntax_error_unterm_ch('"');
  3453. return 0;
  3454. }
  3455. if (ch == '"')
  3456. return 1;
  3457. if (ch == '\\') { /* \x. Copy both chars. */
  3458. o_addchr(dest, ch);
  3459. ch = i_getch(input);
  3460. }
  3461. o_addchr(dest, ch);
  3462. if (ch == '`') {
  3463. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  3464. return 0;
  3465. o_addchr(dest, ch);
  3466. continue;
  3467. }
  3468. //if (ch == '$') ...
  3469. }
  3470. }
  3471. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  3472. * \` quoting.
  3473. * "Within the backquoted style of command substitution, backslash
  3474. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  3475. * The search for the matching backquote shall be satisfied by the first
  3476. * backquote found without a preceding backslash; during this search,
  3477. * if a non-escaped backquote is encountered within a shell comment,
  3478. * a here-document, an embedded command substitution of the $(command)
  3479. * form, or a quoted string, undefined results occur. A single-quoted
  3480. * or double-quoted string that begins, but does not end, within the
  3481. * "`...`" sequence produces undefined results."
  3482. * Example Output
  3483. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  3484. */
  3485. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  3486. {
  3487. while (1) {
  3488. int ch = i_getch(input);
  3489. if (ch == '`')
  3490. return 1;
  3491. if (ch == '\\') {
  3492. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  3493. ch = i_getch(input);
  3494. if (ch != '`'
  3495. && ch != '$'
  3496. && ch != '\\'
  3497. && (!in_dquote || ch != '"')
  3498. ) {
  3499. o_addchr(dest, '\\');
  3500. }
  3501. }
  3502. if (ch == EOF) {
  3503. syntax_error_unterm_ch('`');
  3504. return 0;
  3505. }
  3506. o_addchr(dest, ch);
  3507. }
  3508. }
  3509. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  3510. * quoting and nested ()s.
  3511. * "With the $(command) style of command substitution, all characters
  3512. * following the open parenthesis to the matching closing parenthesis
  3513. * constitute the command. Any valid shell script can be used for command,
  3514. * except a script consisting solely of redirections which produces
  3515. * unspecified results."
  3516. * Example Output
  3517. * echo $(echo '(TEST)' BEST) (TEST) BEST
  3518. * echo $(echo 'TEST)' BEST) TEST) BEST
  3519. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  3520. *
  3521. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  3522. * can contain arbitrary constructs, just like $(cmd).
  3523. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  3524. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  3525. */
  3526. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  3527. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  3528. {
  3529. int ch;
  3530. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  3531. # if ENABLE_HUSH_BASH_COMPAT
  3532. char end_char2 = end_ch >> 8;
  3533. # endif
  3534. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  3535. while (1) {
  3536. ch = i_getch(input);
  3537. if (ch == EOF) {
  3538. syntax_error_unterm_ch(end_ch);
  3539. return 0;
  3540. }
  3541. if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
  3542. if (!dbl)
  3543. break;
  3544. /* we look for closing )) of $((EXPR)) */
  3545. if (i_peek(input) == end_ch) {
  3546. i_getch(input); /* eat second ')' */
  3547. break;
  3548. }
  3549. }
  3550. o_addchr(dest, ch);
  3551. if (ch == '(' || ch == '{') {
  3552. ch = (ch == '(' ? ')' : '}');
  3553. if (!add_till_closing_bracket(dest, input, ch))
  3554. return 0;
  3555. o_addchr(dest, ch);
  3556. continue;
  3557. }
  3558. if (ch == '\'') {
  3559. if (!add_till_single_quote(dest, input))
  3560. return 0;
  3561. o_addchr(dest, ch);
  3562. continue;
  3563. }
  3564. if (ch == '"') {
  3565. if (!add_till_double_quote(dest, input))
  3566. return 0;
  3567. o_addchr(dest, ch);
  3568. continue;
  3569. }
  3570. if (ch == '`') {
  3571. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  3572. return 0;
  3573. o_addchr(dest, ch);
  3574. continue;
  3575. }
  3576. if (ch == '\\') {
  3577. /* \x. Copy verbatim. Important for \(, \) */
  3578. ch = i_getch(input);
  3579. if (ch == EOF) {
  3580. syntax_error_unterm_ch(')');
  3581. return 0;
  3582. }
  3583. o_addchr(dest, ch);
  3584. continue;
  3585. }
  3586. }
  3587. return ch;
  3588. }
  3589. #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
  3590. /* Return code: 0 for OK, 1 for syntax error */
  3591. #if BB_MMU
  3592. #define parse_dollar(as_string, dest, input, quote_mask) \
  3593. parse_dollar(dest, input, quote_mask)
  3594. #define as_string NULL
  3595. #endif
  3596. static int parse_dollar(o_string *as_string,
  3597. o_string *dest,
  3598. struct in_str *input, unsigned char quote_mask)
  3599. {
  3600. int ch = i_peek(input); /* first character after the $ */
  3601. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  3602. if (isalpha(ch)) {
  3603. ch = i_getch(input);
  3604. nommu_addchr(as_string, ch);
  3605. make_var:
  3606. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3607. while (1) {
  3608. debug_printf_parse(": '%c'\n", ch);
  3609. o_addchr(dest, ch | quote_mask);
  3610. quote_mask = 0;
  3611. ch = i_peek(input);
  3612. if (!isalnum(ch) && ch != '_')
  3613. break;
  3614. ch = i_getch(input);
  3615. nommu_addchr(as_string, ch);
  3616. }
  3617. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3618. } else if (isdigit(ch)) {
  3619. make_one_char_var:
  3620. ch = i_getch(input);
  3621. nommu_addchr(as_string, ch);
  3622. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3623. debug_printf_parse(": '%c'\n", ch);
  3624. o_addchr(dest, ch | quote_mask);
  3625. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3626. } else switch (ch) {
  3627. case '$': /* pid */
  3628. case '!': /* last bg pid */
  3629. case '?': /* last exit code */
  3630. case '#': /* number of args */
  3631. case '*': /* args */
  3632. case '@': /* args */
  3633. goto make_one_char_var;
  3634. case '{': {
  3635. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3636. ch = i_getch(input); /* eat '{' */
  3637. nommu_addchr(as_string, ch);
  3638. ch = i_getch(input); /* first char after '{' */
  3639. /* It should be ${?}, or ${#var},
  3640. * or even ${?+subst} - operator acting on a special variable,
  3641. * or the beginning of variable name.
  3642. */
  3643. if (ch == EOF
  3644. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  3645. ) {
  3646. bad_dollar_syntax:
  3647. syntax_error_unterm_str("${name}");
  3648. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  3649. return 0;
  3650. }
  3651. nommu_addchr(as_string, ch);
  3652. ch |= quote_mask;
  3653. /* It's possible to just call add_till_closing_bracket() at this point.
  3654. * However, this regresses some of our testsuite cases
  3655. * which check invalid constructs like ${%}.
  3656. * Oh well... let's check that the var name part is fine... */
  3657. while (1) {
  3658. unsigned pos;
  3659. o_addchr(dest, ch);
  3660. debug_printf_parse(": '%c'\n", ch);
  3661. ch = i_getch(input);
  3662. nommu_addchr(as_string, ch);
  3663. if (ch == '}')
  3664. break;
  3665. if (!isalnum(ch) && ch != '_') {
  3666. unsigned end_ch;
  3667. unsigned char last_ch;
  3668. /* handle parameter expansions
  3669. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  3670. */
  3671. if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
  3672. goto bad_dollar_syntax;
  3673. /* Eat everything until closing '}' (or ':') */
  3674. end_ch = '}';
  3675. if (ENABLE_HUSH_BASH_COMPAT
  3676. && ch == ':'
  3677. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  3678. ) {
  3679. /* It's ${var:N[:M]} thing */
  3680. end_ch = '}' * 0x100 + ':';
  3681. }
  3682. if (ENABLE_HUSH_BASH_COMPAT
  3683. && ch == '/'
  3684. ) {
  3685. /* It's ${var/[/]pattern[/repl]} thing */
  3686. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  3687. i_getch(input);
  3688. nommu_addchr(as_string, '/');
  3689. ch = '\\';
  3690. }
  3691. end_ch = '}' * 0x100 + '/';
  3692. }
  3693. o_addchr(dest, ch);
  3694. again:
  3695. if (!BB_MMU)
  3696. pos = dest->length;
  3697. #if ENABLE_HUSH_DOLLAR_OPS
  3698. last_ch = add_till_closing_bracket(dest, input, end_ch);
  3699. if (last_ch == 0) /* error? */
  3700. return 0;
  3701. #else
  3702. #error Simple code to only allow ${var} is not implemented
  3703. #endif
  3704. if (as_string) {
  3705. o_addstr(as_string, dest->data + pos);
  3706. o_addchr(as_string, last_ch);
  3707. }
  3708. if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
  3709. /* close the first block: */
  3710. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3711. /* while parsing N from ${var:N[:M]}
  3712. * or pattern from ${var/[/]pattern[/repl]} */
  3713. if ((end_ch & 0xff) == last_ch) {
  3714. /* got ':' or '/'- parse the rest */
  3715. end_ch = '}';
  3716. goto again;
  3717. }
  3718. /* got '}' */
  3719. if (end_ch == '}' * 0x100 + ':') {
  3720. /* it's ${var:N} - emulate :999999999 */
  3721. o_addstr(dest, "999999999");
  3722. } /* else: it's ${var/[/]pattern} */
  3723. }
  3724. break;
  3725. }
  3726. }
  3727. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3728. break;
  3729. }
  3730. #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
  3731. case '(': {
  3732. unsigned pos;
  3733. ch = i_getch(input);
  3734. nommu_addchr(as_string, ch);
  3735. # if ENABLE_SH_MATH_SUPPORT
  3736. if (i_peek(input) == '(') {
  3737. ch = i_getch(input);
  3738. nommu_addchr(as_string, ch);
  3739. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3740. o_addchr(dest, /*quote_mask |*/ '+');
  3741. if (!BB_MMU)
  3742. pos = dest->length;
  3743. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  3744. return 0; /* error */
  3745. if (as_string) {
  3746. o_addstr(as_string, dest->data + pos);
  3747. o_addchr(as_string, ')');
  3748. o_addchr(as_string, ')');
  3749. }
  3750. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3751. break;
  3752. }
  3753. # endif
  3754. # if ENABLE_HUSH_TICK
  3755. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3756. o_addchr(dest, quote_mask | '`');
  3757. if (!BB_MMU)
  3758. pos = dest->length;
  3759. if (!add_till_closing_bracket(dest, input, ')'))
  3760. return 0; /* error */
  3761. if (as_string) {
  3762. o_addstr(as_string, dest->data + pos);
  3763. o_addchr(as_string, ')');
  3764. }
  3765. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3766. # endif
  3767. break;
  3768. }
  3769. #endif
  3770. case '_':
  3771. ch = i_getch(input);
  3772. nommu_addchr(as_string, ch);
  3773. ch = i_peek(input);
  3774. if (isalnum(ch)) { /* it's $_name or $_123 */
  3775. ch = '_';
  3776. goto make_var;
  3777. }
  3778. /* else: it's $_ */
  3779. /* TODO: $_ and $-: */
  3780. /* $_ Shell or shell script name; or last argument of last command
  3781. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  3782. * but in command's env, set to full pathname used to invoke it */
  3783. /* $- Option flags set by set builtin or shell options (-i etc) */
  3784. default:
  3785. o_addQchr(dest, '$');
  3786. }
  3787. debug_printf_parse("parse_dollar return 1 (ok)\n");
  3788. return 1;
  3789. #undef as_string
  3790. }
  3791. #if BB_MMU
  3792. # if ENABLE_HUSH_BASH_COMPAT
  3793. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3794. encode_string(dest, input, dquote_end, process_bkslash)
  3795. # else
  3796. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  3797. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3798. encode_string(dest, input, dquote_end)
  3799. # endif
  3800. #define as_string NULL
  3801. #else /* !MMU */
  3802. # if ENABLE_HUSH_BASH_COMPAT
  3803. /* all parameters are needed, no macro tricks */
  3804. # else
  3805. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3806. encode_string(as_string, dest, input, dquote_end)
  3807. # endif
  3808. #endif
  3809. static int encode_string(o_string *as_string,
  3810. o_string *dest,
  3811. struct in_str *input,
  3812. int dquote_end,
  3813. int process_bkslash)
  3814. {
  3815. #if !ENABLE_HUSH_BASH_COMPAT
  3816. const int process_bkslash = 1;
  3817. #endif
  3818. int ch;
  3819. int next;
  3820. again:
  3821. ch = i_getch(input);
  3822. if (ch != EOF)
  3823. nommu_addchr(as_string, ch);
  3824. if (ch == dquote_end) { /* may be only '"' or EOF */
  3825. debug_printf_parse("encode_string return 1 (ok)\n");
  3826. return 1;
  3827. }
  3828. /* note: can't move it above ch == dquote_end check! */
  3829. if (ch == EOF) {
  3830. syntax_error_unterm_ch('"');
  3831. return 0; /* error */
  3832. }
  3833. next = '\0';
  3834. if (ch != '\n') {
  3835. next = i_peek(input);
  3836. }
  3837. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  3838. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  3839. if (process_bkslash && ch == '\\') {
  3840. if (next == EOF) {
  3841. syntax_error("\\<eof>");
  3842. xfunc_die();
  3843. }
  3844. /* bash:
  3845. * "The backslash retains its special meaning [in "..."]
  3846. * only when followed by one of the following characters:
  3847. * $, `, ", \, or <newline>. A double quote may be quoted
  3848. * within double quotes by preceding it with a backslash."
  3849. * NB: in (unquoted) heredoc, above does not apply to ",
  3850. * therefore we check for it by "next == dquote_end" cond.
  3851. */
  3852. if (next == dquote_end || strchr("$`\\\n", next)) {
  3853. ch = i_getch(input); /* eat next */
  3854. if (ch == '\n')
  3855. goto again; /* skip \<newline> */
  3856. } /* else: ch remains == '\\', and we double it below: */
  3857. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  3858. nommu_addchr(as_string, ch);
  3859. goto again;
  3860. }
  3861. if (ch == '$') {
  3862. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  3863. debug_printf_parse("encode_string return 0: "
  3864. "parse_dollar returned 0 (error)\n");
  3865. return 0;
  3866. }
  3867. goto again;
  3868. }
  3869. #if ENABLE_HUSH_TICK
  3870. if (ch == '`') {
  3871. //unsigned pos = dest->length;
  3872. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3873. o_addchr(dest, 0x80 | '`');
  3874. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  3875. return 0; /* error */
  3876. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3877. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  3878. goto again;
  3879. }
  3880. #endif
  3881. o_addQchr(dest, ch);
  3882. goto again;
  3883. #undef as_string
  3884. }
  3885. /*
  3886. * Scan input until EOF or end_trigger char.
  3887. * Return a list of pipes to execute, or NULL on EOF
  3888. * or if end_trigger character is met.
  3889. * On syntax error, exit if shell is not interactive,
  3890. * reset parsing machinery and start parsing anew,
  3891. * or return ERR_PTR.
  3892. */
  3893. static struct pipe *parse_stream(char **pstring,
  3894. struct in_str *input,
  3895. int end_trigger)
  3896. {
  3897. struct parse_context ctx;
  3898. o_string dest = NULL_O_STRING;
  3899. int heredoc_cnt;
  3900. /* Single-quote triggers a bypass of the main loop until its mate is
  3901. * found. When recursing, quote state is passed in via dest->o_expflags.
  3902. */
  3903. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  3904. end_trigger ? end_trigger : 'X');
  3905. debug_enter();
  3906. /* If very first arg is "" or '', dest.data may end up NULL.
  3907. * Preventing this: */
  3908. o_addchr(&dest, '\0');
  3909. dest.length = 0;
  3910. /* We used to separate words on $IFS here. This was wrong.
  3911. * $IFS is used only for word splitting when $var is expanded,
  3912. * here we should use blank chars as separators, not $IFS
  3913. */
  3914. if (MAYBE_ASSIGNMENT != 0)
  3915. dest.o_assignment = MAYBE_ASSIGNMENT;
  3916. initialize_context(&ctx);
  3917. heredoc_cnt = 0;
  3918. while (1) {
  3919. const char *is_blank;
  3920. const char *is_special;
  3921. int ch;
  3922. int next;
  3923. int redir_fd;
  3924. redir_type redir_style;
  3925. ch = i_getch(input);
  3926. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  3927. ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  3928. if (ch == EOF) {
  3929. struct pipe *pi;
  3930. if (heredoc_cnt) {
  3931. syntax_error_unterm_str("here document");
  3932. goto parse_error;
  3933. }
  3934. /* end_trigger == '}' case errors out earlier,
  3935. * checking only ')' */
  3936. if (end_trigger == ')') {
  3937. syntax_error_unterm_ch('(');
  3938. goto parse_error;
  3939. }
  3940. if (done_word(&dest, &ctx)) {
  3941. goto parse_error;
  3942. }
  3943. o_free(&dest);
  3944. done_pipe(&ctx, PIPE_SEQ);
  3945. pi = ctx.list_head;
  3946. /* If we got nothing... */
  3947. /* (this makes bare "&" cmd a no-op.
  3948. * bash says: "syntax error near unexpected token '&'") */
  3949. if (pi->num_cmds == 0
  3950. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  3951. ) {
  3952. free_pipe_list(pi);
  3953. pi = NULL;
  3954. }
  3955. #if !BB_MMU
  3956. debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
  3957. if (pstring)
  3958. *pstring = ctx.as_string.data;
  3959. else
  3960. o_free_unsafe(&ctx.as_string);
  3961. #endif
  3962. debug_leave();
  3963. debug_printf_parse("parse_stream return %p\n", pi);
  3964. return pi;
  3965. }
  3966. nommu_addchr(&ctx.as_string, ch);
  3967. next = '\0';
  3968. if (ch != '\n')
  3969. next = i_peek(input);
  3970. is_special = "{}<>;&|()#'" /* special outside of "str" */
  3971. "\\$\"" IF_HUSH_TICK("`"); /* always special */
  3972. /* Are { and } special here? */
  3973. if (ctx.command->argv /* word [word]{... - non-special */
  3974. || dest.length /* word{... - non-special */
  3975. || dest.has_quoted_part /* ""{... - non-special */
  3976. || (next != ';' /* }; - special */
  3977. && next != ')' /* }) - special */
  3978. && next != '&' /* }& and }&& ... - special */
  3979. && next != '|' /* }|| ... - special */
  3980. && !strchr(defifs, next) /* {word - non-special */
  3981. )
  3982. ) {
  3983. /* They are not special, skip "{}" */
  3984. is_special += 2;
  3985. }
  3986. is_special = strchr(is_special, ch);
  3987. is_blank = strchr(defifs, ch);
  3988. if (!is_special && !is_blank) { /* ordinary char */
  3989. ordinary_char:
  3990. o_addQchr(&dest, ch);
  3991. if ((dest.o_assignment == MAYBE_ASSIGNMENT
  3992. || dest.o_assignment == WORD_IS_KEYWORD)
  3993. && ch == '='
  3994. && is_well_formed_var_name(dest.data, '=')
  3995. ) {
  3996. dest.o_assignment = DEFINITELY_ASSIGNMENT;
  3997. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  3998. }
  3999. continue;
  4000. }
  4001. if (is_blank) {
  4002. if (done_word(&dest, &ctx)) {
  4003. goto parse_error;
  4004. }
  4005. if (ch == '\n') {
  4006. /* Is this a case when newline is simply ignored?
  4007. * Some examples:
  4008. * "cmd | <newline> cmd ..."
  4009. * "case ... in <newline> word) ..."
  4010. */
  4011. if (IS_NULL_CMD(ctx.command)
  4012. && dest.length == 0 && !dest.has_quoted_part
  4013. ) {
  4014. /* This newline can be ignored. But...
  4015. * Without check #1, interactive shell
  4016. * ignores even bare <newline>,
  4017. * and shows the continuation prompt:
  4018. * ps1_prompt$ <enter>
  4019. * ps2> _ <=== wrong, should be ps1
  4020. * Without check #2, "cmd & <newline>"
  4021. * is similarly mistreated.
  4022. * (BTW, this makes "cmd & cmd"
  4023. * and "cmd && cmd" non-orthogonal.
  4024. * Really, ask yourself, why
  4025. * "cmd && <newline>" doesn't start
  4026. * cmd but waits for more input?
  4027. * No reason...)
  4028. */
  4029. struct pipe *pi = ctx.list_head;
  4030. if (pi->num_cmds != 0 /* check #1 */
  4031. && pi->followup != PIPE_BG /* check #2 */
  4032. ) {
  4033. continue;
  4034. }
  4035. }
  4036. /* Treat newline as a command separator. */
  4037. done_pipe(&ctx, PIPE_SEQ);
  4038. debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
  4039. if (heredoc_cnt) {
  4040. if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
  4041. goto parse_error;
  4042. }
  4043. heredoc_cnt = 0;
  4044. }
  4045. dest.o_assignment = MAYBE_ASSIGNMENT;
  4046. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4047. ch = ';';
  4048. /* note: if (is_blank) continue;
  4049. * will still trigger for us */
  4050. }
  4051. }
  4052. /* "cmd}" or "cmd }..." without semicolon or &:
  4053. * } is an ordinary char in this case, even inside { cmd; }
  4054. * Pathological example: { ""}; } should exec "}" cmd
  4055. */
  4056. if (ch == '}') {
  4057. if (!IS_NULL_CMD(ctx.command) /* cmd } */
  4058. || dest.length != 0 /* word} */
  4059. || dest.has_quoted_part /* ""} */
  4060. ) {
  4061. goto ordinary_char;
  4062. }
  4063. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  4064. goto skip_end_trigger;
  4065. /* else: } does terminate a group */
  4066. }
  4067. if (end_trigger && end_trigger == ch
  4068. && (ch != ';' || heredoc_cnt == 0)
  4069. #if ENABLE_HUSH_CASE
  4070. && (ch != ')'
  4071. || ctx.ctx_res_w != RES_MATCH
  4072. || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
  4073. )
  4074. #endif
  4075. ) {
  4076. if (heredoc_cnt) {
  4077. /* This is technically valid:
  4078. * { cat <<HERE; }; echo Ok
  4079. * heredoc
  4080. * heredoc
  4081. * HERE
  4082. * but we don't support this.
  4083. * We require heredoc to be in enclosing {}/(),
  4084. * if any.
  4085. */
  4086. syntax_error_unterm_str("here document");
  4087. goto parse_error;
  4088. }
  4089. if (done_word(&dest, &ctx)) {
  4090. goto parse_error;
  4091. }
  4092. done_pipe(&ctx, PIPE_SEQ);
  4093. dest.o_assignment = MAYBE_ASSIGNMENT;
  4094. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4095. /* Do we sit outside of any if's, loops or case's? */
  4096. if (!HAS_KEYWORDS
  4097. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  4098. ) {
  4099. o_free(&dest);
  4100. #if !BB_MMU
  4101. debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
  4102. if (pstring)
  4103. *pstring = ctx.as_string.data;
  4104. else
  4105. o_free_unsafe(&ctx.as_string);
  4106. #endif
  4107. debug_leave();
  4108. debug_printf_parse("parse_stream return %p: "
  4109. "end_trigger char found\n",
  4110. ctx.list_head);
  4111. return ctx.list_head;
  4112. }
  4113. }
  4114. skip_end_trigger:
  4115. if (is_blank)
  4116. continue;
  4117. /* Catch <, > before deciding whether this word is
  4118. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  4119. switch (ch) {
  4120. case '>':
  4121. redir_fd = redirect_opt_num(&dest);
  4122. if (done_word(&dest, &ctx)) {
  4123. goto parse_error;
  4124. }
  4125. redir_style = REDIRECT_OVERWRITE;
  4126. if (next == '>') {
  4127. redir_style = REDIRECT_APPEND;
  4128. ch = i_getch(input);
  4129. nommu_addchr(&ctx.as_string, ch);
  4130. }
  4131. #if 0
  4132. else if (next == '(') {
  4133. syntax_error(">(process) not supported");
  4134. goto parse_error;
  4135. }
  4136. #endif
  4137. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  4138. goto parse_error;
  4139. continue; /* back to top of while (1) */
  4140. case '<':
  4141. redir_fd = redirect_opt_num(&dest);
  4142. if (done_word(&dest, &ctx)) {
  4143. goto parse_error;
  4144. }
  4145. redir_style = REDIRECT_INPUT;
  4146. if (next == '<') {
  4147. redir_style = REDIRECT_HEREDOC;
  4148. heredoc_cnt++;
  4149. debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
  4150. ch = i_getch(input);
  4151. nommu_addchr(&ctx.as_string, ch);
  4152. } else if (next == '>') {
  4153. redir_style = REDIRECT_IO;
  4154. ch = i_getch(input);
  4155. nommu_addchr(&ctx.as_string, ch);
  4156. }
  4157. #if 0
  4158. else if (next == '(') {
  4159. syntax_error("<(process) not supported");
  4160. goto parse_error;
  4161. }
  4162. #endif
  4163. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  4164. goto parse_error;
  4165. continue; /* back to top of while (1) */
  4166. case '#':
  4167. if (dest.length == 0 && !dest.has_quoted_part) {
  4168. /* skip "#comment" */
  4169. while (1) {
  4170. ch = i_peek(input);
  4171. if (ch == EOF || ch == '\n')
  4172. break;
  4173. i_getch(input);
  4174. /* note: we do not add it to &ctx.as_string */
  4175. }
  4176. nommu_addchr(&ctx.as_string, '\n');
  4177. continue; /* back to top of while (1) */
  4178. }
  4179. break;
  4180. case '\\':
  4181. if (next == '\n') {
  4182. /* It's "\<newline>" */
  4183. #if !BB_MMU
  4184. /* Remove trailing '\' from ctx.as_string */
  4185. ctx.as_string.data[--ctx.as_string.length] = '\0';
  4186. #endif
  4187. ch = i_getch(input); /* eat it */
  4188. continue; /* back to top of while (1) */
  4189. }
  4190. break;
  4191. }
  4192. if (dest.o_assignment == MAYBE_ASSIGNMENT
  4193. /* check that we are not in word in "a=1 2>word b=1": */
  4194. && !ctx.pending_redirect
  4195. ) {
  4196. /* ch is a special char and thus this word
  4197. * cannot be an assignment */
  4198. dest.o_assignment = NOT_ASSIGNMENT;
  4199. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4200. }
  4201. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  4202. switch (ch) {
  4203. case '#': /* non-comment #: "echo a#b" etc */
  4204. o_addQchr(&dest, ch);
  4205. break;
  4206. case '\\':
  4207. if (next == EOF) {
  4208. syntax_error("\\<eof>");
  4209. xfunc_die();
  4210. }
  4211. ch = i_getch(input);
  4212. /* note: ch != '\n' (that case does not reach this place) */
  4213. o_addchr(&dest, '\\');
  4214. /*nommu_addchr(&ctx.as_string, '\\'); - already done */
  4215. o_addchr(&dest, ch);
  4216. nommu_addchr(&ctx.as_string, ch);
  4217. /* Example: echo Hello \2>file
  4218. * we need to know that word 2 is quoted */
  4219. dest.has_quoted_part = 1;
  4220. break;
  4221. case '$':
  4222. if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
  4223. debug_printf_parse("parse_stream parse error: "
  4224. "parse_dollar returned 0 (error)\n");
  4225. goto parse_error;
  4226. }
  4227. break;
  4228. case '\'':
  4229. dest.has_quoted_part = 1;
  4230. if (next == '\'' && !ctx.pending_redirect) {
  4231. insert_empty_quoted_str_marker:
  4232. nommu_addchr(&ctx.as_string, next);
  4233. i_getch(input); /* eat second ' */
  4234. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4235. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4236. } else {
  4237. while (1) {
  4238. ch = i_getch(input);
  4239. if (ch == EOF) {
  4240. syntax_error_unterm_ch('\'');
  4241. goto parse_error;
  4242. }
  4243. nommu_addchr(&ctx.as_string, ch);
  4244. if (ch == '\'')
  4245. break;
  4246. o_addqchr(&dest, ch);
  4247. }
  4248. }
  4249. break;
  4250. case '"':
  4251. dest.has_quoted_part = 1;
  4252. if (next == '"' && !ctx.pending_redirect)
  4253. goto insert_empty_quoted_str_marker;
  4254. if (dest.o_assignment == NOT_ASSIGNMENT)
  4255. dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  4256. if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
  4257. goto parse_error;
  4258. dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  4259. break;
  4260. #if ENABLE_HUSH_TICK
  4261. case '`': {
  4262. USE_FOR_NOMMU(unsigned pos;)
  4263. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4264. o_addchr(&dest, '`');
  4265. USE_FOR_NOMMU(pos = dest.length;)
  4266. if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
  4267. goto parse_error;
  4268. # if !BB_MMU
  4269. o_addstr(&ctx.as_string, dest.data + pos);
  4270. o_addchr(&ctx.as_string, '`');
  4271. # endif
  4272. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4273. //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
  4274. break;
  4275. }
  4276. #endif
  4277. case ';':
  4278. #if ENABLE_HUSH_CASE
  4279. case_semi:
  4280. #endif
  4281. if (done_word(&dest, &ctx)) {
  4282. goto parse_error;
  4283. }
  4284. done_pipe(&ctx, PIPE_SEQ);
  4285. #if ENABLE_HUSH_CASE
  4286. /* Eat multiple semicolons, detect
  4287. * whether it means something special */
  4288. while (1) {
  4289. ch = i_peek(input);
  4290. if (ch != ';')
  4291. break;
  4292. ch = i_getch(input);
  4293. nommu_addchr(&ctx.as_string, ch);
  4294. if (ctx.ctx_res_w == RES_CASE_BODY) {
  4295. ctx.ctx_dsemicolon = 1;
  4296. ctx.ctx_res_w = RES_MATCH;
  4297. break;
  4298. }
  4299. }
  4300. #endif
  4301. new_cmd:
  4302. /* We just finished a cmd. New one may start
  4303. * with an assignment */
  4304. dest.o_assignment = MAYBE_ASSIGNMENT;
  4305. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4306. break;
  4307. case '&':
  4308. if (done_word(&dest, &ctx)) {
  4309. goto parse_error;
  4310. }
  4311. if (next == '&') {
  4312. ch = i_getch(input);
  4313. nommu_addchr(&ctx.as_string, ch);
  4314. done_pipe(&ctx, PIPE_AND);
  4315. } else {
  4316. done_pipe(&ctx, PIPE_BG);
  4317. }
  4318. goto new_cmd;
  4319. case '|':
  4320. if (done_word(&dest, &ctx)) {
  4321. goto parse_error;
  4322. }
  4323. #if ENABLE_HUSH_CASE
  4324. if (ctx.ctx_res_w == RES_MATCH)
  4325. break; /* we are in case's "word | word)" */
  4326. #endif
  4327. if (next == '|') { /* || */
  4328. ch = i_getch(input);
  4329. nommu_addchr(&ctx.as_string, ch);
  4330. done_pipe(&ctx, PIPE_OR);
  4331. } else {
  4332. /* we could pick up a file descriptor choice here
  4333. * with redirect_opt_num(), but bash doesn't do it.
  4334. * "echo foo 2| cat" yields "foo 2". */
  4335. done_command(&ctx);
  4336. #if !BB_MMU
  4337. o_reset_to_empty_unquoted(&ctx.as_string);
  4338. #endif
  4339. }
  4340. goto new_cmd;
  4341. case '(':
  4342. #if ENABLE_HUSH_CASE
  4343. /* "case... in [(]word)..." - skip '(' */
  4344. if (ctx.ctx_res_w == RES_MATCH
  4345. && ctx.command->argv == NULL /* not (word|(... */
  4346. && dest.length == 0 /* not word(... */
  4347. && dest.has_quoted_part == 0 /* not ""(... */
  4348. ) {
  4349. continue;
  4350. }
  4351. #endif
  4352. case '{':
  4353. if (parse_group(&dest, &ctx, input, ch) != 0) {
  4354. goto parse_error;
  4355. }
  4356. goto new_cmd;
  4357. case ')':
  4358. #if ENABLE_HUSH_CASE
  4359. if (ctx.ctx_res_w == RES_MATCH)
  4360. goto case_semi;
  4361. #endif
  4362. case '}':
  4363. /* proper use of this character is caught by end_trigger:
  4364. * if we see {, we call parse_group(..., end_trigger='}')
  4365. * and it will match } earlier (not here). */
  4366. syntax_error_unexpected_ch(ch);
  4367. goto parse_error;
  4368. default:
  4369. if (HUSH_DEBUG)
  4370. bb_error_msg_and_die("BUG: unexpected %c\n", ch);
  4371. }
  4372. } /* while (1) */
  4373. parse_error:
  4374. {
  4375. struct parse_context *pctx;
  4376. IF_HAS_KEYWORDS(struct parse_context *p2;)
  4377. /* Clean up allocated tree.
  4378. * Sample for finding leaks on syntax error recovery path.
  4379. * Run it from interactive shell, watch pmap `pidof hush`.
  4380. * while if false; then false; fi; do break; fi
  4381. * Samples to catch leaks at execution:
  4382. * while if (true | {true;}); then echo ok; fi; do break; done
  4383. * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  4384. */
  4385. pctx = &ctx;
  4386. do {
  4387. /* Update pipe/command counts,
  4388. * otherwise freeing may miss some */
  4389. done_pipe(pctx, PIPE_SEQ);
  4390. debug_printf_clean("freeing list %p from ctx %p\n",
  4391. pctx->list_head, pctx);
  4392. debug_print_tree(pctx->list_head, 0);
  4393. free_pipe_list(pctx->list_head);
  4394. debug_printf_clean("freed list %p\n", pctx->list_head);
  4395. #if !BB_MMU
  4396. o_free_unsafe(&pctx->as_string);
  4397. #endif
  4398. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  4399. if (pctx != &ctx) {
  4400. free(pctx);
  4401. }
  4402. IF_HAS_KEYWORDS(pctx = p2;)
  4403. } while (HAS_KEYWORDS && pctx);
  4404. o_free(&dest);
  4405. G.last_exitcode = 1;
  4406. #if !BB_MMU
  4407. if (pstring)
  4408. *pstring = NULL;
  4409. #endif
  4410. debug_leave();
  4411. return ERR_PTR;
  4412. }
  4413. }
  4414. /*** Execution routines ***/
  4415. /* Expansion can recurse, need forward decls: */
  4416. #if !ENABLE_HUSH_BASH_COMPAT
  4417. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  4418. #define expand_string_to_string(str, do_unbackslash) \
  4419. expand_string_to_string(str)
  4420. #endif
  4421. static char *expand_string_to_string(const char *str, int do_unbackslash);
  4422. #if ENABLE_HUSH_TICK
  4423. static int process_command_subs(o_string *dest, const char *s);
  4424. #endif
  4425. /* expand_strvec_to_strvec() takes a list of strings, expands
  4426. * all variable references within and returns a pointer to
  4427. * a list of expanded strings, possibly with larger number
  4428. * of strings. (Think VAR="a b"; echo $VAR).
  4429. * This new list is allocated as a single malloc block.
  4430. * NULL-terminated list of char* pointers is at the beginning of it,
  4431. * followed by strings themselves.
  4432. * Caller can deallocate entire list by single free(list). */
  4433. /* A horde of its helpers come first: */
  4434. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  4435. {
  4436. while (--len >= 0) {
  4437. char c = *str++;
  4438. #if ENABLE_HUSH_BRACE_EXPANSION
  4439. if (c == '{' || c == '}') {
  4440. /* { -> \{, } -> \} */
  4441. o_addchr(o, '\\');
  4442. /* And now we want to add { or } and continue:
  4443. * o_addchr(o, c);
  4444. * continue;
  4445. * luckily, just falling throught achieves this.
  4446. */
  4447. }
  4448. #endif
  4449. o_addchr(o, c);
  4450. if (c == '\\') {
  4451. /* \z -> \\\z; \<eol> -> \\<eol> */
  4452. o_addchr(o, '\\');
  4453. if (len) {
  4454. len--;
  4455. o_addchr(o, '\\');
  4456. o_addchr(o, *str++);
  4457. }
  4458. }
  4459. }
  4460. }
  4461. /* Store given string, finalizing the word and starting new one whenever
  4462. * we encounter IFS char(s). This is used for expanding variable values.
  4463. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  4464. * Return in *ended_with_ifs:
  4465. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  4466. */
  4467. static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
  4468. {
  4469. int last_is_ifs = 0;
  4470. while (1) {
  4471. int word_len;
  4472. if (!*str) /* EOL - do not finalize word */
  4473. break;
  4474. word_len = strcspn(str, G.ifs);
  4475. if (word_len) {
  4476. /* We have WORD_LEN leading non-IFS chars */
  4477. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  4478. o_addblock(output, str, word_len);
  4479. } else {
  4480. /* Protect backslashes against globbing up :)
  4481. * Example: "v='\*'; echo b$v" prints "b\*"
  4482. * (and does not try to glob on "*")
  4483. */
  4484. o_addblock_duplicate_backslash(output, str, word_len);
  4485. /*/ Why can't we do it easier? */
  4486. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  4487. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  4488. }
  4489. last_is_ifs = 0;
  4490. str += word_len;
  4491. if (!*str) /* EOL - do not finalize word */
  4492. break;
  4493. }
  4494. /* We know str here points to at least one IFS char */
  4495. last_is_ifs = 1;
  4496. str += strspn(str, G.ifs); /* skip IFS chars */
  4497. if (!*str) /* EOL - do not finalize word */
  4498. break;
  4499. /* Start new word... but not always! */
  4500. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  4501. if (output->has_quoted_part
  4502. /* Case "v=' a'; echo $v":
  4503. * here nothing precedes the space in $v expansion,
  4504. * therefore we should not finish the word
  4505. * (IOW: if there *is* word to finalize, only then do it):
  4506. */
  4507. || (n > 0 && output->data[output->length - 1])
  4508. ) {
  4509. o_addchr(output, '\0');
  4510. debug_print_list("expand_on_ifs", output, n);
  4511. n = o_save_ptr(output, n);
  4512. }
  4513. }
  4514. if (ended_with_ifs)
  4515. *ended_with_ifs = last_is_ifs;
  4516. debug_print_list("expand_on_ifs[1]", output, n);
  4517. return n;
  4518. }
  4519. /* Helper to expand $((...)) and heredoc body. These act as if
  4520. * they are in double quotes, with the exception that they are not :).
  4521. * Just the rules are similar: "expand only $var and `cmd`"
  4522. *
  4523. * Returns malloced string.
  4524. * As an optimization, we return NULL if expansion is not needed.
  4525. */
  4526. #if !ENABLE_HUSH_BASH_COMPAT
  4527. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  4528. #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
  4529. encode_then_expand_string(str)
  4530. #endif
  4531. static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
  4532. {
  4533. char *exp_str;
  4534. struct in_str input;
  4535. o_string dest = NULL_O_STRING;
  4536. if (!strchr(str, '$')
  4537. && !strchr(str, '\\')
  4538. #if ENABLE_HUSH_TICK
  4539. && !strchr(str, '`')
  4540. #endif
  4541. ) {
  4542. return NULL;
  4543. }
  4544. /* We need to expand. Example:
  4545. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  4546. */
  4547. setup_string_in_str(&input, str);
  4548. encode_string(NULL, &dest, &input, EOF, process_bkslash);
  4549. //TODO: error check (encode_string returns 0 on error)?
  4550. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  4551. exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
  4552. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  4553. o_free_unsafe(&dest);
  4554. return exp_str;
  4555. }
  4556. #if ENABLE_SH_MATH_SUPPORT
  4557. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  4558. {
  4559. arith_state_t math_state;
  4560. arith_t res;
  4561. char *exp_str;
  4562. math_state.lookupvar = get_local_var_value;
  4563. math_state.setvar = set_local_var_from_halves;
  4564. //math_state.endofname = endofname;
  4565. exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4566. res = arith(&math_state, exp_str ? exp_str : arg);
  4567. free(exp_str);
  4568. if (errmsg_p)
  4569. *errmsg_p = math_state.errmsg;
  4570. if (math_state.errmsg)
  4571. die_if_script(math_state.errmsg);
  4572. return res;
  4573. }
  4574. #endif
  4575. #if ENABLE_HUSH_BASH_COMPAT
  4576. /* ${var/[/]pattern[/repl]} helpers */
  4577. static char *strstr_pattern(char *val, const char *pattern, int *size)
  4578. {
  4579. while (1) {
  4580. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  4581. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  4582. if (end) {
  4583. *size = end - val;
  4584. return val;
  4585. }
  4586. if (*val == '\0')
  4587. return NULL;
  4588. /* Optimization: if "*pat" did not match the start of "string",
  4589. * we know that "tring", "ring" etc will not match too:
  4590. */
  4591. if (pattern[0] == '*')
  4592. return NULL;
  4593. val++;
  4594. }
  4595. }
  4596. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  4597. {
  4598. char *result = NULL;
  4599. unsigned res_len = 0;
  4600. unsigned repl_len = strlen(repl);
  4601. while (1) {
  4602. int size;
  4603. char *s = strstr_pattern(val, pattern, &size);
  4604. if (!s)
  4605. break;
  4606. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  4607. memcpy(result + res_len, val, s - val);
  4608. res_len += s - val;
  4609. strcpy(result + res_len, repl);
  4610. res_len += repl_len;
  4611. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  4612. val = s + size;
  4613. if (exp_op == '/')
  4614. break;
  4615. }
  4616. if (val[0] && result) {
  4617. result = xrealloc(result, res_len + strlen(val) + 1);
  4618. strcpy(result + res_len, val);
  4619. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  4620. }
  4621. debug_printf_varexp("result:'%s'\n", result);
  4622. return result;
  4623. }
  4624. #endif
  4625. /* Helper:
  4626. * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  4627. */
  4628. static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
  4629. {
  4630. const char *val = NULL;
  4631. char *to_be_freed = NULL;
  4632. char *p = *pp;
  4633. char *var;
  4634. char first_char;
  4635. char exp_op;
  4636. char exp_save = exp_save; /* for compiler */
  4637. char *exp_saveptr; /* points to expansion operator */
  4638. char *exp_word = exp_word; /* for compiler */
  4639. char arg0;
  4640. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  4641. var = arg;
  4642. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  4643. arg0 = arg[0];
  4644. first_char = arg[0] = arg0 & 0x7f;
  4645. exp_op = 0;
  4646. if (first_char == '#' /* ${#... */
  4647. && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
  4648. ) {
  4649. /* It must be length operator: ${#var} */
  4650. var++;
  4651. exp_op = 'L';
  4652. } else {
  4653. /* Maybe handle parameter expansion */
  4654. if (exp_saveptr /* if 2nd char is one of expansion operators */
  4655. && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
  4656. ) {
  4657. /* ${?:0}, ${#[:]%0} etc */
  4658. exp_saveptr = var + 1;
  4659. } else {
  4660. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  4661. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  4662. }
  4663. exp_op = exp_save = *exp_saveptr;
  4664. if (exp_op) {
  4665. exp_word = exp_saveptr + 1;
  4666. if (exp_op == ':') {
  4667. exp_op = *exp_word++;
  4668. //TODO: try ${var:} and ${var:bogus} in non-bash config
  4669. if (ENABLE_HUSH_BASH_COMPAT
  4670. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  4671. ) {
  4672. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  4673. exp_op = ':';
  4674. exp_word--;
  4675. }
  4676. }
  4677. *exp_saveptr = '\0';
  4678. } /* else: it's not an expansion op, but bare ${var} */
  4679. }
  4680. /* Look up the variable in question */
  4681. if (isdigit(var[0])) {
  4682. /* parse_dollar should have vetted var for us */
  4683. int n = xatoi_positive(var);
  4684. if (n < G.global_argc)
  4685. val = G.global_argv[n];
  4686. /* else val remains NULL: $N with too big N */
  4687. } else {
  4688. switch (var[0]) {
  4689. case '$': /* pid */
  4690. val = utoa(G.root_pid);
  4691. break;
  4692. case '!': /* bg pid */
  4693. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  4694. break;
  4695. case '?': /* exitcode */
  4696. val = utoa(G.last_exitcode);
  4697. break;
  4698. case '#': /* argc */
  4699. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  4700. break;
  4701. default:
  4702. val = get_local_var_value(var);
  4703. }
  4704. }
  4705. /* Handle any expansions */
  4706. if (exp_op == 'L') {
  4707. reinit_unicode_for_hush();
  4708. debug_printf_expand("expand: length(%s)=", val);
  4709. val = utoa(val ? unicode_strlen(val) : 0);
  4710. debug_printf_expand("%s\n", val);
  4711. } else if (exp_op) {
  4712. if (exp_op == '%' || exp_op == '#') {
  4713. /* Standard-mandated substring removal ops:
  4714. * ${parameter%word} - remove smallest suffix pattern
  4715. * ${parameter%%word} - remove largest suffix pattern
  4716. * ${parameter#word} - remove smallest prefix pattern
  4717. * ${parameter##word} - remove largest prefix pattern
  4718. *
  4719. * Word is expanded to produce a glob pattern.
  4720. * Then var's value is matched to it and matching part removed.
  4721. */
  4722. if (val && val[0]) {
  4723. char *t;
  4724. char *exp_exp_word;
  4725. char *loc;
  4726. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  4727. if (exp_op == *exp_word) /* ## or %% */
  4728. exp_word++;
  4729. exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4730. if (exp_exp_word)
  4731. exp_word = exp_exp_word;
  4732. /* HACK ALERT. We depend here on the fact that
  4733. * G.global_argv and results of utoa and get_local_var_value
  4734. * are actually in writable memory:
  4735. * scan_and_match momentarily stores NULs there. */
  4736. t = (char*)val;
  4737. loc = scan_and_match(t, exp_word, scan_flags);
  4738. //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
  4739. // exp_op, t, exp_word, loc);
  4740. free(exp_exp_word);
  4741. if (loc) { /* match was found */
  4742. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  4743. val = loc; /* take right part */
  4744. else /* %[%] */
  4745. val = to_be_freed = xstrndup(val, loc - val); /* left */
  4746. }
  4747. }
  4748. }
  4749. #if ENABLE_HUSH_BASH_COMPAT
  4750. else if (exp_op == '/' || exp_op == '\\') {
  4751. /* It's ${var/[/]pattern[/repl]} thing.
  4752. * Note that in encoded form it has TWO parts:
  4753. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  4754. * and if // is used, it is encoded as \:
  4755. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  4756. */
  4757. /* Empty variable always gives nothing: */
  4758. // "v=''; echo ${v/*/w}" prints "", not "w"
  4759. if (val && val[0]) {
  4760. /* pattern uses non-standard expansion.
  4761. * repl should be unbackslashed and globbed
  4762. * by the usual expansion rules:
  4763. * >az; >bz;
  4764. * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
  4765. * v='a bz'; echo "${v/a*z/\z}" prints "\z"
  4766. * v='a bz'; echo ${v/a*z/a*z} prints "az"
  4767. * v='a bz'; echo ${v/a*z/\z} prints "z"
  4768. * (note that a*z _pattern_ is never globbed!)
  4769. */
  4770. char *pattern, *repl, *t;
  4771. pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
  4772. if (!pattern)
  4773. pattern = xstrdup(exp_word);
  4774. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  4775. *p++ = SPECIAL_VAR_SYMBOL;
  4776. exp_word = p;
  4777. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4778. *p = '\0';
  4779. repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
  4780. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  4781. /* HACK ALERT. We depend here on the fact that
  4782. * G.global_argv and results of utoa and get_local_var_value
  4783. * are actually in writable memory:
  4784. * replace_pattern momentarily stores NULs there. */
  4785. t = (char*)val;
  4786. to_be_freed = replace_pattern(t,
  4787. pattern,
  4788. (repl ? repl : exp_word),
  4789. exp_op);
  4790. if (to_be_freed) /* at least one replace happened */
  4791. val = to_be_freed;
  4792. free(pattern);
  4793. free(repl);
  4794. }
  4795. }
  4796. #endif
  4797. else if (exp_op == ':') {
  4798. #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
  4799. /* It's ${var:N[:M]} bashism.
  4800. * Note that in encoded form it has TWO parts:
  4801. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  4802. */
  4803. arith_t beg, len;
  4804. const char *errmsg;
  4805. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  4806. if (errmsg)
  4807. goto arith_err;
  4808. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  4809. *p++ = SPECIAL_VAR_SYMBOL;
  4810. exp_word = p;
  4811. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4812. *p = '\0';
  4813. len = expand_and_evaluate_arith(exp_word, &errmsg);
  4814. if (errmsg)
  4815. goto arith_err;
  4816. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  4817. if (len >= 0) { /* bash compat: len < 0 is illegal */
  4818. if (beg < 0) /* bash compat */
  4819. beg = 0;
  4820. debug_printf_varexp("from val:'%s'\n", val);
  4821. if (len == 0 || !val || beg >= strlen(val)) {
  4822. arith_err:
  4823. val = NULL;
  4824. } else {
  4825. /* Paranoia. What if user entered 9999999999999
  4826. * which fits in arith_t but not int? */
  4827. if (len >= INT_MAX)
  4828. len = INT_MAX;
  4829. val = to_be_freed = xstrndup(val + beg, len);
  4830. }
  4831. debug_printf_varexp("val:'%s'\n", val);
  4832. } else
  4833. #endif
  4834. {
  4835. die_if_script("malformed ${%s:...}", var);
  4836. val = NULL;
  4837. }
  4838. } else { /* one of "-=+?" */
  4839. /* Standard-mandated substitution ops:
  4840. * ${var?word} - indicate error if unset
  4841. * If var is unset, word (or a message indicating it is unset
  4842. * if word is null) is written to standard error
  4843. * and the shell exits with a non-zero exit status.
  4844. * Otherwise, the value of var is substituted.
  4845. * ${var-word} - use default value
  4846. * If var is unset, word is substituted.
  4847. * ${var=word} - assign and use default value
  4848. * If var is unset, word is assigned to var.
  4849. * In all cases, final value of var is substituted.
  4850. * ${var+word} - use alternative value
  4851. * If var is unset, null is substituted.
  4852. * Otherwise, word is substituted.
  4853. *
  4854. * Word is subjected to tilde expansion, parameter expansion,
  4855. * command substitution, and arithmetic expansion.
  4856. * If word is not needed, it is not expanded.
  4857. *
  4858. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  4859. * but also treat null var as if it is unset.
  4860. */
  4861. int use_word = (!val || ((exp_save == ':') && !val[0]));
  4862. if (exp_op == '+')
  4863. use_word = !use_word;
  4864. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  4865. (exp_save == ':') ? "true" : "false", use_word);
  4866. if (use_word) {
  4867. to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4868. if (to_be_freed)
  4869. exp_word = to_be_freed;
  4870. if (exp_op == '?') {
  4871. /* mimic bash message */
  4872. die_if_script("%s: %s",
  4873. var,
  4874. exp_word[0] ? exp_word : "parameter null or not set"
  4875. );
  4876. //TODO: how interactive bash aborts expansion mid-command?
  4877. } else {
  4878. val = exp_word;
  4879. }
  4880. if (exp_op == '=') {
  4881. /* ${var=[word]} or ${var:=[word]} */
  4882. if (isdigit(var[0]) || var[0] == '#') {
  4883. /* mimic bash message */
  4884. die_if_script("$%s: cannot assign in this way", var);
  4885. val = NULL;
  4886. } else {
  4887. char *new_var = xasprintf("%s=%s", var, val);
  4888. set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  4889. }
  4890. }
  4891. }
  4892. } /* one of "-=+?" */
  4893. *exp_saveptr = exp_save;
  4894. } /* if (exp_op) */
  4895. arg[0] = arg0;
  4896. *pp = p;
  4897. *to_be_freed_pp = to_be_freed;
  4898. return val;
  4899. }
  4900. /* Expand all variable references in given string, adding words to list[]
  4901. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  4902. * to be filled). This routine is extremely tricky: has to deal with
  4903. * variables/parameters with whitespace, $* and $@, and constructs like
  4904. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  4905. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  4906. {
  4907. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  4908. * expansion of right-hand side of assignment == 1-element expand.
  4909. */
  4910. char cant_be_null = 0; /* only bit 0x80 matters */
  4911. int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
  4912. char *p;
  4913. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  4914. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  4915. debug_print_list("expand_vars_to_list", output, n);
  4916. n = o_save_ptr(output, n);
  4917. debug_print_list("expand_vars_to_list[0]", output, n);
  4918. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  4919. char first_ch;
  4920. char *to_be_freed = NULL;
  4921. const char *val = NULL;
  4922. #if ENABLE_HUSH_TICK
  4923. o_string subst_result = NULL_O_STRING;
  4924. #endif
  4925. #if ENABLE_SH_MATH_SUPPORT
  4926. char arith_buf[sizeof(arith_t)*3 + 2];
  4927. #endif
  4928. if (ended_in_ifs) {
  4929. o_addchr(output, '\0');
  4930. n = o_save_ptr(output, n);
  4931. ended_in_ifs = 0;
  4932. }
  4933. o_addblock(output, arg, p - arg);
  4934. debug_print_list("expand_vars_to_list[1]", output, n);
  4935. arg = ++p;
  4936. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4937. /* Fetch special var name (if it is indeed one of them)
  4938. * and quote bit, force the bit on if singleword expansion -
  4939. * important for not getting v=$@ expand to many words. */
  4940. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  4941. /* Is this variable quoted and thus expansion can't be null?
  4942. * "$@" is special. Even if quoted, it can still
  4943. * expand to nothing (not even an empty string),
  4944. * thus it is excluded. */
  4945. if ((first_ch & 0x7f) != '@')
  4946. cant_be_null |= first_ch;
  4947. switch (first_ch & 0x7f) {
  4948. /* Highest bit in first_ch indicates that var is double-quoted */
  4949. case '*':
  4950. case '@': {
  4951. int i;
  4952. if (!G.global_argv[1])
  4953. break;
  4954. i = 1;
  4955. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  4956. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  4957. while (G.global_argv[i]) {
  4958. n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
  4959. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  4960. if (G.global_argv[i++][0] && G.global_argv[i]) {
  4961. /* this argv[] is not empty and not last:
  4962. * put terminating NUL, start new word */
  4963. o_addchr(output, '\0');
  4964. debug_print_list("expand_vars_to_list[2]", output, n);
  4965. n = o_save_ptr(output, n);
  4966. debug_print_list("expand_vars_to_list[3]", output, n);
  4967. }
  4968. }
  4969. } else
  4970. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  4971. * and in this case should treat it like '$*' - see 'else...' below */
  4972. if (first_ch == ('@'|0x80) /* quoted $@ */
  4973. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  4974. ) {
  4975. while (1) {
  4976. o_addQstr(output, G.global_argv[i]);
  4977. if (++i >= G.global_argc)
  4978. break;
  4979. o_addchr(output, '\0');
  4980. debug_print_list("expand_vars_to_list[4]", output, n);
  4981. n = o_save_ptr(output, n);
  4982. }
  4983. } else { /* quoted $* (or v="$@" case): add as one word */
  4984. while (1) {
  4985. o_addQstr(output, G.global_argv[i]);
  4986. if (!G.global_argv[++i])
  4987. break;
  4988. if (G.ifs[0])
  4989. o_addchr(output, G.ifs[0]);
  4990. }
  4991. output->has_quoted_part = 1;
  4992. }
  4993. break;
  4994. }
  4995. case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  4996. /* "Empty variable", used to make "" etc to not disappear */
  4997. output->has_quoted_part = 1;
  4998. arg++;
  4999. cant_be_null = 0x80;
  5000. break;
  5001. #if ENABLE_HUSH_TICK
  5002. case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  5003. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5004. arg++;
  5005. /* Can't just stuff it into output o_string,
  5006. * expanded result may need to be globbed
  5007. * and $IFS-splitted */
  5008. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  5009. G.last_exitcode = process_command_subs(&subst_result, arg);
  5010. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  5011. val = subst_result.data;
  5012. goto store_val;
  5013. #endif
  5014. #if ENABLE_SH_MATH_SUPPORT
  5015. case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
  5016. arith_t res;
  5017. arg++; /* skip '+' */
  5018. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5019. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  5020. res = expand_and_evaluate_arith(arg, NULL);
  5021. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  5022. sprintf(arith_buf, ARITH_FMT, res);
  5023. val = arith_buf;
  5024. break;
  5025. }
  5026. #endif
  5027. default:
  5028. val = expand_one_var(&to_be_freed, arg, &p);
  5029. IF_HUSH_TICK(store_val:)
  5030. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5031. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5032. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5033. if (val && val[0]) {
  5034. n = expand_on_ifs(&ended_in_ifs, output, n, val);
  5035. val = NULL;
  5036. }
  5037. } else { /* quoted $VAR, val will be appended below */
  5038. output->has_quoted_part = 1;
  5039. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5040. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5041. }
  5042. break;
  5043. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  5044. if (val && val[0]) {
  5045. o_addQstr(output, val);
  5046. }
  5047. free(to_be_freed);
  5048. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  5049. * Do the check to avoid writing to a const string. */
  5050. if (*p != SPECIAL_VAR_SYMBOL)
  5051. *p = SPECIAL_VAR_SYMBOL;
  5052. #if ENABLE_HUSH_TICK
  5053. o_free(&subst_result);
  5054. #endif
  5055. arg = ++p;
  5056. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  5057. if (arg[0]) {
  5058. if (ended_in_ifs) {
  5059. o_addchr(output, '\0');
  5060. n = o_save_ptr(output, n);
  5061. }
  5062. debug_print_list("expand_vars_to_list[a]", output, n);
  5063. /* this part is literal, and it was already pre-quoted
  5064. * if needed (much earlier), do not use o_addQstr here! */
  5065. o_addstr_with_NUL(output, arg);
  5066. debug_print_list("expand_vars_to_list[b]", output, n);
  5067. } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  5068. && !(cant_be_null & 0x80) /* and all vars were not quoted. */
  5069. ) {
  5070. n--;
  5071. /* allow to reuse list[n] later without re-growth */
  5072. output->has_empty_slot = 1;
  5073. } else {
  5074. o_addchr(output, '\0');
  5075. }
  5076. return n;
  5077. }
  5078. static char **expand_variables(char **argv, unsigned expflags)
  5079. {
  5080. int n;
  5081. char **list;
  5082. o_string output = NULL_O_STRING;
  5083. output.o_expflags = expflags;
  5084. n = 0;
  5085. while (*argv) {
  5086. n = expand_vars_to_list(&output, n, *argv);
  5087. argv++;
  5088. }
  5089. debug_print_list("expand_variables", &output, n);
  5090. /* output.data (malloced in one block) gets returned in "list" */
  5091. list = o_finalize_list(&output, n);
  5092. debug_print_strings("expand_variables[1]", list);
  5093. return list;
  5094. }
  5095. static char **expand_strvec_to_strvec(char **argv)
  5096. {
  5097. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  5098. }
  5099. #if ENABLE_HUSH_BASH_COMPAT
  5100. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  5101. {
  5102. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  5103. }
  5104. #endif
  5105. /* Used for expansion of right hand of assignments,
  5106. * $((...)), heredocs, variable espansion parts.
  5107. *
  5108. * NB: should NOT do globbing!
  5109. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  5110. */
  5111. static char *expand_string_to_string(const char *str, int do_unbackslash)
  5112. {
  5113. #if !ENABLE_HUSH_BASH_COMPAT
  5114. const int do_unbackslash = 1;
  5115. #endif
  5116. char *argv[2], **list;
  5117. debug_printf_expand("string_to_string<='%s'\n", str);
  5118. /* This is generally an optimization, but it also
  5119. * handles "", which otherwise trips over !list[0] check below.
  5120. * (is this ever happens that we actually get str="" here?)
  5121. */
  5122. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  5123. //TODO: Can use on strings with \ too, just unbackslash() them?
  5124. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  5125. return xstrdup(str);
  5126. }
  5127. argv[0] = (char*)str;
  5128. argv[1] = NULL;
  5129. list = expand_variables(argv, do_unbackslash
  5130. ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
  5131. : EXP_FLAG_SINGLEWORD
  5132. );
  5133. if (HUSH_DEBUG)
  5134. if (!list[0] || list[1])
  5135. bb_error_msg_and_die("BUG in varexp2");
  5136. /* actually, just move string 2*sizeof(char*) bytes back */
  5137. overlapping_strcpy((char*)list, list[0]);
  5138. if (do_unbackslash)
  5139. unbackslash((char*)list);
  5140. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  5141. return (char*)list;
  5142. }
  5143. /* Used for "eval" builtin */
  5144. static char* expand_strvec_to_string(char **argv)
  5145. {
  5146. char **list;
  5147. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  5148. /* Convert all NULs to spaces */
  5149. if (list[0]) {
  5150. int n = 1;
  5151. while (list[n]) {
  5152. if (HUSH_DEBUG)
  5153. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  5154. bb_error_msg_and_die("BUG in varexp3");
  5155. /* bash uses ' ' regardless of $IFS contents */
  5156. list[n][-1] = ' ';
  5157. n++;
  5158. }
  5159. }
  5160. overlapping_strcpy((char*)list, list[0]);
  5161. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  5162. return (char*)list;
  5163. }
  5164. static char **expand_assignments(char **argv, int count)
  5165. {
  5166. int i;
  5167. char **p;
  5168. G.expanded_assignments = p = NULL;
  5169. /* Expand assignments into one string each */
  5170. for (i = 0; i < count; i++) {
  5171. G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
  5172. }
  5173. G.expanded_assignments = NULL;
  5174. return p;
  5175. }
  5176. static void switch_off_special_sigs(unsigned mask)
  5177. {
  5178. unsigned sig = 0;
  5179. while ((mask >>= 1) != 0) {
  5180. sig++;
  5181. if (!(mask & 1))
  5182. continue;
  5183. if (G.traps) {
  5184. if (G.traps[sig] && !G.traps[sig][0])
  5185. /* trap is '', has to remain SIG_IGN */
  5186. continue;
  5187. free(G.traps[sig]);
  5188. G.traps[sig] = NULL;
  5189. }
  5190. /* We are here only if no trap or trap was not '' */
  5191. install_sighandler(sig, SIG_DFL);
  5192. }
  5193. }
  5194. #if BB_MMU
  5195. /* never called */
  5196. void re_execute_shell(char ***to_free, const char *s,
  5197. char *g_argv0, char **g_argv,
  5198. char **builtin_argv) NORETURN;
  5199. static void reset_traps_to_defaults(void)
  5200. {
  5201. /* This function is always called in a child shell
  5202. * after fork (not vfork, NOMMU doesn't use this function).
  5203. */
  5204. unsigned sig;
  5205. unsigned mask;
  5206. /* Child shells are not interactive.
  5207. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  5208. * Testcase: (while :; do :; done) + ^Z should background.
  5209. * Same goes for SIGTERM, SIGHUP, SIGINT.
  5210. */
  5211. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  5212. if (!G.traps && !mask)
  5213. return; /* already no traps and no special sigs */
  5214. /* Switch off special sigs */
  5215. switch_off_special_sigs(mask);
  5216. #if ENABLE_HUSH_JOB
  5217. G_fatal_sig_mask = 0;
  5218. #endif
  5219. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  5220. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  5221. * remain set in G.special_sig_mask */
  5222. if (!G.traps)
  5223. return;
  5224. /* Reset all sigs to default except ones with empty traps */
  5225. for (sig = 0; sig < NSIG; sig++) {
  5226. if (!G.traps[sig])
  5227. continue; /* no trap: nothing to do */
  5228. if (!G.traps[sig][0])
  5229. continue; /* empty trap: has to remain SIG_IGN */
  5230. /* sig has non-empty trap, reset it: */
  5231. free(G.traps[sig]);
  5232. G.traps[sig] = NULL;
  5233. /* There is no signal for trap 0 (EXIT) */
  5234. if (sig == 0)
  5235. continue;
  5236. install_sighandler(sig, pick_sighandler(sig));
  5237. }
  5238. }
  5239. #else /* !BB_MMU */
  5240. static void re_execute_shell(char ***to_free, const char *s,
  5241. char *g_argv0, char **g_argv,
  5242. char **builtin_argv) NORETURN;
  5243. static void re_execute_shell(char ***to_free, const char *s,
  5244. char *g_argv0, char **g_argv,
  5245. char **builtin_argv)
  5246. {
  5247. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  5248. /* delims + 2 * (number of bytes in printed hex numbers) */
  5249. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  5250. char *heredoc_argv[4];
  5251. struct variable *cur;
  5252. # if ENABLE_HUSH_FUNCTIONS
  5253. struct function *funcp;
  5254. # endif
  5255. char **argv, **pp;
  5256. unsigned cnt;
  5257. unsigned long long empty_trap_mask;
  5258. if (!g_argv0) { /* heredoc */
  5259. argv = heredoc_argv;
  5260. argv[0] = (char *) G.argv0_for_re_execing;
  5261. argv[1] = (char *) "-<";
  5262. argv[2] = (char *) s;
  5263. argv[3] = NULL;
  5264. pp = &argv[3]; /* used as pointer to empty environment */
  5265. goto do_exec;
  5266. }
  5267. cnt = 0;
  5268. pp = builtin_argv;
  5269. if (pp) while (*pp++)
  5270. cnt++;
  5271. empty_trap_mask = 0;
  5272. if (G.traps) {
  5273. int sig;
  5274. for (sig = 1; sig < NSIG; sig++) {
  5275. if (G.traps[sig] && !G.traps[sig][0])
  5276. empty_trap_mask |= 1LL << sig;
  5277. }
  5278. }
  5279. sprintf(param_buf, NOMMU_HACK_FMT
  5280. , (unsigned) G.root_pid
  5281. , (unsigned) G.root_ppid
  5282. , (unsigned) G.last_bg_pid
  5283. , (unsigned) G.last_exitcode
  5284. , cnt
  5285. , empty_trap_mask
  5286. IF_HUSH_LOOPS(, G.depth_of_loop)
  5287. );
  5288. # undef NOMMU_HACK_FMT
  5289. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  5290. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  5291. */
  5292. cnt += 6;
  5293. for (cur = G.top_var; cur; cur = cur->next) {
  5294. if (!cur->flg_export || cur->flg_read_only)
  5295. cnt += 2;
  5296. }
  5297. # if ENABLE_HUSH_FUNCTIONS
  5298. for (funcp = G.top_func; funcp; funcp = funcp->next)
  5299. cnt += 3;
  5300. # endif
  5301. pp = g_argv;
  5302. while (*pp++)
  5303. cnt++;
  5304. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  5305. *pp++ = (char *) G.argv0_for_re_execing;
  5306. *pp++ = param_buf;
  5307. for (cur = G.top_var; cur; cur = cur->next) {
  5308. if (strcmp(cur->varstr, hush_version_str) == 0)
  5309. continue;
  5310. if (cur->flg_read_only) {
  5311. *pp++ = (char *) "-R";
  5312. *pp++ = cur->varstr;
  5313. } else if (!cur->flg_export) {
  5314. *pp++ = (char *) "-V";
  5315. *pp++ = cur->varstr;
  5316. }
  5317. }
  5318. # if ENABLE_HUSH_FUNCTIONS
  5319. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  5320. *pp++ = (char *) "-F";
  5321. *pp++ = funcp->name;
  5322. *pp++ = funcp->body_as_string;
  5323. }
  5324. # endif
  5325. /* We can pass activated traps here. Say, -Tnn:trap_string
  5326. *
  5327. * However, POSIX says that subshells reset signals with traps
  5328. * to SIG_DFL.
  5329. * I tested bash-3.2 and it not only does that with true subshells
  5330. * of the form ( list ), but with any forked children shells.
  5331. * I set trap "echo W" WINCH; and then tried:
  5332. *
  5333. * { echo 1; sleep 20; echo 2; } &
  5334. * while true; do echo 1; sleep 20; echo 2; break; done &
  5335. * true | { echo 1; sleep 20; echo 2; } | cat
  5336. *
  5337. * In all these cases sending SIGWINCH to the child shell
  5338. * did not run the trap. If I add trap "echo V" WINCH;
  5339. * _inside_ group (just before echo 1), it works.
  5340. *
  5341. * I conclude it means we don't need to pass active traps here.
  5342. */
  5343. *pp++ = (char *) "-c";
  5344. *pp++ = (char *) s;
  5345. if (builtin_argv) {
  5346. while (*++builtin_argv)
  5347. *pp++ = *builtin_argv;
  5348. *pp++ = (char *) "";
  5349. }
  5350. *pp++ = g_argv0;
  5351. while (*g_argv)
  5352. *pp++ = *g_argv++;
  5353. /* *pp = NULL; - is already there */
  5354. pp = environ;
  5355. do_exec:
  5356. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  5357. /* Don't propagate SIG_IGN to the child */
  5358. if (SPECIAL_JOBSTOP_SIGS != 0)
  5359. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  5360. execve(bb_busybox_exec_path, argv, pp);
  5361. /* Fallback. Useful for init=/bin/hush usage etc */
  5362. if (argv[0][0] == '/')
  5363. execve(argv[0], argv, pp);
  5364. xfunc_error_retval = 127;
  5365. bb_error_msg_and_die("can't re-execute the shell");
  5366. }
  5367. #endif /* !BB_MMU */
  5368. static int run_and_free_list(struct pipe *pi);
  5369. /* Executing from string: eval, sh -c '...'
  5370. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  5371. * end_trigger controls how often we stop parsing
  5372. * NUL: parse all, execute, return
  5373. * ';': parse till ';' or newline, execute, repeat till EOF
  5374. */
  5375. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  5376. {
  5377. /* Why we need empty flag?
  5378. * An obscure corner case "false; ``; echo $?":
  5379. * empty command in `` should still set $? to 0.
  5380. * But we can't just set $? to 0 at the start,
  5381. * this breaks "false; echo `echo $?`" case.
  5382. */
  5383. bool empty = 1;
  5384. while (1) {
  5385. struct pipe *pipe_list;
  5386. #if ENABLE_HUSH_INTERACTIVE
  5387. if (end_trigger == ';')
  5388. inp->promptmode = 0; /* PS1 */
  5389. #endif
  5390. pipe_list = parse_stream(NULL, inp, end_trigger);
  5391. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  5392. /* If we are in "big" script
  5393. * (not in `cmd` or something similar)...
  5394. */
  5395. if (pipe_list == ERR_PTR && end_trigger == ';') {
  5396. /* Discard cached input (rest of line) */
  5397. int ch = inp->last_char;
  5398. while (ch != EOF && ch != '\n') {
  5399. //bb_error_msg("Discarded:'%c'", ch);
  5400. ch = i_getch(inp);
  5401. }
  5402. /* Force prompt */
  5403. inp->p = NULL;
  5404. /* This stream isn't empty */
  5405. empty = 0;
  5406. continue;
  5407. }
  5408. if (!pipe_list && empty)
  5409. G.last_exitcode = 0;
  5410. break;
  5411. }
  5412. debug_print_tree(pipe_list, 0);
  5413. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  5414. run_and_free_list(pipe_list);
  5415. empty = 0;
  5416. #if ENABLE_HUSH_FUNCTIONS
  5417. if (G.flag_return_in_progress == 1)
  5418. break;
  5419. #endif
  5420. }
  5421. }
  5422. static void parse_and_run_string(const char *s)
  5423. {
  5424. struct in_str input;
  5425. setup_string_in_str(&input, s);
  5426. parse_and_run_stream(&input, '\0');
  5427. }
  5428. static void parse_and_run_file(FILE *f)
  5429. {
  5430. struct in_str input;
  5431. setup_file_in_str(&input, f);
  5432. parse_and_run_stream(&input, ';');
  5433. }
  5434. #if ENABLE_HUSH_TICK
  5435. static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
  5436. {
  5437. pid_t pid;
  5438. int channel[2];
  5439. # if !BB_MMU
  5440. char **to_free = NULL;
  5441. # endif
  5442. xpipe(channel);
  5443. pid = BB_MMU ? xfork() : xvfork();
  5444. if (pid == 0) { /* child */
  5445. disable_restore_tty_pgrp_on_exit();
  5446. /* Process substitution is not considered to be usual
  5447. * 'command execution'.
  5448. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  5449. */
  5450. bb_signals(0
  5451. + (1 << SIGTSTP)
  5452. + (1 << SIGTTIN)
  5453. + (1 << SIGTTOU)
  5454. , SIG_IGN);
  5455. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  5456. close(channel[0]); /* NB: close _first_, then move fd! */
  5457. xmove_fd(channel[1], 1);
  5458. /* Prevent it from trying to handle ctrl-z etc */
  5459. IF_HUSH_JOB(G.run_list_level = 1;)
  5460. /* Awful hack for `trap` or $(trap).
  5461. *
  5462. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  5463. * contains an example where "trap" is executed in a subshell:
  5464. *
  5465. * save_traps=$(trap)
  5466. * ...
  5467. * eval "$save_traps"
  5468. *
  5469. * Standard does not say that "trap" in subshell shall print
  5470. * parent shell's traps. It only says that its output
  5471. * must have suitable form, but then, in the above example
  5472. * (which is not supposed to be normative), it implies that.
  5473. *
  5474. * bash (and probably other shell) does implement it
  5475. * (traps are reset to defaults, but "trap" still shows them),
  5476. * but as a result, "trap" logic is hopelessly messed up:
  5477. *
  5478. * # trap
  5479. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  5480. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  5481. * # true | trap <--- trap is in subshell - no output (ditto)
  5482. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  5483. * trap -- 'echo Ho' SIGWINCH
  5484. * # echo `(trap)` <--- in subshell in subshell - output
  5485. * trap -- 'echo Ho' SIGWINCH
  5486. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  5487. * trap -- 'echo Ho' SIGWINCH
  5488. *
  5489. * The rules when to forget and when to not forget traps
  5490. * get really complex and nonsensical.
  5491. *
  5492. * Our solution: ONLY bare $(trap) or `trap` is special.
  5493. */
  5494. s = skip_whitespace(s);
  5495. if (strncmp(s, "trap", 4) == 0
  5496. && skip_whitespace(s + 4)[0] == '\0'
  5497. ) {
  5498. static const char *const argv[] = { NULL, NULL };
  5499. builtin_trap((char**)argv);
  5500. exit(0); /* not _exit() - we need to fflush */
  5501. }
  5502. # if BB_MMU
  5503. reset_traps_to_defaults();
  5504. parse_and_run_string(s);
  5505. _exit(G.last_exitcode);
  5506. # else
  5507. /* We re-execute after vfork on NOMMU. This makes this script safe:
  5508. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  5509. * huge=`cat BIG` # was blocking here forever
  5510. * echo OK
  5511. */
  5512. re_execute_shell(&to_free,
  5513. s,
  5514. G.global_argv[0],
  5515. G.global_argv + 1,
  5516. NULL);
  5517. # endif
  5518. }
  5519. /* parent */
  5520. *pid_p = pid;
  5521. # if ENABLE_HUSH_FAST
  5522. G.count_SIGCHLD++;
  5523. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  5524. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  5525. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  5526. # endif
  5527. enable_restore_tty_pgrp_on_exit();
  5528. # if !BB_MMU
  5529. free(to_free);
  5530. # endif
  5531. close(channel[1]);
  5532. close_on_exec_on(channel[0]);
  5533. return xfdopen_for_read(channel[0]);
  5534. }
  5535. /* Return code is exit status of the process that is run. */
  5536. static int process_command_subs(o_string *dest, const char *s)
  5537. {
  5538. FILE *fp;
  5539. struct in_str pipe_str;
  5540. pid_t pid;
  5541. int status, ch, eol_cnt;
  5542. fp = generate_stream_from_string(s, &pid);
  5543. /* Now send results of command back into original context */
  5544. setup_file_in_str(&pipe_str, fp);
  5545. eol_cnt = 0;
  5546. while ((ch = i_getch(&pipe_str)) != EOF) {
  5547. if (ch == '\n') {
  5548. eol_cnt++;
  5549. continue;
  5550. }
  5551. while (eol_cnt) {
  5552. o_addchr(dest, '\n');
  5553. eol_cnt--;
  5554. }
  5555. o_addQchr(dest, ch);
  5556. }
  5557. debug_printf("done reading from `cmd` pipe, closing it\n");
  5558. fclose(fp);
  5559. /* We need to extract exitcode. Test case
  5560. * "true; echo `sleep 1; false` $?"
  5561. * should print 1 */
  5562. safe_waitpid(pid, &status, 0);
  5563. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  5564. return WEXITSTATUS(status);
  5565. }
  5566. #endif /* ENABLE_HUSH_TICK */
  5567. static void setup_heredoc(struct redir_struct *redir)
  5568. {
  5569. struct fd_pair pair;
  5570. pid_t pid;
  5571. int len, written;
  5572. /* the _body_ of heredoc (misleading field name) */
  5573. const char *heredoc = redir->rd_filename;
  5574. char *expanded;
  5575. #if !BB_MMU
  5576. char **to_free;
  5577. #endif
  5578. expanded = NULL;
  5579. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  5580. expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  5581. if (expanded)
  5582. heredoc = expanded;
  5583. }
  5584. len = strlen(heredoc);
  5585. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  5586. xpiped_pair(pair);
  5587. xmove_fd(pair.rd, redir->rd_fd);
  5588. /* Try writing without forking. Newer kernels have
  5589. * dynamically growing pipes. Must use non-blocking write! */
  5590. ndelay_on(pair.wr);
  5591. while (1) {
  5592. written = write(pair.wr, heredoc, len);
  5593. if (written <= 0)
  5594. break;
  5595. len -= written;
  5596. if (len == 0) {
  5597. close(pair.wr);
  5598. free(expanded);
  5599. return;
  5600. }
  5601. heredoc += written;
  5602. }
  5603. ndelay_off(pair.wr);
  5604. /* Okay, pipe buffer was not big enough */
  5605. /* Note: we must not create a stray child (bastard? :)
  5606. * for the unsuspecting parent process. Child creates a grandchild
  5607. * and exits before parent execs the process which consumes heredoc
  5608. * (that exec happens after we return from this function) */
  5609. #if !BB_MMU
  5610. to_free = NULL;
  5611. #endif
  5612. pid = xvfork();
  5613. if (pid == 0) {
  5614. /* child */
  5615. disable_restore_tty_pgrp_on_exit();
  5616. pid = BB_MMU ? xfork() : xvfork();
  5617. if (pid != 0)
  5618. _exit(0);
  5619. /* grandchild */
  5620. close(redir->rd_fd); /* read side of the pipe */
  5621. #if BB_MMU
  5622. full_write(pair.wr, heredoc, len); /* may loop or block */
  5623. _exit(0);
  5624. #else
  5625. /* Delegate blocking writes to another process */
  5626. xmove_fd(pair.wr, STDOUT_FILENO);
  5627. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  5628. #endif
  5629. }
  5630. /* parent */
  5631. #if ENABLE_HUSH_FAST
  5632. G.count_SIGCHLD++;
  5633. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  5634. #endif
  5635. enable_restore_tty_pgrp_on_exit();
  5636. #if !BB_MMU
  5637. free(to_free);
  5638. #endif
  5639. close(pair.wr);
  5640. free(expanded);
  5641. wait(NULL); /* wait till child has died */
  5642. }
  5643. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  5644. * and stderr if they are redirected. */
  5645. static int setup_redirects(struct command *prog, int squirrel[])
  5646. {
  5647. int openfd, mode;
  5648. struct redir_struct *redir;
  5649. for (redir = prog->redirects; redir; redir = redir->next) {
  5650. if (redir->rd_type == REDIRECT_HEREDOC2) {
  5651. /* rd_fd<<HERE case */
  5652. if (squirrel && redir->rd_fd < 3
  5653. && squirrel[redir->rd_fd] < 0
  5654. ) {
  5655. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  5656. }
  5657. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  5658. * of the heredoc */
  5659. debug_printf_parse("set heredoc '%s'\n",
  5660. redir->rd_filename);
  5661. setup_heredoc(redir);
  5662. continue;
  5663. }
  5664. if (redir->rd_dup == REDIRFD_TO_FILE) {
  5665. /* rd_fd<*>file case (<*> is <,>,>>,<>) */
  5666. char *p;
  5667. if (redir->rd_filename == NULL) {
  5668. /* Something went wrong in the parse.
  5669. * Pretend it didn't happen */
  5670. bb_error_msg("bug in redirect parse");
  5671. continue;
  5672. }
  5673. mode = redir_table[redir->rd_type].mode;
  5674. p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
  5675. openfd = open_or_warn(p, mode);
  5676. free(p);
  5677. if (openfd < 0) {
  5678. /* this could get lost if stderr has been redirected, but
  5679. * bash and ash both lose it as well (though zsh doesn't!) */
  5680. //what the above comment tries to say?
  5681. return 1;
  5682. }
  5683. } else {
  5684. /* rd_fd<*>rd_dup or rd_fd<*>- cases */
  5685. openfd = redir->rd_dup;
  5686. }
  5687. if (openfd != redir->rd_fd) {
  5688. if (squirrel && redir->rd_fd < 3
  5689. && squirrel[redir->rd_fd] < 0
  5690. ) {
  5691. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  5692. }
  5693. if (openfd == REDIRFD_CLOSE) {
  5694. /* "n>-" means "close me" */
  5695. close(redir->rd_fd);
  5696. } else {
  5697. xdup2(openfd, redir->rd_fd);
  5698. if (redir->rd_dup == REDIRFD_TO_FILE)
  5699. close(openfd);
  5700. }
  5701. }
  5702. }
  5703. return 0;
  5704. }
  5705. static void restore_redirects(int squirrel[])
  5706. {
  5707. int i, fd;
  5708. for (i = 0; i < 3; i++) {
  5709. fd = squirrel[i];
  5710. if (fd != -1) {
  5711. /* We simply die on error */
  5712. xmove_fd(fd, i);
  5713. }
  5714. }
  5715. }
  5716. static char *find_in_path(const char *arg)
  5717. {
  5718. char *ret = NULL;
  5719. const char *PATH = get_local_var_value("PATH");
  5720. if (!PATH)
  5721. return NULL;
  5722. while (1) {
  5723. const char *end = strchrnul(PATH, ':');
  5724. int sz = end - PATH; /* must be int! */
  5725. free(ret);
  5726. if (sz != 0) {
  5727. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  5728. } else {
  5729. /* We have xxx::yyyy in $PATH,
  5730. * it means "use current dir" */
  5731. ret = xstrdup(arg);
  5732. }
  5733. if (access(ret, F_OK) == 0)
  5734. break;
  5735. if (*end == '\0') {
  5736. free(ret);
  5737. return NULL;
  5738. }
  5739. PATH = end + 1;
  5740. }
  5741. return ret;
  5742. }
  5743. static const struct built_in_command *find_builtin_helper(const char *name,
  5744. const struct built_in_command *x,
  5745. const struct built_in_command *end)
  5746. {
  5747. while (x != end) {
  5748. if (strcmp(name, x->b_cmd) != 0) {
  5749. x++;
  5750. continue;
  5751. }
  5752. debug_printf_exec("found builtin '%s'\n", name);
  5753. return x;
  5754. }
  5755. return NULL;
  5756. }
  5757. static const struct built_in_command *find_builtin1(const char *name)
  5758. {
  5759. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  5760. }
  5761. static const struct built_in_command *find_builtin(const char *name)
  5762. {
  5763. const struct built_in_command *x = find_builtin1(name);
  5764. if (x)
  5765. return x;
  5766. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  5767. }
  5768. #if ENABLE_HUSH_FUNCTIONS
  5769. static struct function **find_function_slot(const char *name)
  5770. {
  5771. struct function **funcpp = &G.top_func;
  5772. while (*funcpp) {
  5773. if (strcmp(name, (*funcpp)->name) == 0) {
  5774. break;
  5775. }
  5776. funcpp = &(*funcpp)->next;
  5777. }
  5778. return funcpp;
  5779. }
  5780. static const struct function *find_function(const char *name)
  5781. {
  5782. const struct function *funcp = *find_function_slot(name);
  5783. if (funcp)
  5784. debug_printf_exec("found function '%s'\n", name);
  5785. return funcp;
  5786. }
  5787. /* Note: takes ownership on name ptr */
  5788. static struct function *new_function(char *name)
  5789. {
  5790. struct function **funcpp = find_function_slot(name);
  5791. struct function *funcp = *funcpp;
  5792. if (funcp != NULL) {
  5793. struct command *cmd = funcp->parent_cmd;
  5794. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  5795. if (!cmd) {
  5796. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  5797. free(funcp->name);
  5798. /* Note: if !funcp->body, do not free body_as_string!
  5799. * This is a special case of "-F name body" function:
  5800. * body_as_string was not malloced! */
  5801. if (funcp->body) {
  5802. free_pipe_list(funcp->body);
  5803. # if !BB_MMU
  5804. free(funcp->body_as_string);
  5805. # endif
  5806. }
  5807. } else {
  5808. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  5809. cmd->argv[0] = funcp->name;
  5810. cmd->group = funcp->body;
  5811. # if !BB_MMU
  5812. cmd->group_as_string = funcp->body_as_string;
  5813. # endif
  5814. }
  5815. } else {
  5816. debug_printf_exec("remembering new function '%s'\n", name);
  5817. funcp = *funcpp = xzalloc(sizeof(*funcp));
  5818. /*funcp->next = NULL;*/
  5819. }
  5820. funcp->name = name;
  5821. return funcp;
  5822. }
  5823. static void unset_func(const char *name)
  5824. {
  5825. struct function **funcpp = find_function_slot(name);
  5826. struct function *funcp = *funcpp;
  5827. if (funcp != NULL) {
  5828. debug_printf_exec("freeing function '%s'\n", funcp->name);
  5829. *funcpp = funcp->next;
  5830. /* funcp is unlinked now, deleting it.
  5831. * Note: if !funcp->body, the function was created by
  5832. * "-F name body", do not free ->body_as_string
  5833. * and ->name as they were not malloced. */
  5834. if (funcp->body) {
  5835. free_pipe_list(funcp->body);
  5836. free(funcp->name);
  5837. # if !BB_MMU
  5838. free(funcp->body_as_string);
  5839. # endif
  5840. }
  5841. free(funcp);
  5842. }
  5843. }
  5844. # if BB_MMU
  5845. #define exec_function(to_free, funcp, argv) \
  5846. exec_function(funcp, argv)
  5847. # endif
  5848. static void exec_function(char ***to_free,
  5849. const struct function *funcp,
  5850. char **argv) NORETURN;
  5851. static void exec_function(char ***to_free,
  5852. const struct function *funcp,
  5853. char **argv)
  5854. {
  5855. # if BB_MMU
  5856. int n = 1;
  5857. argv[0] = G.global_argv[0];
  5858. G.global_argv = argv;
  5859. while (*++argv)
  5860. n++;
  5861. G.global_argc = n;
  5862. /* On MMU, funcp->body is always non-NULL */
  5863. n = run_list(funcp->body);
  5864. fflush_all();
  5865. _exit(n);
  5866. # else
  5867. re_execute_shell(to_free,
  5868. funcp->body_as_string,
  5869. G.global_argv[0],
  5870. argv + 1,
  5871. NULL);
  5872. # endif
  5873. }
  5874. static int run_function(const struct function *funcp, char **argv)
  5875. {
  5876. int rc;
  5877. save_arg_t sv;
  5878. smallint sv_flg;
  5879. save_and_replace_G_args(&sv, argv);
  5880. /* "we are in function, ok to use return" */
  5881. sv_flg = G.flag_return_in_progress;
  5882. G.flag_return_in_progress = -1;
  5883. # if ENABLE_HUSH_LOCAL
  5884. G.func_nest_level++;
  5885. # endif
  5886. /* On MMU, funcp->body is always non-NULL */
  5887. # if !BB_MMU
  5888. if (!funcp->body) {
  5889. /* Function defined by -F */
  5890. parse_and_run_string(funcp->body_as_string);
  5891. rc = G.last_exitcode;
  5892. } else
  5893. # endif
  5894. {
  5895. rc = run_list(funcp->body);
  5896. }
  5897. # if ENABLE_HUSH_LOCAL
  5898. {
  5899. struct variable *var;
  5900. struct variable **var_pp;
  5901. var_pp = &G.top_var;
  5902. while ((var = *var_pp) != NULL) {
  5903. if (var->func_nest_level < G.func_nest_level) {
  5904. var_pp = &var->next;
  5905. continue;
  5906. }
  5907. /* Unexport */
  5908. if (var->flg_export)
  5909. bb_unsetenv(var->varstr);
  5910. /* Remove from global list */
  5911. *var_pp = var->next;
  5912. /* Free */
  5913. if (!var->max_len)
  5914. free(var->varstr);
  5915. free(var);
  5916. }
  5917. G.func_nest_level--;
  5918. }
  5919. # endif
  5920. G.flag_return_in_progress = sv_flg;
  5921. restore_G_args(&sv, argv);
  5922. return rc;
  5923. }
  5924. #endif /* ENABLE_HUSH_FUNCTIONS */
  5925. #if BB_MMU
  5926. #define exec_builtin(to_free, x, argv) \
  5927. exec_builtin(x, argv)
  5928. #else
  5929. #define exec_builtin(to_free, x, argv) \
  5930. exec_builtin(to_free, argv)
  5931. #endif
  5932. static void exec_builtin(char ***to_free,
  5933. const struct built_in_command *x,
  5934. char **argv) NORETURN;
  5935. static void exec_builtin(char ***to_free,
  5936. const struct built_in_command *x,
  5937. char **argv)
  5938. {
  5939. #if BB_MMU
  5940. int rcode;
  5941. fflush_all();
  5942. rcode = x->b_function(argv);
  5943. fflush_all();
  5944. _exit(rcode);
  5945. #else
  5946. fflush_all();
  5947. /* On NOMMU, we must never block!
  5948. * Example: { sleep 99 | read line; } & echo Ok
  5949. */
  5950. re_execute_shell(to_free,
  5951. argv[0],
  5952. G.global_argv[0],
  5953. G.global_argv + 1,
  5954. argv);
  5955. #endif
  5956. }
  5957. static void execvp_or_die(char **argv) NORETURN;
  5958. static void execvp_or_die(char **argv)
  5959. {
  5960. debug_printf_exec("execing '%s'\n", argv[0]);
  5961. /* Don't propagate SIG_IGN to the child */
  5962. if (SPECIAL_JOBSTOP_SIGS != 0)
  5963. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  5964. execvp(argv[0], argv);
  5965. bb_perror_msg("can't execute '%s'", argv[0]);
  5966. _exit(127); /* bash compat */
  5967. }
  5968. #if ENABLE_HUSH_MODE_X
  5969. static void dump_cmd_in_x_mode(char **argv)
  5970. {
  5971. if (G_x_mode && argv) {
  5972. /* We want to output the line in one write op */
  5973. char *buf, *p;
  5974. int len;
  5975. int n;
  5976. len = 3;
  5977. n = 0;
  5978. while (argv[n])
  5979. len += strlen(argv[n++]) + 1;
  5980. buf = xmalloc(len);
  5981. buf[0] = '+';
  5982. p = buf + 1;
  5983. n = 0;
  5984. while (argv[n])
  5985. p += sprintf(p, " %s", argv[n++]);
  5986. *p++ = '\n';
  5987. *p = '\0';
  5988. fputs(buf, stderr);
  5989. free(buf);
  5990. }
  5991. }
  5992. #else
  5993. # define dump_cmd_in_x_mode(argv) ((void)0)
  5994. #endif
  5995. #if BB_MMU
  5996. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  5997. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  5998. #define pseudo_exec(nommu_save, command, argv_expanded) \
  5999. pseudo_exec(command, argv_expanded)
  6000. #endif
  6001. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  6002. * Never returns.
  6003. * Don't exit() here. If you don't exec, use _exit instead.
  6004. * The at_exit handlers apparently confuse the calling process,
  6005. * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
  6006. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  6007. char **argv, int assignment_cnt,
  6008. char **argv_expanded) NORETURN;
  6009. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  6010. char **argv, int assignment_cnt,
  6011. char **argv_expanded)
  6012. {
  6013. char **new_env;
  6014. new_env = expand_assignments(argv, assignment_cnt);
  6015. dump_cmd_in_x_mode(new_env);
  6016. if (!argv[assignment_cnt]) {
  6017. /* Case when we are here: ... | var=val | ...
  6018. * (note that we do not exit early, i.e., do not optimize out
  6019. * expand_assignments(): think about ... | var=`sleep 1` | ...
  6020. */
  6021. free_strings(new_env);
  6022. _exit(EXIT_SUCCESS);
  6023. }
  6024. #if BB_MMU
  6025. set_vars_and_save_old(new_env);
  6026. free(new_env); /* optional */
  6027. /* we can also destroy set_vars_and_save_old's return value,
  6028. * to save memory */
  6029. #else
  6030. nommu_save->new_env = new_env;
  6031. nommu_save->old_vars = set_vars_and_save_old(new_env);
  6032. #endif
  6033. if (argv_expanded) {
  6034. argv = argv_expanded;
  6035. } else {
  6036. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  6037. #if !BB_MMU
  6038. nommu_save->argv = argv;
  6039. #endif
  6040. }
  6041. dump_cmd_in_x_mode(argv);
  6042. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  6043. if (strchr(argv[0], '/') != NULL)
  6044. goto skip;
  6045. #endif
  6046. /* Check if the command matches any of the builtins.
  6047. * Depending on context, this might be redundant. But it's
  6048. * easier to waste a few CPU cycles than it is to figure out
  6049. * if this is one of those cases.
  6050. */
  6051. {
  6052. /* On NOMMU, it is more expensive to re-execute shell
  6053. * just in order to run echo or test builtin.
  6054. * It's better to skip it here and run corresponding
  6055. * non-builtin later. */
  6056. const struct built_in_command *x;
  6057. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  6058. if (x) {
  6059. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  6060. }
  6061. }
  6062. #if ENABLE_HUSH_FUNCTIONS
  6063. /* Check if the command matches any functions */
  6064. {
  6065. const struct function *funcp = find_function(argv[0]);
  6066. if (funcp) {
  6067. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  6068. }
  6069. }
  6070. #endif
  6071. #if ENABLE_FEATURE_SH_STANDALONE
  6072. /* Check if the command matches any busybox applets */
  6073. {
  6074. int a = find_applet_by_name(argv[0]);
  6075. if (a >= 0) {
  6076. # if BB_MMU /* see above why on NOMMU it is not allowed */
  6077. if (APPLET_IS_NOEXEC(a)) {
  6078. debug_printf_exec("running applet '%s'\n", argv[0]);
  6079. run_applet_no_and_exit(a, argv);
  6080. }
  6081. # endif
  6082. /* Re-exec ourselves */
  6083. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  6084. /* Don't propagate SIG_IGN to the child */
  6085. if (SPECIAL_JOBSTOP_SIGS != 0)
  6086. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6087. execv(bb_busybox_exec_path, argv);
  6088. /* If they called chroot or otherwise made the binary no longer
  6089. * executable, fall through */
  6090. }
  6091. }
  6092. #endif
  6093. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  6094. skip:
  6095. #endif
  6096. execvp_or_die(argv);
  6097. }
  6098. /* Called after [v]fork() in run_pipe
  6099. */
  6100. static void pseudo_exec(nommu_save_t *nommu_save,
  6101. struct command *command,
  6102. char **argv_expanded) NORETURN;
  6103. static void pseudo_exec(nommu_save_t *nommu_save,
  6104. struct command *command,
  6105. char **argv_expanded)
  6106. {
  6107. if (command->argv) {
  6108. pseudo_exec_argv(nommu_save, command->argv,
  6109. command->assignment_cnt, argv_expanded);
  6110. }
  6111. if (command->group) {
  6112. /* Cases when we are here:
  6113. * ( list )
  6114. * { list } &
  6115. * ... | ( list ) | ...
  6116. * ... | { list } | ...
  6117. */
  6118. #if BB_MMU
  6119. int rcode;
  6120. debug_printf_exec("pseudo_exec: run_list\n");
  6121. reset_traps_to_defaults();
  6122. rcode = run_list(command->group);
  6123. /* OK to leak memory by not calling free_pipe_list,
  6124. * since this process is about to exit */
  6125. _exit(rcode);
  6126. #else
  6127. re_execute_shell(&nommu_save->argv_from_re_execing,
  6128. command->group_as_string,
  6129. G.global_argv[0],
  6130. G.global_argv + 1,
  6131. NULL);
  6132. #endif
  6133. }
  6134. /* Case when we are here: ... | >file */
  6135. debug_printf_exec("pseudo_exec'ed null command\n");
  6136. _exit(EXIT_SUCCESS);
  6137. }
  6138. #if ENABLE_HUSH_JOB
  6139. static const char *get_cmdtext(struct pipe *pi)
  6140. {
  6141. char **argv;
  6142. char *p;
  6143. int len;
  6144. /* This is subtle. ->cmdtext is created only on first backgrounding.
  6145. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  6146. * On subsequent bg argv is trashed, but we won't use it */
  6147. if (pi->cmdtext)
  6148. return pi->cmdtext;
  6149. argv = pi->cmds[0].argv;
  6150. if (!argv || !argv[0]) {
  6151. pi->cmdtext = xzalloc(1);
  6152. return pi->cmdtext;
  6153. }
  6154. len = 0;
  6155. do {
  6156. len += strlen(*argv) + 1;
  6157. } while (*++argv);
  6158. p = xmalloc(len);
  6159. pi->cmdtext = p;
  6160. argv = pi->cmds[0].argv;
  6161. do {
  6162. len = strlen(*argv);
  6163. memcpy(p, *argv, len);
  6164. p += len;
  6165. *p++ = ' ';
  6166. } while (*++argv);
  6167. p[-1] = '\0';
  6168. return pi->cmdtext;
  6169. }
  6170. static void insert_bg_job(struct pipe *pi)
  6171. {
  6172. struct pipe *job, **jobp;
  6173. int i;
  6174. /* Linear search for the ID of the job to use */
  6175. pi->jobid = 1;
  6176. for (job = G.job_list; job; job = job->next)
  6177. if (job->jobid >= pi->jobid)
  6178. pi->jobid = job->jobid + 1;
  6179. /* Add job to the list of running jobs */
  6180. jobp = &G.job_list;
  6181. while ((job = *jobp) != NULL)
  6182. jobp = &job->next;
  6183. job = *jobp = xmalloc(sizeof(*job));
  6184. *job = *pi; /* physical copy */
  6185. job->next = NULL;
  6186. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  6187. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  6188. for (i = 0; i < pi->num_cmds; i++) {
  6189. job->cmds[i].pid = pi->cmds[i].pid;
  6190. /* all other fields are not used and stay zero */
  6191. }
  6192. job->cmdtext = xstrdup(get_cmdtext(pi));
  6193. if (G_interactive_fd)
  6194. printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
  6195. G.last_jobid = job->jobid;
  6196. }
  6197. static void remove_bg_job(struct pipe *pi)
  6198. {
  6199. struct pipe *prev_pipe;
  6200. if (pi == G.job_list) {
  6201. G.job_list = pi->next;
  6202. } else {
  6203. prev_pipe = G.job_list;
  6204. while (prev_pipe->next != pi)
  6205. prev_pipe = prev_pipe->next;
  6206. prev_pipe->next = pi->next;
  6207. }
  6208. if (G.job_list)
  6209. G.last_jobid = G.job_list->jobid;
  6210. else
  6211. G.last_jobid = 0;
  6212. }
  6213. /* Remove a backgrounded job */
  6214. static void delete_finished_bg_job(struct pipe *pi)
  6215. {
  6216. remove_bg_job(pi);
  6217. free_pipe(pi);
  6218. }
  6219. #endif /* JOB */
  6220. /* Check to see if any processes have exited -- if they
  6221. * have, figure out why and see if a job has completed */
  6222. static int checkjobs(struct pipe *fg_pipe)
  6223. {
  6224. int attributes;
  6225. int status;
  6226. #if ENABLE_HUSH_JOB
  6227. struct pipe *pi;
  6228. #endif
  6229. pid_t childpid;
  6230. int rcode = 0;
  6231. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  6232. attributes = WUNTRACED;
  6233. if (fg_pipe == NULL)
  6234. attributes |= WNOHANG;
  6235. errno = 0;
  6236. #if ENABLE_HUSH_FAST
  6237. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  6238. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  6239. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  6240. /* There was neither fork nor SIGCHLD since last waitpid */
  6241. /* Avoid doing waitpid syscall if possible */
  6242. if (!G.we_have_children) {
  6243. errno = ECHILD;
  6244. return -1;
  6245. }
  6246. if (fg_pipe == NULL) { /* is WNOHANG set? */
  6247. /* We have children, but they did not exit
  6248. * or stop yet (we saw no SIGCHLD) */
  6249. return 0;
  6250. }
  6251. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  6252. }
  6253. #endif
  6254. /* Do we do this right?
  6255. * bash-3.00# sleep 20 | false
  6256. * <ctrl-Z pressed>
  6257. * [3]+ Stopped sleep 20 | false
  6258. * bash-3.00# echo $?
  6259. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  6260. * [hush 1.14.0: yes we do it right]
  6261. */
  6262. wait_more:
  6263. while (1) {
  6264. int i;
  6265. int dead;
  6266. #if ENABLE_HUSH_FAST
  6267. i = G.count_SIGCHLD;
  6268. #endif
  6269. childpid = waitpid(-1, &status, attributes);
  6270. if (childpid <= 0) {
  6271. if (childpid && errno != ECHILD)
  6272. bb_perror_msg("waitpid");
  6273. #if ENABLE_HUSH_FAST
  6274. else { /* Until next SIGCHLD, waitpid's are useless */
  6275. G.we_have_children = (childpid == 0);
  6276. G.handled_SIGCHLD = i;
  6277. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6278. }
  6279. #endif
  6280. break;
  6281. }
  6282. dead = WIFEXITED(status) || WIFSIGNALED(status);
  6283. #if DEBUG_JOBS
  6284. if (WIFSTOPPED(status))
  6285. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  6286. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  6287. if (WIFSIGNALED(status))
  6288. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  6289. childpid, WTERMSIG(status), WEXITSTATUS(status));
  6290. if (WIFEXITED(status))
  6291. debug_printf_jobs("pid %d exited, exitcode %d\n",
  6292. childpid, WEXITSTATUS(status));
  6293. #endif
  6294. /* Were we asked to wait for fg pipe? */
  6295. if (fg_pipe) {
  6296. i = fg_pipe->num_cmds;
  6297. while (--i >= 0) {
  6298. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  6299. if (fg_pipe->cmds[i].pid != childpid)
  6300. continue;
  6301. if (dead) {
  6302. int ex;
  6303. fg_pipe->cmds[i].pid = 0;
  6304. fg_pipe->alive_cmds--;
  6305. ex = WEXITSTATUS(status);
  6306. /* bash prints killer signal's name for *last*
  6307. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  6308. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  6309. */
  6310. if (WIFSIGNALED(status)) {
  6311. int sig = WTERMSIG(status);
  6312. if (i == fg_pipe->num_cmds-1)
  6313. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  6314. printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  6315. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  6316. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  6317. * Maybe we need to use sig | 128? */
  6318. ex = sig + 128;
  6319. }
  6320. fg_pipe->cmds[i].cmd_exitcode = ex;
  6321. } else {
  6322. fg_pipe->stopped_cmds++;
  6323. }
  6324. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  6325. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  6326. if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
  6327. /* All processes in fg pipe have exited or stopped */
  6328. i = fg_pipe->num_cmds;
  6329. while (--i >= 0) {
  6330. rcode = fg_pipe->cmds[i].cmd_exitcode;
  6331. /* usually last process gives overall exitstatus,
  6332. * but with "set -o pipefail", last *failed* process does */
  6333. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  6334. break;
  6335. }
  6336. IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
  6337. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  6338. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  6339. * and "killall -STOP cat" */
  6340. if (G_interactive_fd) {
  6341. #if ENABLE_HUSH_JOB
  6342. if (fg_pipe->alive_cmds != 0)
  6343. insert_bg_job(fg_pipe);
  6344. #endif
  6345. return rcode;
  6346. }
  6347. if (fg_pipe->alive_cmds == 0)
  6348. return rcode;
  6349. }
  6350. /* There are still running processes in the fg pipe */
  6351. goto wait_more; /* do waitpid again */
  6352. }
  6353. /* it wasnt fg_pipe, look for process in bg pipes */
  6354. }
  6355. #if ENABLE_HUSH_JOB
  6356. /* We asked to wait for bg or orphaned children */
  6357. /* No need to remember exitcode in this case */
  6358. for (pi = G.job_list; pi; pi = pi->next) {
  6359. for (i = 0; i < pi->num_cmds; i++) {
  6360. if (pi->cmds[i].pid == childpid)
  6361. goto found_pi_and_prognum;
  6362. }
  6363. }
  6364. /* Happens when shell is used as init process (init=/bin/sh) */
  6365. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  6366. continue; /* do waitpid again */
  6367. found_pi_and_prognum:
  6368. if (dead) {
  6369. /* child exited */
  6370. pi->cmds[i].pid = 0;
  6371. pi->alive_cmds--;
  6372. if (!pi->alive_cmds) {
  6373. if (G_interactive_fd)
  6374. printf(JOB_STATUS_FORMAT, pi->jobid,
  6375. "Done", pi->cmdtext);
  6376. delete_finished_bg_job(pi);
  6377. }
  6378. } else {
  6379. /* child stopped */
  6380. pi->stopped_cmds++;
  6381. }
  6382. #endif
  6383. } /* while (waitpid succeeds)... */
  6384. return rcode;
  6385. }
  6386. #if ENABLE_HUSH_JOB
  6387. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  6388. {
  6389. pid_t p;
  6390. int rcode = checkjobs(fg_pipe);
  6391. if (G_saved_tty_pgrp) {
  6392. /* Job finished, move the shell to the foreground */
  6393. p = getpgrp(); /* our process group id */
  6394. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  6395. tcsetpgrp(G_interactive_fd, p);
  6396. }
  6397. return rcode;
  6398. }
  6399. #endif
  6400. /* Start all the jobs, but don't wait for anything to finish.
  6401. * See checkjobs().
  6402. *
  6403. * Return code is normally -1, when the caller has to wait for children
  6404. * to finish to determine the exit status of the pipe. If the pipe
  6405. * is a simple builtin command, however, the action is done by the
  6406. * time run_pipe returns, and the exit code is provided as the
  6407. * return value.
  6408. *
  6409. * Returns -1 only if started some children. IOW: we have to
  6410. * mask out retvals of builtins etc with 0xff!
  6411. *
  6412. * The only case when we do not need to [v]fork is when the pipe
  6413. * is single, non-backgrounded, non-subshell command. Examples:
  6414. * cmd ; ... { list } ; ...
  6415. * cmd && ... { list } && ...
  6416. * cmd || ... { list } || ...
  6417. * If it is, then we can run cmd as a builtin, NOFORK,
  6418. * or (if SH_STANDALONE) an applet, and we can run the { list }
  6419. * with run_list. If it isn't one of these, we fork and exec cmd.
  6420. *
  6421. * Cases when we must fork:
  6422. * non-single: cmd | cmd
  6423. * backgrounded: cmd & { list } &
  6424. * subshell: ( list ) [&]
  6425. */
  6426. #if !ENABLE_HUSH_MODE_X
  6427. #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
  6428. redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
  6429. #endif
  6430. static int redirect_and_varexp_helper(char ***new_env_p,
  6431. struct variable **old_vars_p,
  6432. struct command *command,
  6433. int squirrel[3],
  6434. char **argv_expanded)
  6435. {
  6436. /* setup_redirects acts on file descriptors, not FILEs.
  6437. * This is perfect for work that comes after exec().
  6438. * Is it really safe for inline use? Experimentally,
  6439. * things seem to work. */
  6440. int rcode = setup_redirects(command, squirrel);
  6441. if (rcode == 0) {
  6442. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  6443. *new_env_p = new_env;
  6444. dump_cmd_in_x_mode(new_env);
  6445. dump_cmd_in_x_mode(argv_expanded);
  6446. if (old_vars_p)
  6447. *old_vars_p = set_vars_and_save_old(new_env);
  6448. }
  6449. return rcode;
  6450. }
  6451. static NOINLINE int run_pipe(struct pipe *pi)
  6452. {
  6453. static const char *const null_ptr = NULL;
  6454. int cmd_no;
  6455. int next_infd;
  6456. struct command *command;
  6457. char **argv_expanded;
  6458. char **argv;
  6459. /* it is not always needed, but we aim to smaller code */
  6460. int squirrel[] = { -1, -1, -1 };
  6461. int rcode;
  6462. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  6463. debug_enter();
  6464. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  6465. * Result should be 3 lines: q w e, qwe, q w e
  6466. */
  6467. G.ifs = get_local_var_value("IFS");
  6468. if (!G.ifs)
  6469. G.ifs = defifs;
  6470. IF_HUSH_JOB(pi->pgrp = -1;)
  6471. pi->stopped_cmds = 0;
  6472. command = &pi->cmds[0];
  6473. argv_expanded = NULL;
  6474. if (pi->num_cmds != 1
  6475. || pi->followup == PIPE_BG
  6476. || command->cmd_type == CMD_SUBSHELL
  6477. ) {
  6478. goto must_fork;
  6479. }
  6480. pi->alive_cmds = 1;
  6481. debug_printf_exec(": group:%p argv:'%s'\n",
  6482. command->group, command->argv ? command->argv[0] : "NONE");
  6483. if (command->group) {
  6484. #if ENABLE_HUSH_FUNCTIONS
  6485. if (command->cmd_type == CMD_FUNCDEF) {
  6486. /* "executing" func () { list } */
  6487. struct function *funcp;
  6488. funcp = new_function(command->argv[0]);
  6489. /* funcp->name is already set to argv[0] */
  6490. funcp->body = command->group;
  6491. # if !BB_MMU
  6492. funcp->body_as_string = command->group_as_string;
  6493. command->group_as_string = NULL;
  6494. # endif
  6495. command->group = NULL;
  6496. command->argv[0] = NULL;
  6497. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  6498. funcp->parent_cmd = command;
  6499. command->child_func = funcp;
  6500. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  6501. debug_leave();
  6502. return EXIT_SUCCESS;
  6503. }
  6504. #endif
  6505. /* { list } */
  6506. debug_printf("non-subshell group\n");
  6507. rcode = 1; /* exitcode if redir failed */
  6508. if (setup_redirects(command, squirrel) == 0) {
  6509. debug_printf_exec(": run_list\n");
  6510. rcode = run_list(command->group) & 0xff;
  6511. }
  6512. restore_redirects(squirrel);
  6513. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6514. debug_leave();
  6515. debug_printf_exec("run_pipe: return %d\n", rcode);
  6516. return rcode;
  6517. }
  6518. argv = command->argv ? command->argv : (char **) &null_ptr;
  6519. {
  6520. const struct built_in_command *x;
  6521. #if ENABLE_HUSH_FUNCTIONS
  6522. const struct function *funcp;
  6523. #else
  6524. enum { funcp = 0 };
  6525. #endif
  6526. char **new_env = NULL;
  6527. struct variable *old_vars = NULL;
  6528. if (argv[command->assignment_cnt] == NULL) {
  6529. /* Assignments, but no command */
  6530. /* Ensure redirects take effect (that is, create files).
  6531. * Try "a=t >file" */
  6532. #if 0 /* A few cases in testsuite fail with this code. FIXME */
  6533. rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
  6534. /* Set shell variables */
  6535. if (new_env) {
  6536. argv = new_env;
  6537. while (*argv) {
  6538. set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6539. /* Do we need to flag set_local_var() errors?
  6540. * "assignment to readonly var" and "putenv error"
  6541. */
  6542. argv++;
  6543. }
  6544. }
  6545. /* Redirect error sets $? to 1. Otherwise,
  6546. * if evaluating assignment value set $?, retain it.
  6547. * Try "false; q=`exit 2`; echo $?" - should print 2: */
  6548. if (rcode == 0)
  6549. rcode = G.last_exitcode;
  6550. /* Exit, _skipping_ variable restoring code: */
  6551. goto clean_up_and_ret0;
  6552. #else /* Older, bigger, but more correct code */
  6553. rcode = setup_redirects(command, squirrel);
  6554. restore_redirects(squirrel);
  6555. /* Set shell variables */
  6556. if (G_x_mode)
  6557. bb_putchar_stderr('+');
  6558. while (*argv) {
  6559. char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
  6560. if (G_x_mode)
  6561. fprintf(stderr, " %s", p);
  6562. debug_printf_exec("set shell var:'%s'->'%s'\n",
  6563. *argv, p);
  6564. set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6565. /* Do we need to flag set_local_var() errors?
  6566. * "assignment to readonly var" and "putenv error"
  6567. */
  6568. argv++;
  6569. }
  6570. if (G_x_mode)
  6571. bb_putchar_stderr('\n');
  6572. /* Redirect error sets $? to 1. Otherwise,
  6573. * if evaluating assignment value set $?, retain it.
  6574. * Try "false; q=`exit 2`; echo $?" - should print 2: */
  6575. if (rcode == 0)
  6576. rcode = G.last_exitcode;
  6577. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6578. debug_leave();
  6579. debug_printf_exec("run_pipe: return %d\n", rcode);
  6580. return rcode;
  6581. #endif
  6582. }
  6583. /* Expand the rest into (possibly) many strings each */
  6584. #if ENABLE_HUSH_BASH_COMPAT
  6585. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
  6586. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  6587. } else
  6588. #endif
  6589. {
  6590. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  6591. }
  6592. /* if someone gives us an empty string: `cmd with empty output` */
  6593. if (!argv_expanded[0]) {
  6594. free(argv_expanded);
  6595. debug_leave();
  6596. return G.last_exitcode;
  6597. }
  6598. x = find_builtin(argv_expanded[0]);
  6599. #if ENABLE_HUSH_FUNCTIONS
  6600. funcp = NULL;
  6601. if (!x)
  6602. funcp = find_function(argv_expanded[0]);
  6603. #endif
  6604. if (x || funcp) {
  6605. if (!funcp) {
  6606. if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  6607. debug_printf("exec with redirects only\n");
  6608. rcode = setup_redirects(command, NULL);
  6609. goto clean_up_and_ret1;
  6610. }
  6611. }
  6612. rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
  6613. if (rcode == 0) {
  6614. if (!funcp) {
  6615. debug_printf_exec(": builtin '%s' '%s'...\n",
  6616. x->b_cmd, argv_expanded[1]);
  6617. fflush_all();
  6618. rcode = x->b_function(argv_expanded) & 0xff;
  6619. fflush_all();
  6620. }
  6621. #if ENABLE_HUSH_FUNCTIONS
  6622. else {
  6623. # if ENABLE_HUSH_LOCAL
  6624. struct variable **sv;
  6625. sv = G.shadowed_vars_pp;
  6626. G.shadowed_vars_pp = &old_vars;
  6627. # endif
  6628. debug_printf_exec(": function '%s' '%s'...\n",
  6629. funcp->name, argv_expanded[1]);
  6630. rcode = run_function(funcp, argv_expanded) & 0xff;
  6631. # if ENABLE_HUSH_LOCAL
  6632. G.shadowed_vars_pp = sv;
  6633. # endif
  6634. }
  6635. #endif
  6636. }
  6637. clean_up_and_ret:
  6638. unset_vars(new_env);
  6639. add_vars(old_vars);
  6640. /* clean_up_and_ret0: */
  6641. restore_redirects(squirrel);
  6642. clean_up_and_ret1:
  6643. free(argv_expanded);
  6644. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6645. debug_leave();
  6646. debug_printf_exec("run_pipe return %d\n", rcode);
  6647. return rcode;
  6648. }
  6649. if (ENABLE_FEATURE_SH_NOFORK) {
  6650. int n = find_applet_by_name(argv_expanded[0]);
  6651. if (n >= 0 && APPLET_IS_NOFORK(n)) {
  6652. rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
  6653. if (rcode == 0) {
  6654. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  6655. argv_expanded[0], argv_expanded[1]);
  6656. rcode = run_nofork_applet(n, argv_expanded);
  6657. }
  6658. goto clean_up_and_ret;
  6659. }
  6660. }
  6661. /* It is neither builtin nor applet. We must fork. */
  6662. }
  6663. must_fork:
  6664. /* NB: argv_expanded may already be created, and that
  6665. * might include `cmd` runs! Do not rerun it! We *must*
  6666. * use argv_expanded if it's non-NULL */
  6667. /* Going to fork a child per each pipe member */
  6668. pi->alive_cmds = 0;
  6669. next_infd = 0;
  6670. cmd_no = 0;
  6671. while (cmd_no < pi->num_cmds) {
  6672. struct fd_pair pipefds;
  6673. #if !BB_MMU
  6674. volatile nommu_save_t nommu_save;
  6675. nommu_save.new_env = NULL;
  6676. nommu_save.old_vars = NULL;
  6677. nommu_save.argv = NULL;
  6678. nommu_save.argv_from_re_execing = NULL;
  6679. #endif
  6680. command = &pi->cmds[cmd_no];
  6681. cmd_no++;
  6682. if (command->argv) {
  6683. debug_printf_exec(": pipe member '%s' '%s'...\n",
  6684. command->argv[0], command->argv[1]);
  6685. } else {
  6686. debug_printf_exec(": pipe member with no argv\n");
  6687. }
  6688. /* pipes are inserted between pairs of commands */
  6689. pipefds.rd = 0;
  6690. pipefds.wr = 1;
  6691. if (cmd_no < pi->num_cmds)
  6692. xpiped_pair(pipefds);
  6693. command->pid = BB_MMU ? fork() : vfork();
  6694. if (!command->pid) { /* child */
  6695. #if ENABLE_HUSH_JOB
  6696. disable_restore_tty_pgrp_on_exit();
  6697. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6698. /* Every child adds itself to new process group
  6699. * with pgid == pid_of_first_child_in_pipe */
  6700. if (G.run_list_level == 1 && G_interactive_fd) {
  6701. pid_t pgrp;
  6702. pgrp = pi->pgrp;
  6703. if (pgrp < 0) /* true for 1st process only */
  6704. pgrp = getpid();
  6705. if (setpgid(0, pgrp) == 0
  6706. && pi->followup != PIPE_BG
  6707. && G_saved_tty_pgrp /* we have ctty */
  6708. ) {
  6709. /* We do it in *every* child, not just first,
  6710. * to avoid races */
  6711. tcsetpgrp(G_interactive_fd, pgrp);
  6712. }
  6713. }
  6714. #endif
  6715. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  6716. /* 1st cmd in backgrounded pipe
  6717. * should have its stdin /dev/null'ed */
  6718. close(0);
  6719. if (open(bb_dev_null, O_RDONLY))
  6720. xopen("/", O_RDONLY);
  6721. } else {
  6722. xmove_fd(next_infd, 0);
  6723. }
  6724. xmove_fd(pipefds.wr, 1);
  6725. if (pipefds.rd > 1)
  6726. close(pipefds.rd);
  6727. /* Like bash, explicit redirects override pipes,
  6728. * and the pipe fd is available for dup'ing. */
  6729. if (setup_redirects(command, NULL))
  6730. _exit(1);
  6731. /* Stores to nommu_save list of env vars putenv'ed
  6732. * (NOMMU, on MMU we don't need that) */
  6733. /* cast away volatility... */
  6734. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  6735. /* pseudo_exec() does not return */
  6736. }
  6737. /* parent or error */
  6738. #if ENABLE_HUSH_FAST
  6739. G.count_SIGCHLD++;
  6740. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6741. #endif
  6742. enable_restore_tty_pgrp_on_exit();
  6743. #if !BB_MMU
  6744. /* Clean up after vforked child */
  6745. free(nommu_save.argv);
  6746. free(nommu_save.argv_from_re_execing);
  6747. unset_vars(nommu_save.new_env);
  6748. add_vars(nommu_save.old_vars);
  6749. #endif
  6750. free(argv_expanded);
  6751. argv_expanded = NULL;
  6752. if (command->pid < 0) { /* [v]fork failed */
  6753. /* Clearly indicate, was it fork or vfork */
  6754. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  6755. } else {
  6756. pi->alive_cmds++;
  6757. #if ENABLE_HUSH_JOB
  6758. /* Second and next children need to know pid of first one */
  6759. if (pi->pgrp < 0)
  6760. pi->pgrp = command->pid;
  6761. #endif
  6762. }
  6763. if (cmd_no > 1)
  6764. close(next_infd);
  6765. if (cmd_no < pi->num_cmds)
  6766. close(pipefds.wr);
  6767. /* Pass read (output) pipe end to next iteration */
  6768. next_infd = pipefds.rd;
  6769. }
  6770. if (!pi->alive_cmds) {
  6771. debug_leave();
  6772. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  6773. return 1;
  6774. }
  6775. debug_leave();
  6776. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  6777. return -1;
  6778. }
  6779. /* NB: called by pseudo_exec, and therefore must not modify any
  6780. * global data until exec/_exit (we can be a child after vfork!) */
  6781. static int run_list(struct pipe *pi)
  6782. {
  6783. #if ENABLE_HUSH_CASE
  6784. char *case_word = NULL;
  6785. #endif
  6786. #if ENABLE_HUSH_LOOPS
  6787. struct pipe *loop_top = NULL;
  6788. char **for_lcur = NULL;
  6789. char **for_list = NULL;
  6790. #endif
  6791. smallint last_followup;
  6792. smalluint rcode;
  6793. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  6794. smalluint cond_code = 0;
  6795. #else
  6796. enum { cond_code = 0 };
  6797. #endif
  6798. #if HAS_KEYWORDS
  6799. smallint rword; /* RES_foo */
  6800. smallint last_rword; /* ditto */
  6801. #endif
  6802. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  6803. debug_enter();
  6804. #if ENABLE_HUSH_LOOPS
  6805. /* Check syntax for "for" */
  6806. {
  6807. struct pipe *cpipe;
  6808. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  6809. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  6810. continue;
  6811. /* current word is FOR or IN (BOLD in comments below) */
  6812. if (cpipe->next == NULL) {
  6813. syntax_error("malformed for");
  6814. debug_leave();
  6815. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  6816. return 1;
  6817. }
  6818. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  6819. if (cpipe->next->res_word == RES_DO)
  6820. continue;
  6821. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  6822. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  6823. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  6824. ) {
  6825. syntax_error("malformed for");
  6826. debug_leave();
  6827. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  6828. return 1;
  6829. }
  6830. }
  6831. }
  6832. #endif
  6833. /* Past this point, all code paths should jump to ret: label
  6834. * in order to return, no direct "return" statements please.
  6835. * This helps to ensure that no memory is leaked. */
  6836. #if ENABLE_HUSH_JOB
  6837. G.run_list_level++;
  6838. #endif
  6839. #if HAS_KEYWORDS
  6840. rword = RES_NONE;
  6841. last_rword = RES_XXXX;
  6842. #endif
  6843. last_followup = PIPE_SEQ;
  6844. rcode = G.last_exitcode;
  6845. /* Go through list of pipes, (maybe) executing them. */
  6846. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  6847. if (G.flag_SIGINT)
  6848. break;
  6849. IF_HAS_KEYWORDS(rword = pi->res_word;)
  6850. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  6851. rword, cond_code, last_rword);
  6852. #if ENABLE_HUSH_LOOPS
  6853. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  6854. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  6855. ) {
  6856. /* start of a loop: remember where loop starts */
  6857. loop_top = pi;
  6858. G.depth_of_loop++;
  6859. }
  6860. #endif
  6861. /* Still in the same "if...", "then..." or "do..." branch? */
  6862. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  6863. if ((rcode == 0 && last_followup == PIPE_OR)
  6864. || (rcode != 0 && last_followup == PIPE_AND)
  6865. ) {
  6866. /* It is "<true> || CMD" or "<false> && CMD"
  6867. * and we should not execute CMD */
  6868. debug_printf_exec("skipped cmd because of || or &&\n");
  6869. last_followup = pi->followup;
  6870. goto dont_check_jobs_but_continue;
  6871. }
  6872. }
  6873. last_followup = pi->followup;
  6874. IF_HAS_KEYWORDS(last_rword = rword;)
  6875. #if ENABLE_HUSH_IF
  6876. if (cond_code) {
  6877. if (rword == RES_THEN) {
  6878. /* if false; then ... fi has exitcode 0! */
  6879. G.last_exitcode = rcode = EXIT_SUCCESS;
  6880. /* "if <false> THEN cmd": skip cmd */
  6881. continue;
  6882. }
  6883. } else {
  6884. if (rword == RES_ELSE || rword == RES_ELIF) {
  6885. /* "if <true> then ... ELSE/ELIF cmd":
  6886. * skip cmd and all following ones */
  6887. break;
  6888. }
  6889. }
  6890. #endif
  6891. #if ENABLE_HUSH_LOOPS
  6892. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  6893. if (!for_lcur) {
  6894. /* first loop through for */
  6895. static const char encoded_dollar_at[] ALIGN1 = {
  6896. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  6897. }; /* encoded representation of "$@" */
  6898. static const char *const encoded_dollar_at_argv[] = {
  6899. encoded_dollar_at, NULL
  6900. }; /* argv list with one element: "$@" */
  6901. char **vals;
  6902. vals = (char**)encoded_dollar_at_argv;
  6903. if (pi->next->res_word == RES_IN) {
  6904. /* if no variable values after "in" we skip "for" */
  6905. if (!pi->next->cmds[0].argv) {
  6906. G.last_exitcode = rcode = EXIT_SUCCESS;
  6907. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  6908. break;
  6909. }
  6910. vals = pi->next->cmds[0].argv;
  6911. } /* else: "for var; do..." -> assume "$@" list */
  6912. /* create list of variable values */
  6913. debug_print_strings("for_list made from", vals);
  6914. for_list = expand_strvec_to_strvec(vals);
  6915. for_lcur = for_list;
  6916. debug_print_strings("for_list", for_list);
  6917. }
  6918. if (!*for_lcur) {
  6919. /* "for" loop is over, clean up */
  6920. free(for_list);
  6921. for_list = NULL;
  6922. for_lcur = NULL;
  6923. break;
  6924. }
  6925. /* Insert next value from for_lcur */
  6926. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  6927. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6928. continue;
  6929. }
  6930. if (rword == RES_IN) {
  6931. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  6932. }
  6933. if (rword == RES_DONE) {
  6934. continue; /* "done" has no cmds too */
  6935. }
  6936. #endif
  6937. #if ENABLE_HUSH_CASE
  6938. if (rword == RES_CASE) {
  6939. case_word = expand_strvec_to_string(pi->cmds->argv);
  6940. continue;
  6941. }
  6942. if (rword == RES_MATCH) {
  6943. char **argv;
  6944. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  6945. break;
  6946. /* all prev words didn't match, does this one match? */
  6947. argv = pi->cmds->argv;
  6948. while (*argv) {
  6949. char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
  6950. /* TODO: which FNM_xxx flags to use? */
  6951. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  6952. free(pattern);
  6953. if (cond_code == 0) { /* match! we will execute this branch */
  6954. free(case_word); /* make future "word)" stop */
  6955. case_word = NULL;
  6956. break;
  6957. }
  6958. argv++;
  6959. }
  6960. continue;
  6961. }
  6962. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  6963. if (cond_code != 0)
  6964. continue; /* not matched yet, skip this pipe */
  6965. }
  6966. #endif
  6967. /* Just pressing <enter> in shell should check for jobs.
  6968. * OTOH, in non-interactive shell this is useless
  6969. * and only leads to extra job checks */
  6970. if (pi->num_cmds == 0) {
  6971. if (G_interactive_fd)
  6972. goto check_jobs_and_continue;
  6973. continue;
  6974. }
  6975. /* After analyzing all keywords and conditions, we decided
  6976. * to execute this pipe. NB: have to do checkjobs(NULL)
  6977. * after run_pipe to collect any background children,
  6978. * even if list execution is to be stopped. */
  6979. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  6980. {
  6981. int r;
  6982. #if ENABLE_HUSH_LOOPS
  6983. G.flag_break_continue = 0;
  6984. #endif
  6985. rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
  6986. if (r != -1) {
  6987. /* We ran a builtin, function, or group.
  6988. * rcode is already known
  6989. * and we don't need to wait for anything. */
  6990. G.last_exitcode = rcode;
  6991. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  6992. check_and_run_traps();
  6993. #if ENABLE_HUSH_LOOPS
  6994. /* Was it "break" or "continue"? */
  6995. if (G.flag_break_continue) {
  6996. smallint fbc = G.flag_break_continue;
  6997. /* We might fall into outer *loop*,
  6998. * don't want to break it too */
  6999. if (loop_top) {
  7000. G.depth_break_continue--;
  7001. if (G.depth_break_continue == 0)
  7002. G.flag_break_continue = 0;
  7003. /* else: e.g. "continue 2" should *break* once, *then* continue */
  7004. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  7005. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  7006. checkjobs(NULL);
  7007. break;
  7008. }
  7009. /* "continue": simulate end of loop */
  7010. rword = RES_DONE;
  7011. continue;
  7012. }
  7013. #endif
  7014. #if ENABLE_HUSH_FUNCTIONS
  7015. if (G.flag_return_in_progress == 1) {
  7016. checkjobs(NULL);
  7017. break;
  7018. }
  7019. #endif
  7020. } else if (pi->followup == PIPE_BG) {
  7021. /* What does bash do with attempts to background builtins? */
  7022. /* even bash 3.2 doesn't do that well with nested bg:
  7023. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  7024. * I'm NOT treating inner &'s as jobs */
  7025. check_and_run_traps();
  7026. #if ENABLE_HUSH_JOB
  7027. if (G.run_list_level == 1)
  7028. insert_bg_job(pi);
  7029. #endif
  7030. /* Last command's pid goes to $! */
  7031. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  7032. G.last_exitcode = rcode = EXIT_SUCCESS;
  7033. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  7034. } else {
  7035. #if ENABLE_HUSH_JOB
  7036. if (G.run_list_level == 1 && G_interactive_fd) {
  7037. /* Waits for completion, then fg's main shell */
  7038. rcode = checkjobs_and_fg_shell(pi);
  7039. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  7040. check_and_run_traps();
  7041. } else
  7042. #endif
  7043. { /* This one just waits for completion */
  7044. rcode = checkjobs(pi);
  7045. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  7046. check_and_run_traps();
  7047. }
  7048. G.last_exitcode = rcode;
  7049. }
  7050. }
  7051. /* Analyze how result affects subsequent commands */
  7052. #if ENABLE_HUSH_IF
  7053. if (rword == RES_IF || rword == RES_ELIF)
  7054. cond_code = rcode;
  7055. #endif
  7056. check_jobs_and_continue:
  7057. checkjobs(NULL);
  7058. dont_check_jobs_but_continue: ;
  7059. #if ENABLE_HUSH_LOOPS
  7060. /* Beware of "while false; true; do ..."! */
  7061. if (pi->next
  7062. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  7063. /* check for RES_DONE is needed for "while ...; do \n done" case */
  7064. ) {
  7065. if (rword == RES_WHILE) {
  7066. if (rcode) {
  7067. /* "while false; do...done" - exitcode 0 */
  7068. G.last_exitcode = rcode = EXIT_SUCCESS;
  7069. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  7070. break;
  7071. }
  7072. }
  7073. if (rword == RES_UNTIL) {
  7074. if (!rcode) {
  7075. debug_printf_exec(": until expr is true: breaking\n");
  7076. break;
  7077. }
  7078. }
  7079. }
  7080. #endif
  7081. } /* for (pi) */
  7082. #if ENABLE_HUSH_JOB
  7083. G.run_list_level--;
  7084. #endif
  7085. #if ENABLE_HUSH_LOOPS
  7086. if (loop_top)
  7087. G.depth_of_loop--;
  7088. free(for_list);
  7089. #endif
  7090. #if ENABLE_HUSH_CASE
  7091. free(case_word);
  7092. #endif
  7093. debug_leave();
  7094. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  7095. return rcode;
  7096. }
  7097. /* Select which version we will use */
  7098. static int run_and_free_list(struct pipe *pi)
  7099. {
  7100. int rcode = 0;
  7101. debug_printf_exec("run_and_free_list entered\n");
  7102. if (!G.o_opt[OPT_O_NOEXEC]) {
  7103. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  7104. rcode = run_list(pi);
  7105. }
  7106. /* free_pipe_list has the side effect of clearing memory.
  7107. * In the long run that function can be merged with run_list,
  7108. * but doing that now would hobble the debugging effort. */
  7109. free_pipe_list(pi);
  7110. debug_printf_exec("run_and_free_list return %d\n", rcode);
  7111. return rcode;
  7112. }
  7113. static void install_sighandlers(unsigned mask)
  7114. {
  7115. sighandler_t old_handler;
  7116. unsigned sig = 0;
  7117. while ((mask >>= 1) != 0) {
  7118. sig++;
  7119. if (!(mask & 1))
  7120. continue;
  7121. old_handler = install_sighandler(sig, pick_sighandler(sig));
  7122. /* POSIX allows shell to re-enable SIGCHLD
  7123. * even if it was SIG_IGN on entry.
  7124. * Therefore we skip IGN check for it:
  7125. */
  7126. if (sig == SIGCHLD)
  7127. continue;
  7128. if (old_handler == SIG_IGN) {
  7129. /* oops... restore back to IGN, and record this fact */
  7130. install_sighandler(sig, old_handler);
  7131. if (!G.traps)
  7132. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7133. free(G.traps[sig]);
  7134. G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
  7135. }
  7136. }
  7137. }
  7138. /* Called a few times only (or even once if "sh -c") */
  7139. static void install_special_sighandlers(void)
  7140. {
  7141. unsigned mask;
  7142. /* Which signals are shell-special? */
  7143. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  7144. if (G_interactive_fd) {
  7145. mask |= SPECIAL_INTERACTIVE_SIGS;
  7146. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  7147. mask |= SPECIAL_JOBSTOP_SIGS;
  7148. }
  7149. /* Careful, do not re-install handlers we already installed */
  7150. if (G.special_sig_mask != mask) {
  7151. unsigned diff = mask & ~G.special_sig_mask;
  7152. G.special_sig_mask = mask;
  7153. install_sighandlers(diff);
  7154. }
  7155. }
  7156. #if ENABLE_HUSH_JOB
  7157. /* helper */
  7158. /* Set handlers to restore tty pgrp and exit */
  7159. static void install_fatal_sighandlers(void)
  7160. {
  7161. unsigned mask;
  7162. /* We will restore tty pgrp on these signals */
  7163. mask = 0
  7164. + (1 << SIGILL ) * HUSH_DEBUG
  7165. + (1 << SIGFPE ) * HUSH_DEBUG
  7166. + (1 << SIGBUS ) * HUSH_DEBUG
  7167. + (1 << SIGSEGV) * HUSH_DEBUG
  7168. + (1 << SIGTRAP) * HUSH_DEBUG
  7169. + (1 << SIGABRT)
  7170. /* bash 3.2 seems to handle these just like 'fatal' ones */
  7171. + (1 << SIGPIPE)
  7172. + (1 << SIGALRM)
  7173. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  7174. * if we aren't interactive... but in this case
  7175. * we never want to restore pgrp on exit, and this fn is not called
  7176. */
  7177. /*+ (1 << SIGHUP )*/
  7178. /*+ (1 << SIGTERM)*/
  7179. /*+ (1 << SIGINT )*/
  7180. ;
  7181. G_fatal_sig_mask = mask;
  7182. install_sighandlers(mask);
  7183. }
  7184. #endif
  7185. static int set_mode(int state, char mode, const char *o_opt)
  7186. {
  7187. int idx;
  7188. switch (mode) {
  7189. case 'n':
  7190. G.o_opt[OPT_O_NOEXEC] = state;
  7191. break;
  7192. case 'x':
  7193. IF_HUSH_MODE_X(G_x_mode = state;)
  7194. break;
  7195. case 'o':
  7196. if (!o_opt) {
  7197. /* "set -+o" without parameter.
  7198. * in bash, set -o produces this output:
  7199. * pipefail off
  7200. * and set +o:
  7201. * set +o pipefail
  7202. * We always use the second form.
  7203. */
  7204. const char *p = o_opt_strings;
  7205. idx = 0;
  7206. while (*p) {
  7207. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  7208. idx++;
  7209. p += strlen(p) + 1;
  7210. }
  7211. break;
  7212. }
  7213. idx = index_in_strings(o_opt_strings, o_opt);
  7214. if (idx >= 0) {
  7215. G.o_opt[idx] = state;
  7216. break;
  7217. }
  7218. default:
  7219. return EXIT_FAILURE;
  7220. }
  7221. return EXIT_SUCCESS;
  7222. }
  7223. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  7224. int hush_main(int argc, char **argv)
  7225. {
  7226. enum {
  7227. OPT_login = (1 << 0),
  7228. };
  7229. unsigned flags;
  7230. int opt;
  7231. unsigned builtin_argc;
  7232. char **e;
  7233. struct variable *cur_var;
  7234. struct variable *shell_ver;
  7235. INIT_G();
  7236. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  7237. G.last_exitcode = EXIT_SUCCESS;
  7238. #if ENABLE_HUSH_FAST
  7239. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  7240. #endif
  7241. #if !BB_MMU
  7242. G.argv0_for_re_execing = argv[0];
  7243. #endif
  7244. /* Deal with HUSH_VERSION */
  7245. shell_ver = xzalloc(sizeof(*shell_ver));
  7246. shell_ver->flg_export = 1;
  7247. shell_ver->flg_read_only = 1;
  7248. /* Code which handles ${var<op>...} needs writable values for all variables,
  7249. * therefore we xstrdup: */
  7250. shell_ver->varstr = xstrdup(hush_version_str);
  7251. /* Create shell local variables from the values
  7252. * currently living in the environment */
  7253. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  7254. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  7255. G.top_var = shell_ver;
  7256. cur_var = G.top_var;
  7257. e = environ;
  7258. if (e) while (*e) {
  7259. char *value = strchr(*e, '=');
  7260. if (value) { /* paranoia */
  7261. cur_var->next = xzalloc(sizeof(*cur_var));
  7262. cur_var = cur_var->next;
  7263. cur_var->varstr = *e;
  7264. cur_var->max_len = strlen(*e);
  7265. cur_var->flg_export = 1;
  7266. }
  7267. e++;
  7268. }
  7269. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  7270. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  7271. putenv(shell_ver->varstr);
  7272. /* Export PWD */
  7273. set_pwd_var(/*exp:*/ 1);
  7274. #if ENABLE_HUSH_BASH_COMPAT
  7275. /* Set (but not export) HOSTNAME unless already set */
  7276. if (!get_local_var_value("HOSTNAME")) {
  7277. struct utsname uts;
  7278. uname(&uts);
  7279. set_local_var_from_halves("HOSTNAME", uts.nodename);
  7280. }
  7281. /* bash also exports SHLVL and _,
  7282. * and sets (but doesn't export) the following variables:
  7283. * BASH=/bin/bash
  7284. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  7285. * BASH_VERSION='3.2.0(1)-release'
  7286. * HOSTTYPE=i386
  7287. * MACHTYPE=i386-pc-linux-gnu
  7288. * OSTYPE=linux-gnu
  7289. * PPID=<NNNNN> - we also do it elsewhere
  7290. * EUID=<NNNNN>
  7291. * UID=<NNNNN>
  7292. * GROUPS=()
  7293. * LINES=<NNN>
  7294. * COLUMNS=<NNN>
  7295. * BASH_ARGC=()
  7296. * BASH_ARGV=()
  7297. * BASH_LINENO=()
  7298. * BASH_SOURCE=()
  7299. * DIRSTACK=()
  7300. * PIPESTATUS=([0]="0")
  7301. * HISTFILE=/<xxx>/.bash_history
  7302. * HISTFILESIZE=500
  7303. * HISTSIZE=500
  7304. * MAILCHECK=60
  7305. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  7306. * SHELL=/bin/bash
  7307. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  7308. * TERM=dumb
  7309. * OPTERR=1
  7310. * OPTIND=1
  7311. * IFS=$' \t\n'
  7312. * PS1='\s-\v\$ '
  7313. * PS2='> '
  7314. * PS4='+ '
  7315. */
  7316. #endif
  7317. #if ENABLE_FEATURE_EDITING
  7318. G.line_input_state = new_line_input_t(FOR_SHELL);
  7319. #endif
  7320. /* Initialize some more globals to non-zero values */
  7321. cmdedit_update_prompt();
  7322. if (setjmp(die_jmp)) {
  7323. /* xfunc has failed! die die die */
  7324. /* no EXIT traps, this is an escape hatch! */
  7325. G.exiting = 1;
  7326. hush_exit(xfunc_error_retval);
  7327. }
  7328. /* Shell is non-interactive at first. We need to call
  7329. * install_special_sighandlers() if we are going to execute "sh <script>",
  7330. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  7331. * If we later decide that we are interactive, we run install_special_sighandlers()
  7332. * in order to intercept (more) signals.
  7333. */
  7334. /* Parse options */
  7335. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  7336. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  7337. builtin_argc = 0;
  7338. while (1) {
  7339. opt = getopt(argc, argv, "+c:xinsl"
  7340. #if !BB_MMU
  7341. "<:$:R:V:"
  7342. # if ENABLE_HUSH_FUNCTIONS
  7343. "F:"
  7344. # endif
  7345. #endif
  7346. );
  7347. if (opt <= 0)
  7348. break;
  7349. switch (opt) {
  7350. case 'c':
  7351. /* Possibilities:
  7352. * sh ... -c 'script'
  7353. * sh ... -c 'script' ARG0 [ARG1...]
  7354. * On NOMMU, if builtin_argc != 0,
  7355. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  7356. * "" needs to be replaced with NULL
  7357. * and BARGV vector fed to builtin function.
  7358. * Note: the form without ARG0 never happens:
  7359. * sh ... -c 'builtin' BARGV... ""
  7360. */
  7361. if (!G.root_pid) {
  7362. G.root_pid = getpid();
  7363. G.root_ppid = getppid();
  7364. }
  7365. G.global_argv = argv + optind;
  7366. G.global_argc = argc - optind;
  7367. if (builtin_argc) {
  7368. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  7369. const struct built_in_command *x;
  7370. install_special_sighandlers();
  7371. x = find_builtin(optarg);
  7372. if (x) { /* paranoia */
  7373. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  7374. G.global_argv += builtin_argc;
  7375. G.global_argv[-1] = NULL; /* replace "" */
  7376. fflush_all();
  7377. G.last_exitcode = x->b_function(argv + optind - 1);
  7378. }
  7379. goto final_return;
  7380. }
  7381. if (!G.global_argv[0]) {
  7382. /* -c 'script' (no params): prevent empty $0 */
  7383. G.global_argv--; /* points to argv[i] of 'script' */
  7384. G.global_argv[0] = argv[0];
  7385. G.global_argc++;
  7386. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  7387. install_special_sighandlers();
  7388. parse_and_run_string(optarg);
  7389. goto final_return;
  7390. case 'i':
  7391. /* Well, we cannot just declare interactiveness,
  7392. * we have to have some stuff (ctty, etc) */
  7393. /* G_interactive_fd++; */
  7394. break;
  7395. case 's':
  7396. /* "-s" means "read from stdin", but this is how we always
  7397. * operate, so simply do nothing here. */
  7398. break;
  7399. case 'l':
  7400. flags |= OPT_login;
  7401. break;
  7402. #if !BB_MMU
  7403. case '<': /* "big heredoc" support */
  7404. full_write1_str(optarg);
  7405. _exit(0);
  7406. case '$': {
  7407. unsigned long long empty_trap_mask;
  7408. G.root_pid = bb_strtou(optarg, &optarg, 16);
  7409. optarg++;
  7410. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  7411. optarg++;
  7412. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  7413. optarg++;
  7414. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  7415. optarg++;
  7416. builtin_argc = bb_strtou(optarg, &optarg, 16);
  7417. optarg++;
  7418. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  7419. if (empty_trap_mask != 0) {
  7420. int sig;
  7421. install_special_sighandlers();
  7422. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7423. for (sig = 1; sig < NSIG; sig++) {
  7424. if (empty_trap_mask & (1LL << sig)) {
  7425. G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
  7426. install_sighandler(sig, SIG_IGN);
  7427. }
  7428. }
  7429. }
  7430. # if ENABLE_HUSH_LOOPS
  7431. optarg++;
  7432. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  7433. # endif
  7434. break;
  7435. }
  7436. case 'R':
  7437. case 'V':
  7438. set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
  7439. break;
  7440. # if ENABLE_HUSH_FUNCTIONS
  7441. case 'F': {
  7442. struct function *funcp = new_function(optarg);
  7443. /* funcp->name is already set to optarg */
  7444. /* funcp->body is set to NULL. It's a special case. */
  7445. funcp->body_as_string = argv[optind];
  7446. optind++;
  7447. break;
  7448. }
  7449. # endif
  7450. #endif
  7451. case 'n':
  7452. case 'x':
  7453. if (set_mode(1, opt, NULL) == 0) /* no error */
  7454. break;
  7455. default:
  7456. #ifndef BB_VER
  7457. fprintf(stderr, "Usage: sh [FILE]...\n"
  7458. " or: sh -c command [args]...\n\n");
  7459. exit(EXIT_FAILURE);
  7460. #else
  7461. bb_show_usage();
  7462. #endif
  7463. }
  7464. } /* option parsing loop */
  7465. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  7466. G.global_argc = argc - (optind - 1);
  7467. G.global_argv = argv + (optind - 1);
  7468. G.global_argv[0] = argv[0];
  7469. if (!G.root_pid) {
  7470. G.root_pid = getpid();
  7471. G.root_ppid = getppid();
  7472. }
  7473. /* If we are login shell... */
  7474. if (flags & OPT_login) {
  7475. FILE *input;
  7476. debug_printf("sourcing /etc/profile\n");
  7477. input = fopen_for_read("/etc/profile");
  7478. if (input != NULL) {
  7479. close_on_exec_on(fileno(input));
  7480. install_special_sighandlers();
  7481. parse_and_run_file(input);
  7482. fclose(input);
  7483. }
  7484. /* bash: after sourcing /etc/profile,
  7485. * tries to source (in the given order):
  7486. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  7487. * stopping on first found. --noprofile turns this off.
  7488. * bash also sources ~/.bash_logout on exit.
  7489. * If called as sh, skips .bash_XXX files.
  7490. */
  7491. }
  7492. if (G.global_argv[1]) {
  7493. FILE *input;
  7494. /*
  7495. * "bash <script>" (which is never interactive (unless -i?))
  7496. * sources $BASH_ENV here (without scanning $PATH).
  7497. * If called as sh, does the same but with $ENV.
  7498. */
  7499. G.global_argc--;
  7500. G.global_argv++;
  7501. debug_printf("running script '%s'\n", G.global_argv[0]);
  7502. input = xfopen_for_read(G.global_argv[0]);
  7503. close_on_exec_on(fileno(input));
  7504. install_special_sighandlers();
  7505. parse_and_run_file(input);
  7506. #if ENABLE_FEATURE_CLEAN_UP
  7507. fclose(input);
  7508. #endif
  7509. goto final_return;
  7510. }
  7511. /* Up to here, shell was non-interactive. Now it may become one.
  7512. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  7513. */
  7514. /* A shell is interactive if the '-i' flag was given,
  7515. * or if all of the following conditions are met:
  7516. * no -c command
  7517. * no arguments remaining or the -s flag given
  7518. * standard input is a terminal
  7519. * standard output is a terminal
  7520. * Refer to Posix.2, the description of the 'sh' utility.
  7521. */
  7522. #if ENABLE_HUSH_JOB
  7523. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  7524. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  7525. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  7526. if (G_saved_tty_pgrp < 0)
  7527. G_saved_tty_pgrp = 0;
  7528. /* try to dup stdin to high fd#, >= 255 */
  7529. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  7530. if (G_interactive_fd < 0) {
  7531. /* try to dup to any fd */
  7532. G_interactive_fd = dup(STDIN_FILENO);
  7533. if (G_interactive_fd < 0) {
  7534. /* give up */
  7535. G_interactive_fd = 0;
  7536. G_saved_tty_pgrp = 0;
  7537. }
  7538. }
  7539. // TODO: track & disallow any attempts of user
  7540. // to (inadvertently) close/redirect G_interactive_fd
  7541. }
  7542. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  7543. if (G_interactive_fd) {
  7544. close_on_exec_on(G_interactive_fd);
  7545. if (G_saved_tty_pgrp) {
  7546. /* If we were run as 'hush &', sleep until we are
  7547. * in the foreground (tty pgrp == our pgrp).
  7548. * If we get started under a job aware app (like bash),
  7549. * make sure we are now in charge so we don't fight over
  7550. * who gets the foreground */
  7551. while (1) {
  7552. pid_t shell_pgrp = getpgrp();
  7553. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  7554. if (G_saved_tty_pgrp == shell_pgrp)
  7555. break;
  7556. /* send TTIN to ourself (should stop us) */
  7557. kill(- shell_pgrp, SIGTTIN);
  7558. }
  7559. }
  7560. /* Install more signal handlers */
  7561. install_special_sighandlers();
  7562. if (G_saved_tty_pgrp) {
  7563. /* Set other signals to restore saved_tty_pgrp */
  7564. install_fatal_sighandlers();
  7565. /* Put ourselves in our own process group
  7566. * (bash, too, does this only if ctty is available) */
  7567. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  7568. /* Grab control of the terminal */
  7569. tcsetpgrp(G_interactive_fd, getpid());
  7570. }
  7571. /* -1 is special - makes xfuncs longjmp, not exit
  7572. * (we reset die_sleep = 0 whereever we [v]fork) */
  7573. enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
  7574. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  7575. {
  7576. const char *hp = get_local_var_value("HISTFILE");
  7577. if (!hp) {
  7578. hp = get_local_var_value("HOME");
  7579. if (hp)
  7580. hp = concat_path_file(hp, ".hush_history");
  7581. } else {
  7582. hp = xstrdup(hp);
  7583. }
  7584. if (hp) {
  7585. G.line_input_state->hist_file = hp;
  7586. //set_local_var(xasprintf("HISTFILE=%s", ...));
  7587. }
  7588. # if ENABLE_FEATURE_SH_HISTFILESIZE
  7589. hp = get_local_var_value("HISTFILESIZE");
  7590. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  7591. # endif
  7592. }
  7593. # endif
  7594. } else {
  7595. install_special_sighandlers();
  7596. }
  7597. #elif ENABLE_HUSH_INTERACTIVE
  7598. /* No job control compiled in, only prompt/line editing */
  7599. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  7600. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  7601. if (G_interactive_fd < 0) {
  7602. /* try to dup to any fd */
  7603. G_interactive_fd = dup(STDIN_FILENO);
  7604. if (G_interactive_fd < 0)
  7605. /* give up */
  7606. G_interactive_fd = 0;
  7607. }
  7608. }
  7609. if (G_interactive_fd) {
  7610. close_on_exec_on(G_interactive_fd);
  7611. }
  7612. install_special_sighandlers();
  7613. #else
  7614. /* We have interactiveness code disabled */
  7615. install_special_sighandlers();
  7616. #endif
  7617. /* bash:
  7618. * if interactive but not a login shell, sources ~/.bashrc
  7619. * (--norc turns this off, --rcfile <file> overrides)
  7620. */
  7621. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  7622. /* note: ash and hush share this string */
  7623. printf("\n\n%s %s\n"
  7624. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  7625. "\n",
  7626. bb_banner,
  7627. "hush - the humble shell"
  7628. );
  7629. }
  7630. parse_and_run_file(stdin);
  7631. final_return:
  7632. hush_exit(G.last_exitcode);
  7633. }
  7634. #if ENABLE_MSH
  7635. int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  7636. int msh_main(int argc, char **argv)
  7637. {
  7638. //bb_error_msg("msh is deprecated, please use hush instead");
  7639. return hush_main(argc, argv);
  7640. }
  7641. #endif
  7642. /*
  7643. * Built-ins
  7644. */
  7645. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  7646. {
  7647. return 0;
  7648. }
  7649. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  7650. {
  7651. int argc = 0;
  7652. while (*argv) {
  7653. argc++;
  7654. argv++;
  7655. }
  7656. return applet_main_func(argc, argv - argc);
  7657. }
  7658. static int FAST_FUNC builtin_test(char **argv)
  7659. {
  7660. return run_applet_main(argv, test_main);
  7661. }
  7662. static int FAST_FUNC builtin_echo(char **argv)
  7663. {
  7664. return run_applet_main(argv, echo_main);
  7665. }
  7666. #if ENABLE_PRINTF
  7667. static int FAST_FUNC builtin_printf(char **argv)
  7668. {
  7669. return run_applet_main(argv, printf_main);
  7670. }
  7671. #endif
  7672. static char **skip_dash_dash(char **argv)
  7673. {
  7674. argv++;
  7675. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  7676. argv++;
  7677. return argv;
  7678. }
  7679. static int FAST_FUNC builtin_eval(char **argv)
  7680. {
  7681. int rcode = EXIT_SUCCESS;
  7682. argv = skip_dash_dash(argv);
  7683. if (*argv) {
  7684. char *str = expand_strvec_to_string(argv);
  7685. /* bash:
  7686. * eval "echo Hi; done" ("done" is syntax error):
  7687. * "echo Hi" will not execute too.
  7688. */
  7689. parse_and_run_string(str);
  7690. free(str);
  7691. rcode = G.last_exitcode;
  7692. }
  7693. return rcode;
  7694. }
  7695. static int FAST_FUNC builtin_cd(char **argv)
  7696. {
  7697. const char *newdir;
  7698. argv = skip_dash_dash(argv);
  7699. newdir = argv[0];
  7700. if (newdir == NULL) {
  7701. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  7702. * bash says "bash: cd: HOME not set" and does nothing
  7703. * (exitcode 1)
  7704. */
  7705. const char *home = get_local_var_value("HOME");
  7706. newdir = home ? home : "/";
  7707. }
  7708. if (chdir(newdir)) {
  7709. /* Mimic bash message exactly */
  7710. bb_perror_msg("cd: %s", newdir);
  7711. return EXIT_FAILURE;
  7712. }
  7713. /* Read current dir (get_cwd(1) is inside) and set PWD.
  7714. * Note: do not enforce exporting. If PWD was unset or unexported,
  7715. * set it again, but do not export. bash does the same.
  7716. */
  7717. set_pwd_var(/*exp:*/ 0);
  7718. return EXIT_SUCCESS;
  7719. }
  7720. static int FAST_FUNC builtin_exec(char **argv)
  7721. {
  7722. argv = skip_dash_dash(argv);
  7723. if (argv[0] == NULL)
  7724. return EXIT_SUCCESS; /* bash does this */
  7725. /* Careful: we can end up here after [v]fork. Do not restore
  7726. * tty pgrp then, only top-level shell process does that */
  7727. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  7728. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  7729. /* TODO: if exec fails, bash does NOT exit! We do.
  7730. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  7731. * and tcsetpgrp, and this is inherently racy.
  7732. */
  7733. execvp_or_die(argv);
  7734. }
  7735. static int FAST_FUNC builtin_exit(char **argv)
  7736. {
  7737. debug_printf_exec("%s()\n", __func__);
  7738. /* interactive bash:
  7739. * # trap "echo EEE" EXIT
  7740. * # exit
  7741. * exit
  7742. * There are stopped jobs.
  7743. * (if there are _stopped_ jobs, running ones don't count)
  7744. * # exit
  7745. * exit
  7746. * EEE (then bash exits)
  7747. *
  7748. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  7749. */
  7750. /* note: EXIT trap is run by hush_exit */
  7751. argv = skip_dash_dash(argv);
  7752. if (argv[0] == NULL)
  7753. hush_exit(G.last_exitcode);
  7754. /* mimic bash: exit 123abc == exit 255 + error msg */
  7755. xfunc_error_retval = 255;
  7756. /* bash: exit -2 == exit 254, no error msg */
  7757. hush_exit(xatoi(argv[0]) & 0xff);
  7758. }
  7759. static void print_escaped(const char *s)
  7760. {
  7761. if (*s == '\'')
  7762. goto squote;
  7763. do {
  7764. const char *p = strchrnul(s, '\'');
  7765. /* print 'xxxx', possibly just '' */
  7766. printf("'%.*s'", (int)(p - s), s);
  7767. if (*p == '\0')
  7768. break;
  7769. s = p;
  7770. squote:
  7771. /* s points to '; print "'''...'''" */
  7772. putchar('"');
  7773. do putchar('\''); while (*++s == '\'');
  7774. putchar('"');
  7775. } while (*s);
  7776. }
  7777. #if !ENABLE_HUSH_LOCAL
  7778. #define helper_export_local(argv, exp, lvl) \
  7779. helper_export_local(argv, exp)
  7780. #endif
  7781. static void helper_export_local(char **argv, int exp, int lvl)
  7782. {
  7783. do {
  7784. char *name = *argv;
  7785. char *name_end = strchrnul(name, '=');
  7786. /* So far we do not check that name is valid (TODO?) */
  7787. if (*name_end == '\0') {
  7788. struct variable *var, **vpp;
  7789. vpp = get_ptr_to_local_var(name, name_end - name);
  7790. var = vpp ? *vpp : NULL;
  7791. if (exp == -1) { /* unexporting? */
  7792. /* export -n NAME (without =VALUE) */
  7793. if (var) {
  7794. var->flg_export = 0;
  7795. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  7796. unsetenv(name);
  7797. } /* else: export -n NOT_EXISTING_VAR: no-op */
  7798. continue;
  7799. }
  7800. if (exp == 1) { /* exporting? */
  7801. /* export NAME (without =VALUE) */
  7802. if (var) {
  7803. var->flg_export = 1;
  7804. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  7805. putenv(var->varstr);
  7806. continue;
  7807. }
  7808. }
  7809. /* Exporting non-existing variable.
  7810. * bash does not put it in environment,
  7811. * but remembers that it is exported,
  7812. * and does put it in env when it is set later.
  7813. * We just set it to "" and export. */
  7814. /* Or, it's "local NAME" (without =VALUE).
  7815. * bash sets the value to "". */
  7816. name = xasprintf("%s=", name);
  7817. } else {
  7818. /* (Un)exporting/making local NAME=VALUE */
  7819. name = xstrdup(name);
  7820. }
  7821. set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
  7822. } while (*++argv);
  7823. }
  7824. static int FAST_FUNC builtin_export(char **argv)
  7825. {
  7826. unsigned opt_unexport;
  7827. #if ENABLE_HUSH_EXPORT_N
  7828. /* "!": do not abort on errors */
  7829. opt_unexport = getopt32(argv, "!n");
  7830. if (opt_unexport == (uint32_t)-1)
  7831. return EXIT_FAILURE;
  7832. argv += optind;
  7833. #else
  7834. opt_unexport = 0;
  7835. argv++;
  7836. #endif
  7837. if (argv[0] == NULL) {
  7838. char **e = environ;
  7839. if (e) {
  7840. while (*e) {
  7841. #if 0
  7842. puts(*e++);
  7843. #else
  7844. /* ash emits: export VAR='VAL'
  7845. * bash: declare -x VAR="VAL"
  7846. * we follow ash example */
  7847. const char *s = *e++;
  7848. const char *p = strchr(s, '=');
  7849. if (!p) /* wtf? take next variable */
  7850. continue;
  7851. /* export var= */
  7852. printf("export %.*s", (int)(p - s) + 1, s);
  7853. print_escaped(p + 1);
  7854. putchar('\n');
  7855. #endif
  7856. }
  7857. /*fflush_all(); - done after each builtin anyway */
  7858. }
  7859. return EXIT_SUCCESS;
  7860. }
  7861. helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
  7862. return EXIT_SUCCESS;
  7863. }
  7864. #if ENABLE_HUSH_LOCAL
  7865. static int FAST_FUNC builtin_local(char **argv)
  7866. {
  7867. if (G.func_nest_level == 0) {
  7868. bb_error_msg("%s: not in a function", argv[0]);
  7869. return EXIT_FAILURE; /* bash compat */
  7870. }
  7871. helper_export_local(argv, 0, G.func_nest_level);
  7872. return EXIT_SUCCESS;
  7873. }
  7874. #endif
  7875. static int FAST_FUNC builtin_trap(char **argv)
  7876. {
  7877. int sig;
  7878. char *new_cmd;
  7879. if (!G.traps)
  7880. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7881. argv++;
  7882. if (!*argv) {
  7883. int i;
  7884. /* No args: print all trapped */
  7885. for (i = 0; i < NSIG; ++i) {
  7886. if (G.traps[i]) {
  7887. printf("trap -- ");
  7888. print_escaped(G.traps[i]);
  7889. /* note: bash adds "SIG", but only if invoked
  7890. * as "bash". If called as "sh", or if set -o posix,
  7891. * then it prints short signal names.
  7892. * We are printing short names: */
  7893. printf(" %s\n", get_signame(i));
  7894. }
  7895. }
  7896. /*fflush_all(); - done after each builtin anyway */
  7897. return EXIT_SUCCESS;
  7898. }
  7899. new_cmd = NULL;
  7900. /* If first arg is a number: reset all specified signals */
  7901. sig = bb_strtou(*argv, NULL, 10);
  7902. if (errno == 0) {
  7903. int ret;
  7904. process_sig_list:
  7905. ret = EXIT_SUCCESS;
  7906. while (*argv) {
  7907. sighandler_t handler;
  7908. sig = get_signum(*argv++);
  7909. if (sig < 0 || sig >= NSIG) {
  7910. ret = EXIT_FAILURE;
  7911. /* Mimic bash message exactly */
  7912. bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
  7913. continue;
  7914. }
  7915. free(G.traps[sig]);
  7916. G.traps[sig] = xstrdup(new_cmd);
  7917. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  7918. get_signame(sig), sig, G.traps[sig]);
  7919. /* There is no signal for 0 (EXIT) */
  7920. if (sig == 0)
  7921. continue;
  7922. if (new_cmd)
  7923. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  7924. else
  7925. /* We are removing trap handler */
  7926. handler = pick_sighandler(sig);
  7927. install_sighandler(sig, handler);
  7928. }
  7929. return ret;
  7930. }
  7931. if (!argv[1]) { /* no second arg */
  7932. bb_error_msg("trap: invalid arguments");
  7933. return EXIT_FAILURE;
  7934. }
  7935. /* First arg is "-": reset all specified to default */
  7936. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  7937. /* Everything else: set arg as signal handler
  7938. * (includes "" case, which ignores signal) */
  7939. if (argv[0][0] == '-') {
  7940. if (argv[0][1] == '\0') { /* "-" */
  7941. /* new_cmd remains NULL: "reset these sigs" */
  7942. goto reset_traps;
  7943. }
  7944. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  7945. argv++;
  7946. }
  7947. /* else: "-something", no special meaning */
  7948. }
  7949. new_cmd = *argv;
  7950. reset_traps:
  7951. argv++;
  7952. goto process_sig_list;
  7953. }
  7954. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  7955. static int FAST_FUNC builtin_type(char **argv)
  7956. {
  7957. int ret = EXIT_SUCCESS;
  7958. while (*++argv) {
  7959. const char *type;
  7960. char *path = NULL;
  7961. if (0) {} /* make conditional compile easier below */
  7962. /*else if (find_alias(*argv))
  7963. type = "an alias";*/
  7964. #if ENABLE_HUSH_FUNCTIONS
  7965. else if (find_function(*argv))
  7966. type = "a function";
  7967. #endif
  7968. else if (find_builtin(*argv))
  7969. type = "a shell builtin";
  7970. else if ((path = find_in_path(*argv)) != NULL)
  7971. type = path;
  7972. else {
  7973. bb_error_msg("type: %s: not found", *argv);
  7974. ret = EXIT_FAILURE;
  7975. continue;
  7976. }
  7977. printf("%s is %s\n", *argv, type);
  7978. free(path);
  7979. }
  7980. return ret;
  7981. }
  7982. #if ENABLE_HUSH_JOB
  7983. /* built-in 'fg' and 'bg' handler */
  7984. static int FAST_FUNC builtin_fg_bg(char **argv)
  7985. {
  7986. int i, jobnum;
  7987. struct pipe *pi;
  7988. if (!G_interactive_fd)
  7989. return EXIT_FAILURE;
  7990. /* If they gave us no args, assume they want the last backgrounded task */
  7991. if (!argv[1]) {
  7992. for (pi = G.job_list; pi; pi = pi->next) {
  7993. if (pi->jobid == G.last_jobid) {
  7994. goto found;
  7995. }
  7996. }
  7997. bb_error_msg("%s: no current job", argv[0]);
  7998. return EXIT_FAILURE;
  7999. }
  8000. if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
  8001. bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
  8002. return EXIT_FAILURE;
  8003. }
  8004. for (pi = G.job_list; pi; pi = pi->next) {
  8005. if (pi->jobid == jobnum) {
  8006. goto found;
  8007. }
  8008. }
  8009. bb_error_msg("%s: %d: no such job", argv[0], jobnum);
  8010. return EXIT_FAILURE;
  8011. found:
  8012. /* TODO: bash prints a string representation
  8013. * of job being foregrounded (like "sleep 1 | cat") */
  8014. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  8015. /* Put the job into the foreground. */
  8016. tcsetpgrp(G_interactive_fd, pi->pgrp);
  8017. }
  8018. /* Restart the processes in the job */
  8019. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  8020. for (i = 0; i < pi->num_cmds; i++) {
  8021. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  8022. }
  8023. pi->stopped_cmds = 0;
  8024. i = kill(- pi->pgrp, SIGCONT);
  8025. if (i < 0) {
  8026. if (errno == ESRCH) {
  8027. delete_finished_bg_job(pi);
  8028. return EXIT_SUCCESS;
  8029. }
  8030. bb_perror_msg("kill (SIGCONT)");
  8031. }
  8032. if (argv[0][0] == 'f') {
  8033. remove_bg_job(pi);
  8034. return checkjobs_and_fg_shell(pi);
  8035. }
  8036. return EXIT_SUCCESS;
  8037. }
  8038. #endif
  8039. #if ENABLE_HUSH_HELP
  8040. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  8041. {
  8042. const struct built_in_command *x;
  8043. printf(
  8044. "Built-in commands:\n"
  8045. "------------------\n");
  8046. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  8047. if (x->b_descr)
  8048. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  8049. }
  8050. bb_putchar('\n');
  8051. return EXIT_SUCCESS;
  8052. }
  8053. #endif
  8054. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  8055. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  8056. {
  8057. show_history(G.line_input_state);
  8058. return EXIT_SUCCESS;
  8059. }
  8060. #endif
  8061. #if ENABLE_HUSH_JOB
  8062. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  8063. {
  8064. struct pipe *job;
  8065. const char *status_string;
  8066. for (job = G.job_list; job; job = job->next) {
  8067. if (job->alive_cmds == job->stopped_cmds)
  8068. status_string = "Stopped";
  8069. else
  8070. status_string = "Running";
  8071. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  8072. }
  8073. return EXIT_SUCCESS;
  8074. }
  8075. #endif
  8076. #if HUSH_DEBUG
  8077. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  8078. {
  8079. void *p;
  8080. unsigned long l;
  8081. # ifdef M_TRIM_THRESHOLD
  8082. /* Optional. Reduces probability of false positives */
  8083. malloc_trim(0);
  8084. # endif
  8085. /* Crude attempt to find where "free memory" starts,
  8086. * sans fragmentation. */
  8087. p = malloc(240);
  8088. l = (unsigned long)p;
  8089. free(p);
  8090. p = malloc(3400);
  8091. if (l < (unsigned long)p) l = (unsigned long)p;
  8092. free(p);
  8093. if (!G.memleak_value)
  8094. G.memleak_value = l;
  8095. l -= G.memleak_value;
  8096. if ((long)l < 0)
  8097. l = 0;
  8098. l /= 1024;
  8099. if (l > 127)
  8100. l = 127;
  8101. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  8102. return l;
  8103. }
  8104. #endif
  8105. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  8106. {
  8107. puts(get_cwd(0));
  8108. return EXIT_SUCCESS;
  8109. }
  8110. /* Interruptibility of read builtin in bash
  8111. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  8112. *
  8113. * Empty trap makes read ignore corresponding signal, for any signal.
  8114. *
  8115. * SIGINT:
  8116. * - terminates non-interactive shell;
  8117. * - interrupts read in interactive shell;
  8118. * if it has non-empty trap:
  8119. * - executes trap and returns to command prompt in interactive shell;
  8120. * - executes trap and returns to read in non-interactive shell;
  8121. * SIGTERM:
  8122. * - is ignored (does not interrupt) read in interactive shell;
  8123. * - terminates non-interactive shell;
  8124. * if it has non-empty trap:
  8125. * - executes trap and returns to read;
  8126. * SIGHUP:
  8127. * - terminates shell (regardless of interactivity);
  8128. * if it has non-empty trap:
  8129. * - executes trap and returns to read;
  8130. */
  8131. static int FAST_FUNC builtin_read(char **argv)
  8132. {
  8133. const char *r;
  8134. char *opt_n = NULL;
  8135. char *opt_p = NULL;
  8136. char *opt_t = NULL;
  8137. char *opt_u = NULL;
  8138. const char *ifs;
  8139. int read_flags;
  8140. /* "!": do not abort on errors.
  8141. * Option string must start with "sr" to match BUILTIN_READ_xxx
  8142. */
  8143. read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
  8144. if (read_flags == (uint32_t)-1)
  8145. return EXIT_FAILURE;
  8146. argv += optind;
  8147. ifs = get_local_var_value("IFS"); /* can be NULL */
  8148. again:
  8149. r = shell_builtin_read(set_local_var_from_halves,
  8150. argv,
  8151. ifs,
  8152. read_flags,
  8153. opt_n,
  8154. opt_p,
  8155. opt_t,
  8156. opt_u
  8157. );
  8158. if ((uintptr_t)r == 1 && errno == EINTR) {
  8159. unsigned sig = check_and_run_traps();
  8160. if (sig && sig != SIGINT)
  8161. goto again;
  8162. }
  8163. if ((uintptr_t)r > 1) {
  8164. bb_error_msg("%s", r);
  8165. r = (char*)(uintptr_t)1;
  8166. }
  8167. return (uintptr_t)r;
  8168. }
  8169. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  8170. * built-in 'set' handler
  8171. * SUSv3 says:
  8172. * set [-abCefhmnuvx] [-o option] [argument...]
  8173. * set [+abCefhmnuvx] [+o option] [argument...]
  8174. * set -- [argument...]
  8175. * set -o
  8176. * set +o
  8177. * Implementations shall support the options in both their hyphen and
  8178. * plus-sign forms. These options can also be specified as options to sh.
  8179. * Examples:
  8180. * Write out all variables and their values: set
  8181. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  8182. * Turn on the -x and -v options: set -xv
  8183. * Unset all positional parameters: set --
  8184. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  8185. * Set the positional parameters to the expansion of x, even if x expands
  8186. * with a leading '-' or '+': set -- $x
  8187. *
  8188. * So far, we only support "set -- [argument...]" and some of the short names.
  8189. */
  8190. static int FAST_FUNC builtin_set(char **argv)
  8191. {
  8192. int n;
  8193. char **pp, **g_argv;
  8194. char *arg = *++argv;
  8195. if (arg == NULL) {
  8196. struct variable *e;
  8197. for (e = G.top_var; e; e = e->next)
  8198. puts(e->varstr);
  8199. return EXIT_SUCCESS;
  8200. }
  8201. do {
  8202. if (strcmp(arg, "--") == 0) {
  8203. ++argv;
  8204. goto set_argv;
  8205. }
  8206. if (arg[0] != '+' && arg[0] != '-')
  8207. break;
  8208. for (n = 1; arg[n]; ++n) {
  8209. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  8210. goto error;
  8211. if (arg[n] == 'o' && argv[1])
  8212. argv++;
  8213. }
  8214. } while ((arg = *++argv) != NULL);
  8215. /* Now argv[0] is 1st argument */
  8216. if (arg == NULL)
  8217. return EXIT_SUCCESS;
  8218. set_argv:
  8219. /* NB: G.global_argv[0] ($0) is never freed/changed */
  8220. g_argv = G.global_argv;
  8221. if (G.global_args_malloced) {
  8222. pp = g_argv;
  8223. while (*++pp)
  8224. free(*pp);
  8225. g_argv[1] = NULL;
  8226. } else {
  8227. G.global_args_malloced = 1;
  8228. pp = xzalloc(sizeof(pp[0]) * 2);
  8229. pp[0] = g_argv[0]; /* retain $0 */
  8230. g_argv = pp;
  8231. }
  8232. /* This realloc's G.global_argv */
  8233. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  8234. n = 1;
  8235. while (*++pp)
  8236. n++;
  8237. G.global_argc = n;
  8238. return EXIT_SUCCESS;
  8239. /* Nothing known, so abort */
  8240. error:
  8241. bb_error_msg("set: %s: invalid option", arg);
  8242. return EXIT_FAILURE;
  8243. }
  8244. static int FAST_FUNC builtin_shift(char **argv)
  8245. {
  8246. int n = 1;
  8247. argv = skip_dash_dash(argv);
  8248. if (argv[0]) {
  8249. n = atoi(argv[0]);
  8250. }
  8251. if (n >= 0 && n < G.global_argc) {
  8252. if (G.global_args_malloced) {
  8253. int m = 1;
  8254. while (m <= n)
  8255. free(G.global_argv[m++]);
  8256. }
  8257. G.global_argc -= n;
  8258. memmove(&G.global_argv[1], &G.global_argv[n+1],
  8259. G.global_argc * sizeof(G.global_argv[0]));
  8260. return EXIT_SUCCESS;
  8261. }
  8262. return EXIT_FAILURE;
  8263. }
  8264. static int FAST_FUNC builtin_source(char **argv)
  8265. {
  8266. char *arg_path, *filename;
  8267. FILE *input;
  8268. save_arg_t sv;
  8269. #if ENABLE_HUSH_FUNCTIONS
  8270. smallint sv_flg;
  8271. #endif
  8272. argv = skip_dash_dash(argv);
  8273. filename = argv[0];
  8274. if (!filename) {
  8275. /* bash says: "bash: .: filename argument required" */
  8276. return 2; /* bash compat */
  8277. }
  8278. arg_path = NULL;
  8279. if (!strchr(filename, '/')) {
  8280. arg_path = find_in_path(filename);
  8281. if (arg_path)
  8282. filename = arg_path;
  8283. }
  8284. input = fopen_or_warn(filename, "r");
  8285. free(arg_path);
  8286. if (!input) {
  8287. /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
  8288. /* POSIX: non-interactive shell should abort here,
  8289. * not merely fail. So far no one complained :)
  8290. */
  8291. return EXIT_FAILURE;
  8292. }
  8293. close_on_exec_on(fileno(input));
  8294. #if ENABLE_HUSH_FUNCTIONS
  8295. sv_flg = G.flag_return_in_progress;
  8296. /* "we are inside sourced file, ok to use return" */
  8297. G.flag_return_in_progress = -1;
  8298. #endif
  8299. if (argv[1])
  8300. save_and_replace_G_args(&sv, argv);
  8301. parse_and_run_file(input);
  8302. fclose(input);
  8303. if (argv[1])
  8304. restore_G_args(&sv, argv);
  8305. #if ENABLE_HUSH_FUNCTIONS
  8306. G.flag_return_in_progress = sv_flg;
  8307. #endif
  8308. return G.last_exitcode;
  8309. }
  8310. static int FAST_FUNC builtin_umask(char **argv)
  8311. {
  8312. int rc;
  8313. mode_t mask;
  8314. mask = umask(0);
  8315. argv = skip_dash_dash(argv);
  8316. if (argv[0]) {
  8317. mode_t old_mask = mask;
  8318. mask ^= 0777;
  8319. rc = bb_parse_mode(argv[0], &mask);
  8320. mask ^= 0777;
  8321. if (rc == 0) {
  8322. mask = old_mask;
  8323. /* bash messages:
  8324. * bash: umask: 'q': invalid symbolic mode operator
  8325. * bash: umask: 999: octal number out of range
  8326. */
  8327. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  8328. }
  8329. } else {
  8330. rc = 1;
  8331. /* Mimic bash */
  8332. printf("%04o\n", (unsigned) mask);
  8333. /* fall through and restore mask which we set to 0 */
  8334. }
  8335. umask(mask);
  8336. return !rc; /* rc != 0 - success */
  8337. }
  8338. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  8339. static int FAST_FUNC builtin_unset(char **argv)
  8340. {
  8341. int ret;
  8342. unsigned opts;
  8343. /* "!": do not abort on errors */
  8344. /* "+": stop at 1st non-option */
  8345. opts = getopt32(argv, "!+vf");
  8346. if (opts == (unsigned)-1)
  8347. return EXIT_FAILURE;
  8348. if (opts == 3) {
  8349. bb_error_msg("unset: -v and -f are exclusive");
  8350. return EXIT_FAILURE;
  8351. }
  8352. argv += optind;
  8353. ret = EXIT_SUCCESS;
  8354. while (*argv) {
  8355. if (!(opts & 2)) { /* not -f */
  8356. if (unset_local_var(*argv)) {
  8357. /* unset <nonexistent_var> doesn't fail.
  8358. * Error is when one tries to unset RO var.
  8359. * Message was printed by unset_local_var. */
  8360. ret = EXIT_FAILURE;
  8361. }
  8362. }
  8363. #if ENABLE_HUSH_FUNCTIONS
  8364. else {
  8365. unset_func(*argv);
  8366. }
  8367. #endif
  8368. argv++;
  8369. }
  8370. return ret;
  8371. }
  8372. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  8373. static int FAST_FUNC builtin_wait(char **argv)
  8374. {
  8375. int ret = EXIT_SUCCESS;
  8376. int status;
  8377. argv = skip_dash_dash(argv);
  8378. if (argv[0] == NULL) {
  8379. /* Don't care about wait results */
  8380. /* Note 1: must wait until there are no more children */
  8381. /* Note 2: must be interruptible */
  8382. /* Examples:
  8383. * $ sleep 3 & sleep 6 & wait
  8384. * [1] 30934 sleep 3
  8385. * [2] 30935 sleep 6
  8386. * [1] Done sleep 3
  8387. * [2] Done sleep 6
  8388. * $ sleep 3 & sleep 6 & wait
  8389. * [1] 30936 sleep 3
  8390. * [2] 30937 sleep 6
  8391. * [1] Done sleep 3
  8392. * ^C <-- after ~4 sec from keyboard
  8393. * $
  8394. */
  8395. while (1) {
  8396. int sig;
  8397. sigset_t oldset, allsigs;
  8398. /* waitpid is not interruptible by SA_RESTARTed
  8399. * signals which we use. Thus, this ugly dance:
  8400. */
  8401. /* Make sure possible SIGCHLD is stored in kernel's
  8402. * pending signal mask before we call waitpid.
  8403. * Or else we may race with SIGCHLD, lose it,
  8404. * and get stuck in sigwaitinfo...
  8405. */
  8406. sigfillset(&allsigs);
  8407. sigprocmask(SIG_SETMASK, &allsigs, &oldset);
  8408. if (!sigisemptyset(&G.pending_set)) {
  8409. /* Crap! we raced with some signal! */
  8410. // sig = 0;
  8411. goto restore;
  8412. }
  8413. checkjobs(NULL); /* waitpid(WNOHANG) inside */
  8414. if (errno == ECHILD) {
  8415. sigprocmask(SIG_SETMASK, &oldset, NULL);
  8416. break;
  8417. }
  8418. /* Wait for SIGCHLD or any other signal */
  8419. //sig = sigwaitinfo(&allsigs, NULL);
  8420. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  8421. /* Note: sigsuspend invokes signal handler */
  8422. sigsuspend(&oldset);
  8423. restore:
  8424. sigprocmask(SIG_SETMASK, &oldset, NULL);
  8425. /* So, did we get a signal? */
  8426. //if (sig > 0)
  8427. // raise(sig); /* run handler */
  8428. sig = check_and_run_traps();
  8429. if (sig /*&& sig != SIGCHLD - always true */) {
  8430. /* see note 2 */
  8431. ret = 128 + sig;
  8432. break;
  8433. }
  8434. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  8435. }
  8436. return ret;
  8437. }
  8438. /* This is probably buggy wrt interruptible-ness */
  8439. while (*argv) {
  8440. pid_t pid = bb_strtou(*argv, NULL, 10);
  8441. if (errno) {
  8442. /* mimic bash message */
  8443. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  8444. return EXIT_FAILURE;
  8445. }
  8446. if (waitpid(pid, &status, 0) == pid) {
  8447. if (WIFSIGNALED(status))
  8448. ret = 128 + WTERMSIG(status);
  8449. else if (WIFEXITED(status))
  8450. ret = WEXITSTATUS(status);
  8451. else /* wtf? */
  8452. ret = EXIT_FAILURE;
  8453. } else {
  8454. bb_perror_msg("wait %s", *argv);
  8455. ret = 127;
  8456. }
  8457. argv++;
  8458. }
  8459. return ret;
  8460. }
  8461. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  8462. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  8463. {
  8464. if (argv[1]) {
  8465. def = bb_strtou(argv[1], NULL, 10);
  8466. if (errno || def < def_min || argv[2]) {
  8467. bb_error_msg("%s: bad arguments", argv[0]);
  8468. def = UINT_MAX;
  8469. }
  8470. }
  8471. return def;
  8472. }
  8473. #endif
  8474. #if ENABLE_HUSH_LOOPS
  8475. static int FAST_FUNC builtin_break(char **argv)
  8476. {
  8477. unsigned depth;
  8478. if (G.depth_of_loop == 0) {
  8479. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  8480. return EXIT_SUCCESS; /* bash compat */
  8481. }
  8482. G.flag_break_continue++; /* BC_BREAK = 1 */
  8483. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  8484. if (depth == UINT_MAX)
  8485. G.flag_break_continue = BC_BREAK;
  8486. if (G.depth_of_loop < depth)
  8487. G.depth_break_continue = G.depth_of_loop;
  8488. return EXIT_SUCCESS;
  8489. }
  8490. static int FAST_FUNC builtin_continue(char **argv)
  8491. {
  8492. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  8493. return builtin_break(argv);
  8494. }
  8495. #endif
  8496. #if ENABLE_HUSH_FUNCTIONS
  8497. static int FAST_FUNC builtin_return(char **argv)
  8498. {
  8499. int rc;
  8500. if (G.flag_return_in_progress != -1) {
  8501. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  8502. return EXIT_FAILURE; /* bash compat */
  8503. }
  8504. G.flag_return_in_progress = 1;
  8505. /* bash:
  8506. * out of range: wraps around at 256, does not error out
  8507. * non-numeric param:
  8508. * f() { false; return qwe; }; f; echo $?
  8509. * bash: return: qwe: numeric argument required <== we do this
  8510. * 255 <== we also do this
  8511. */
  8512. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  8513. return rc;
  8514. }
  8515. #endif