hush.c 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085
  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. * Credits:
  12. * The parser routines proper are all original material, first
  13. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  14. * execution engine, the builtins, and much of the underlying
  15. * support has been adapted from busybox-0.49pre's lash, which is
  16. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  17. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  18. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  19. * Troan, which they placed in the public domain. I don't know
  20. * how much of the Johnson/Troan code has survived the repeated
  21. * rewrites.
  22. *
  23. * Other credits:
  24. * o_addchr derived from similar w_addchar function in glibc-2.2.
  25. * parse_redirect, redirect_opt_num, and big chunks of main
  26. * and many builtins derived from contributions by Erik Andersen.
  27. * Miscellaneous bugfixes from Matt Kraai.
  28. *
  29. * There are two big (and related) architecture differences between
  30. * this parser and the lash parser. One is that this version is
  31. * actually designed from the ground up to understand nearly all
  32. * of the Bourne grammar. The second, consequential change is that
  33. * the parser and input reader have been turned inside out. Now,
  34. * the parser is in control, and asks for input as needed. The old
  35. * way had the input reader in control, and it asked for parsing to
  36. * take place as needed. The new way makes it much easier to properly
  37. * handle the recursion implicit in the various substitutions, especially
  38. * across continuation lines.
  39. *
  40. * POSIX syntax not implemented:
  41. * aliases
  42. * <(list) and >(list) Process Substitution
  43. * Tilde Expansion
  44. *
  45. * Bash stuff (maybe optionally enable?):
  46. * &> and >& redirection of stdout+stderr
  47. * Brace expansion
  48. * reserved words: [[ ]] function select
  49. * substrings ${var:1:5}
  50. *
  51. * TODOs:
  52. * grep for "TODO" and fix (some of them are easy)
  53. * change { and } from special chars to reserved words
  54. * $var refs in function do not pick up values set by "var=val func"
  55. * builtins: ulimit
  56. * follow IFS rules more precisely, including update semantics
  57. * figure out what to do with backslash-newline
  58. * continuation lines, both explicit and implicit - done?
  59. * separate job control from interactiveness
  60. * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
  61. *
  62. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  63. */
  64. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  65. #include <glob.h>
  66. /* #include <dmalloc.h> */
  67. #if ENABLE_HUSH_CASE
  68. # include <fnmatch.h>
  69. #endif
  70. #include "math.h"
  71. #include "match.h"
  72. #ifndef PIPE_BUF
  73. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  74. #endif
  75. /* Debug build knobs */
  76. #define LEAK_HUNTING 0
  77. #define BUILD_AS_NOMMU 0
  78. /* Enable/disable sanity checks. Ok to enable in production,
  79. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  80. * Keeping 1 for now even in released versions.
  81. */
  82. #define HUSH_DEBUG 1
  83. #if BUILD_AS_NOMMU
  84. # undef BB_MMU
  85. # undef USE_FOR_NOMMU
  86. # undef USE_FOR_MMU
  87. # define BB_MMU 0
  88. # define USE_FOR_NOMMU(...) __VA_ARGS__
  89. # define USE_FOR_MMU(...)
  90. #endif
  91. #if defined SINGLE_APPLET_MAIN
  92. /* STANDALONE does not make sense, and won't compile */
  93. # undef CONFIG_FEATURE_SH_STANDALONE
  94. # undef ENABLE_FEATURE_SH_STANDALONE
  95. # undef IF_FEATURE_SH_STANDALONE
  96. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  97. # define ENABLE_FEATURE_SH_STANDALONE 0
  98. # define IF_FEATURE_SH_STANDALONE(...)
  99. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  100. #endif
  101. #if !ENABLE_HUSH_INTERACTIVE
  102. # undef ENABLE_FEATURE_EDITING
  103. # define ENABLE_FEATURE_EDITING 0
  104. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  105. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  106. #endif
  107. /* Do we support ANY keywords? */
  108. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  109. # define HAS_KEYWORDS 1
  110. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  111. # define IF_HAS_NO_KEYWORDS(...)
  112. #else
  113. # define HAS_KEYWORDS 0
  114. # define IF_HAS_KEYWORDS(...)
  115. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  116. #endif
  117. /* If you comment out one of these below, it will be #defined later
  118. * to perform debug printfs to stderr: */
  119. #define debug_printf(...) do {} while (0)
  120. /* Finer-grained debug switches */
  121. #define debug_printf_parse(...) do {} while (0)
  122. #define debug_print_tree(a, b) do {} while (0)
  123. #define debug_printf_exec(...) do {} while (0)
  124. #define debug_printf_env(...) do {} while (0)
  125. #define debug_printf_jobs(...) do {} while (0)
  126. #define debug_printf_expand(...) do {} while (0)
  127. #define debug_printf_glob(...) do {} while (0)
  128. #define debug_printf_list(...) do {} while (0)
  129. #define debug_printf_subst(...) do {} while (0)
  130. #define debug_printf_clean(...) do {} while (0)
  131. #define ERR_PTR ((void*)(long)1)
  132. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  133. #define SPECIAL_VAR_SYMBOL 3
  134. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  135. /* This supports saving pointers malloced in vfork child,
  136. * to be freed in the parent.
  137. */
  138. #if !BB_MMU
  139. typedef struct nommu_save_t {
  140. char **new_env;
  141. char **old_env;
  142. char **argv;
  143. char **argv_from_re_execing;
  144. } nommu_save_t;
  145. #endif
  146. /* The descrip member of this structure is only used to make
  147. * debugging output pretty */
  148. static const struct {
  149. int mode;
  150. signed char default_fd;
  151. char descrip[3];
  152. } redir_table[] = {
  153. { 0, 0, "??" },
  154. { O_RDONLY, 0, "<" },
  155. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  156. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  157. { O_RDONLY, 0, "<<" },
  158. { O_CREAT|O_RDWR, 1, "<>" },
  159. /* Should not be needed. Bogus default_fd helps in debugging */
  160. /* { O_RDONLY, 77, "<<" }, */
  161. };
  162. typedef enum reserved_style {
  163. RES_NONE = 0,
  164. #if ENABLE_HUSH_IF
  165. RES_IF ,
  166. RES_THEN ,
  167. RES_ELIF ,
  168. RES_ELSE ,
  169. RES_FI ,
  170. #endif
  171. #if ENABLE_HUSH_LOOPS
  172. RES_FOR ,
  173. RES_WHILE ,
  174. RES_UNTIL ,
  175. RES_DO ,
  176. RES_DONE ,
  177. #endif
  178. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  179. RES_IN ,
  180. #endif
  181. #if ENABLE_HUSH_CASE
  182. RES_CASE ,
  183. /* two pseudo-keywords support contrived "case" syntax: */
  184. RES_MATCH , /* "word)" */
  185. RES_CASEI , /* "this command is inside CASE" */
  186. RES_ESAC ,
  187. #endif
  188. RES_XXXX ,
  189. RES_SNTX
  190. } reserved_style;
  191. typedef struct o_string {
  192. char *data;
  193. int length; /* position where data is appended */
  194. int maxlen;
  195. /* Protect newly added chars against globbing
  196. * (by prepending \ to *, ?, [, \) */
  197. smallint o_escape;
  198. smallint o_glob;
  199. /* At least some part of the string was inside '' or "",
  200. * possibly empty one: word"", wo''rd etc. */
  201. smallint o_quoted;
  202. smallint has_empty_slot;
  203. smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
  204. } o_string;
  205. enum {
  206. MAYBE_ASSIGNMENT = 0,
  207. DEFINITELY_ASSIGNMENT = 1,
  208. NOT_ASSIGNMENT = 2,
  209. WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
  210. };
  211. /* Used for initialization: o_string foo = NULL_O_STRING; */
  212. #define NULL_O_STRING { NULL }
  213. /* I can almost use ordinary FILE*. Is open_memstream() universally
  214. * available? Where is it documented? */
  215. typedef struct in_str {
  216. const char *p;
  217. /* eof_flag=1: last char in ->p is really an EOF */
  218. char eof_flag; /* meaningless if ->p == NULL */
  219. char peek_buf[2];
  220. #if ENABLE_HUSH_INTERACTIVE
  221. smallint promptme;
  222. smallint promptmode; /* 0: PS1, 1: PS2 */
  223. #endif
  224. FILE *file;
  225. int (*get) (struct in_str *);
  226. int (*peek) (struct in_str *);
  227. } in_str;
  228. #define i_getch(input) ((input)->get(input))
  229. #define i_peek(input) ((input)->peek(input))
  230. struct redir_struct {
  231. struct redir_struct *next;
  232. char *rd_filename; /* filename */
  233. int rd_fd; /* fd to redirect */
  234. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  235. int rd_dup;
  236. smallint rd_type; /* (enum redir_type) */
  237. /* note: for heredocs, rd_filename contains heredoc delimiter,
  238. * and subsequently heredoc itself; and rd_dup is a bitmask:
  239. * 1: do we need to trim leading tabs?
  240. * 2: is heredoc quoted (<<'delim' syntax) ?
  241. */
  242. };
  243. typedef enum redir_type {
  244. REDIRECT_INVALID = 0,
  245. REDIRECT_INPUT = 1,
  246. REDIRECT_OVERWRITE = 2,
  247. REDIRECT_APPEND = 3,
  248. REDIRECT_HEREDOC = 4,
  249. REDIRECT_IO = 5,
  250. REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
  251. REDIRFD_CLOSE = -3,
  252. REDIRFD_SYNTAX_ERR = -2,
  253. REDIRFD_TO_FILE = -1,
  254. /* otherwise, rd_fd is redirected to rd_dup */
  255. HEREDOC_SKIPTABS = 1,
  256. HEREDOC_QUOTED = 2,
  257. } redir_type;
  258. struct command {
  259. pid_t pid; /* 0 if exited */
  260. int assignment_cnt; /* how many argv[i] are assignments? */
  261. smallint is_stopped; /* is the command currently running? */
  262. smallint grp_type; /* GRP_xxx */
  263. #define GRP_NORMAL 0
  264. #define GRP_SUBSHELL 1
  265. #if ENABLE_HUSH_FUNCTIONS
  266. # define GRP_FUNCTION 2
  267. #endif
  268. struct pipe *group; /* if non-NULL, this "command" is { list },
  269. * ( list ), or a compound statement */
  270. #if !BB_MMU
  271. char *group_as_string;
  272. #endif
  273. #if ENABLE_HUSH_FUNCTIONS
  274. struct function *child_func;
  275. /* This field is used to prevent a bug here:
  276. * while...do f1() {a;}; f1; f1 {b;}; f1; done
  277. * When we execute "f1() {a;}" cmd, we create new function and clear
  278. * cmd->group, cmd->group_as_string, cmd->argv[0].
  279. * when we execute "f1 {b;}", we notice that f1 exists,
  280. * and that it's "parent cmd" struct is still "alive",
  281. * we put those fields back into cmd->xxx
  282. * (struct function has ->parent_cmd ptr to facilitate that).
  283. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  284. * Without this trick, loop would execute a;b;b;b;...
  285. * instead of correct sequence a;b;a;b;...
  286. * When command is freed, it severs the link
  287. * (sets ->child_func->parent_cmd to NULL).
  288. */
  289. #endif
  290. char **argv; /* command name and arguments */
  291. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  292. * and on execution these are substituted with their values.
  293. * Substitution can make _several_ words out of one argv[n]!
  294. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  295. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  296. */
  297. struct redir_struct *redirects; /* I/O redirections */
  298. };
  299. /* Is there anything in this command at all? */
  300. #define IS_NULL_CMD(cmd) \
  301. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  302. struct pipe {
  303. struct pipe *next;
  304. int num_cmds; /* total number of commands in pipe */
  305. int alive_cmds; /* number of commands running (not exited) */
  306. int stopped_cmds; /* number of commands alive, but stopped */
  307. #if ENABLE_HUSH_JOB
  308. int jobid; /* job number */
  309. pid_t pgrp; /* process group ID for the job */
  310. char *cmdtext; /* name of job */
  311. #endif
  312. struct command *cmds; /* array of commands in pipe */
  313. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  314. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  315. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  316. };
  317. typedef enum pipe_style {
  318. PIPE_SEQ = 1,
  319. PIPE_AND = 2,
  320. PIPE_OR = 3,
  321. PIPE_BG = 4,
  322. } pipe_style;
  323. /* Is there anything in this pipe at all? */
  324. #define IS_NULL_PIPE(pi) \
  325. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  326. /* This holds pointers to the various results of parsing */
  327. struct parse_context {
  328. /* linked list of pipes */
  329. struct pipe *list_head;
  330. /* last pipe (being constructed right now) */
  331. struct pipe *pipe;
  332. /* last command in pipe (being constructed right now) */
  333. struct command *command;
  334. /* last redirect in command->redirects list */
  335. struct redir_struct *pending_redirect;
  336. #if !BB_MMU
  337. o_string as_string;
  338. #endif
  339. #if HAS_KEYWORDS
  340. smallint ctx_res_w;
  341. smallint ctx_inverted; /* "! cmd | cmd" */
  342. #if ENABLE_HUSH_CASE
  343. smallint ctx_dsemicolon; /* ";;" seen */
  344. #endif
  345. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  346. int old_flag;
  347. /* group we are enclosed in:
  348. * example: "if pipe1; pipe2; then pipe3; fi"
  349. * when we see "if" or "then", we malloc and copy current context,
  350. * and make ->stack point to it. then we parse pipeN.
  351. * when closing "then" / fi" / whatever is found,
  352. * we move list_head into ->stack->command->group,
  353. * copy ->stack into current context, and delete ->stack.
  354. * (parsing of { list } and ( list ) doesn't use this method)
  355. */
  356. struct parse_context *stack;
  357. #endif
  358. };
  359. /* On program start, environ points to initial environment.
  360. * putenv adds new pointers into it, unsetenv removes them.
  361. * Neither of these (de)allocates the strings.
  362. * setenv allocates new strings in malloc space and does putenv,
  363. * and thus setenv is unusable (leaky) for shell's purposes */
  364. #define setenv(...) setenv_is_leaky_dont_use()
  365. struct variable {
  366. struct variable *next;
  367. char *varstr; /* points to "name=" portion */
  368. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  369. smallint flg_export; /* putenv should be done on this var */
  370. smallint flg_read_only;
  371. };
  372. enum {
  373. BC_BREAK = 1,
  374. BC_CONTINUE = 2,
  375. };
  376. #if ENABLE_HUSH_FUNCTIONS
  377. struct function {
  378. struct function *next;
  379. char *name;
  380. struct command *parent_cmd;
  381. struct pipe *body;
  382. #if !BB_MMU
  383. char *body_as_string;
  384. #endif
  385. };
  386. #endif
  387. /* "Globals" within this file */
  388. /* Sorted roughly by size (smaller offsets == smaller code) */
  389. struct globals {
  390. #if ENABLE_HUSH_INTERACTIVE
  391. /* 'interactive_fd' is a fd# open to ctty, if we have one
  392. * _AND_ if we decided to act interactively */
  393. int interactive_fd;
  394. const char *PS1;
  395. const char *PS2;
  396. #define G_interactive_fd (G.interactive_fd)
  397. #else
  398. #define G_interactive_fd 0
  399. #endif
  400. #if ENABLE_FEATURE_EDITING
  401. line_input_t *line_input_state;
  402. #endif
  403. pid_t root_pid;
  404. pid_t last_bg_pid;
  405. #if ENABLE_HUSH_JOB
  406. int run_list_level;
  407. pid_t saved_tty_pgrp;
  408. int last_jobid;
  409. struct pipe *job_list;
  410. struct pipe *toplevel_list;
  411. #endif
  412. smallint flag_SIGINT;
  413. #if ENABLE_HUSH_LOOPS
  414. smallint flag_break_continue;
  415. #endif
  416. #if ENABLE_HUSH_FUNCTIONS
  417. /* 0: outside of a function (or sourced file)
  418. * -1: inside of a function, ok to use return builtin
  419. * 1: return is invoked, skip all till end of func.
  420. */
  421. smallint flag_return_in_progress;
  422. #endif
  423. smallint fake_mode;
  424. smallint exiting; /* used to prevent EXIT trap recursion */
  425. /* These four support $?, $#, and $1 */
  426. smalluint last_exitcode;
  427. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  428. smalluint global_args_malloced;
  429. /* how many non-NULL argv's we have. NB: $# + 1 */
  430. int global_argc;
  431. char **global_argv;
  432. #if !BB_MMU
  433. char *argv0_for_re_execing;
  434. #endif
  435. #if ENABLE_HUSH_LOOPS
  436. unsigned depth_break_continue;
  437. unsigned depth_of_loop;
  438. #endif
  439. const char *ifs;
  440. const char *cwd;
  441. struct variable *top_var; /* = &G.shell_ver (set in main()) */
  442. struct variable shell_ver;
  443. #if ENABLE_HUSH_FUNCTIONS
  444. struct function *top_func;
  445. #endif
  446. /* Signal and trap handling */
  447. // unsigned count_SIGCHLD;
  448. // unsigned handled_SIGCHLD;
  449. /* which signals have non-DFL handler (even with no traps set)? */
  450. unsigned non_DFL_mask;
  451. char **traps; /* char *traps[NSIG] */
  452. sigset_t blocked_set;
  453. sigset_t inherited_set;
  454. #if HUSH_DEBUG
  455. unsigned long memleak_value;
  456. int debug_indent;
  457. #endif
  458. char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
  459. };
  460. #define G (*ptr_to_globals)
  461. /* Not #defining name to G.name - this quickly gets unwieldy
  462. * (too many defines). Also, I actually prefer to see when a variable
  463. * is global, thus "G." prefix is a useful hint */
  464. #define INIT_G() do { \
  465. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  466. } while (0)
  467. /* Function prototypes for builtins */
  468. static int builtin_cd(char **argv);
  469. static int builtin_echo(char **argv);
  470. static int builtin_eval(char **argv);
  471. static int builtin_exec(char **argv);
  472. static int builtin_exit(char **argv);
  473. static int builtin_export(char **argv);
  474. #if ENABLE_HUSH_JOB
  475. static int builtin_fg_bg(char **argv);
  476. static int builtin_jobs(char **argv);
  477. #endif
  478. #if ENABLE_HUSH_HELP
  479. static int builtin_help(char **argv);
  480. #endif
  481. #if HUSH_DEBUG
  482. static int builtin_memleak(char **argv);
  483. #endif
  484. static int builtin_pwd(char **argv);
  485. static int builtin_read(char **argv);
  486. static int builtin_set(char **argv);
  487. static int builtin_shift(char **argv);
  488. static int builtin_source(char **argv);
  489. static int builtin_test(char **argv);
  490. static int builtin_trap(char **argv);
  491. static int builtin_true(char **argv);
  492. static int builtin_umask(char **argv);
  493. static int builtin_unset(char **argv);
  494. static int builtin_wait(char **argv);
  495. #if ENABLE_HUSH_LOOPS
  496. static int builtin_break(char **argv);
  497. static int builtin_continue(char **argv);
  498. #endif
  499. #if ENABLE_HUSH_FUNCTIONS
  500. static int builtin_return(char **argv);
  501. #endif
  502. /* Table of built-in functions. They can be forked or not, depending on
  503. * context: within pipes, they fork. As simple commands, they do not.
  504. * When used in non-forking context, they can change global variables
  505. * in the parent shell process. If forked, of course they cannot.
  506. * For example, 'unset foo | whatever' will parse and run, but foo will
  507. * still be set at the end. */
  508. struct built_in_command {
  509. const char *cmd;
  510. int (*function)(char **argv);
  511. #if ENABLE_HUSH_HELP
  512. const char *descr;
  513. #define BLTIN(cmd, func, help) { cmd, func, help }
  514. #else
  515. #define BLTIN(cmd, func, help) { cmd, func }
  516. #endif
  517. };
  518. /* For now, echo and test are unconditionally enabled.
  519. * Maybe make it configurable? */
  520. static const struct built_in_command bltins[] = {
  521. BLTIN("." , builtin_source , "Run commands in a file"),
  522. BLTIN(":" , builtin_true , "No-op"),
  523. BLTIN("[" , builtin_test , "Test condition"),
  524. #if ENABLE_HUSH_JOB
  525. BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
  526. #endif
  527. #if ENABLE_HUSH_LOOPS
  528. BLTIN("break" , builtin_break , "Exit from a loop"),
  529. #endif
  530. BLTIN("cd" , builtin_cd , "Change directory"),
  531. #if ENABLE_HUSH_LOOPS
  532. BLTIN("continue", builtin_continue, "Start new loop iteration"),
  533. #endif
  534. BLTIN("echo" , builtin_echo , "Write to stdout"),
  535. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  536. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  537. BLTIN("exit" , builtin_exit , "Exit"),
  538. BLTIN("export" , builtin_export , "Set environment variable"),
  539. #if ENABLE_HUSH_JOB
  540. BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
  541. #endif
  542. #if ENABLE_HUSH_HELP
  543. BLTIN("help" , builtin_help , "List shell built-in commands"),
  544. #endif
  545. #if ENABLE_HUSH_JOB
  546. BLTIN("jobs" , builtin_jobs , "List active jobs"),
  547. #endif
  548. #if HUSH_DEBUG
  549. BLTIN("memleak" , builtin_memleak , "Debug tool"),
  550. #endif
  551. BLTIN("pwd" , builtin_pwd , "Print current directory"),
  552. BLTIN("read" , builtin_read , "Input environment variable"),
  553. #if ENABLE_HUSH_FUNCTIONS
  554. BLTIN("return" , builtin_return , "Return from a function"),
  555. #endif
  556. BLTIN("set" , builtin_set , "Set/unset shell local variables"),
  557. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  558. BLTIN("test" , builtin_test , "Test condition"),
  559. BLTIN("trap" , builtin_trap , "Trap signals"),
  560. // BLTIN("ulimit" , builtin_return , "Control resource limits"),
  561. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  562. BLTIN("unset" , builtin_unset , "Unset environment variable"),
  563. BLTIN("wait" , builtin_wait , "Wait for process"),
  564. };
  565. /* Debug printouts.
  566. */
  567. #if HUSH_DEBUG
  568. /* prevent disasters with G.debug_indent < 0 */
  569. # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
  570. # define debug_enter() (G.debug_indent++)
  571. # define debug_leave() (G.debug_indent--)
  572. #else
  573. # define indent() ((void)0)
  574. # define debug_enter() ((void)0)
  575. # define debug_leave() ((void)0)
  576. #endif
  577. #ifndef debug_printf
  578. # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
  579. #endif
  580. #ifndef debug_printf_parse
  581. # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
  582. #endif
  583. #ifndef debug_printf_exec
  584. #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
  585. #endif
  586. #ifndef debug_printf_env
  587. # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
  588. #endif
  589. #ifndef debug_printf_jobs
  590. # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
  591. # define DEBUG_JOBS 1
  592. #else
  593. # define DEBUG_JOBS 0
  594. #endif
  595. #ifndef debug_printf_expand
  596. # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
  597. # define DEBUG_EXPAND 1
  598. #else
  599. # define DEBUG_EXPAND 0
  600. #endif
  601. #ifndef debug_printf_glob
  602. # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
  603. # define DEBUG_GLOB 1
  604. #else
  605. # define DEBUG_GLOB 0
  606. #endif
  607. #ifndef debug_printf_list
  608. # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
  609. #endif
  610. #ifndef debug_printf_subst
  611. # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
  612. #endif
  613. #ifndef debug_printf_clean
  614. # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
  615. # define DEBUG_CLEAN 1
  616. #else
  617. # define DEBUG_CLEAN 0
  618. #endif
  619. #if DEBUG_EXPAND
  620. static void debug_print_strings(const char *prefix, char **vv)
  621. {
  622. indent();
  623. fprintf(stderr, "%s:\n", prefix);
  624. while (*vv)
  625. fprintf(stderr, " '%s'\n", *vv++);
  626. }
  627. #else
  628. #define debug_print_strings(prefix, vv) ((void)0)
  629. #endif
  630. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  631. */
  632. #if LEAK_HUNTING
  633. static void *xxmalloc(int lineno, size_t size)
  634. {
  635. void *ptr = xmalloc((size + 0xff) & ~0xff);
  636. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  637. return ptr;
  638. }
  639. static void *xxrealloc(int lineno, void *ptr, size_t size)
  640. {
  641. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  642. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  643. return ptr;
  644. }
  645. static char *xxstrdup(int lineno, const char *str)
  646. {
  647. char *ptr = xstrdup(str);
  648. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  649. return ptr;
  650. }
  651. static void xxfree(void *ptr)
  652. {
  653. fdprintf(2, "free %p\n", ptr);
  654. free(ptr);
  655. }
  656. #define xmalloc(s) xxmalloc(__LINE__, s)
  657. #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  658. #define xstrdup(s) xxstrdup(__LINE__, s)
  659. #define free(p) xxfree(p)
  660. #endif
  661. /* Syntax and runtime errors. They always abort scripts.
  662. * In interactive use they usually discard unparsed and/or unexecuted commands
  663. * and return to the prompt.
  664. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  665. */
  666. #if HUSH_DEBUG < 2
  667. # define die_if_script(lineno, fmt...) die_if_script(fmt)
  668. # define syntax_error(lineno, msg) syntax_error(msg)
  669. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  670. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  671. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  672. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  673. #endif
  674. static void die_if_script(unsigned lineno, const char *fmt, ...)
  675. {
  676. va_list p;
  677. #if HUSH_DEBUG >= 2
  678. bb_error_msg("hush.c:%u", lineno);
  679. #endif
  680. va_start(p, fmt);
  681. bb_verror_msg(fmt, p, NULL);
  682. va_end(p);
  683. if (!G_interactive_fd)
  684. xfunc_die();
  685. }
  686. static void syntax_error(unsigned lineno, const char *msg)
  687. {
  688. if (msg)
  689. die_if_script(lineno, "syntax error: %s", msg);
  690. else
  691. die_if_script(lineno, "syntax error", NULL);
  692. }
  693. static void syntax_error_at(unsigned lineno, const char *msg)
  694. {
  695. die_if_script(lineno, "syntax error at '%s'", msg);
  696. }
  697. /* It so happens that all such cases are totally fatal
  698. * even if shell is interactive: EOF while looking for closing
  699. * delimiter. There is nowhere to read stuff from after that,
  700. * it's EOF! The only choice is to terminate.
  701. */
  702. static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
  703. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  704. {
  705. char msg[2];
  706. msg[0] = ch;
  707. msg[1] = '\0';
  708. die_if_script(lineno, "syntax error: unterminated %s", msg);
  709. xfunc_die();
  710. }
  711. static void syntax_error_unterm_str(unsigned lineno, const char *s)
  712. {
  713. die_if_script(lineno, "syntax error: unterminated %s", s);
  714. }
  715. static void syntax_error_unexpected_ch(unsigned lineno, char ch)
  716. {
  717. char msg[2];
  718. msg[0] = ch;
  719. msg[1] = '\0';
  720. die_if_script(lineno, "syntax error: unexpected %s", msg);
  721. }
  722. #if HUSH_DEBUG < 2
  723. # undef die_if_script
  724. # undef syntax_error
  725. # undef syntax_error_at
  726. # undef syntax_error_unterm_ch
  727. # undef syntax_error_unterm_str
  728. # undef syntax_error_unexpected_ch
  729. #else
  730. # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
  731. # define syntax_error(msg) syntax_error(__LINE__, msg)
  732. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  733. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  734. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  735. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  736. #endif
  737. /* Utility functions
  738. */
  739. static int glob_needed(const char *s)
  740. {
  741. while (*s) {
  742. if (*s == '\\')
  743. s++;
  744. if (*s == '*' || *s == '[' || *s == '?')
  745. return 1;
  746. s++;
  747. }
  748. return 0;
  749. }
  750. static int is_well_formed_var_name(const char *s, char terminator)
  751. {
  752. if (!s || !(isalpha(*s) || *s == '_'))
  753. return 0;
  754. s++;
  755. while (isalnum(*s) || *s == '_')
  756. s++;
  757. return *s == terminator;
  758. }
  759. /* Replace each \x with x in place, return ptr past NUL. */
  760. static char *unbackslash(char *src)
  761. {
  762. char *dst = src;
  763. while (1) {
  764. if (*src == '\\')
  765. src++;
  766. if ((*dst++ = *src++) == '\0')
  767. break;
  768. }
  769. return dst;
  770. }
  771. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  772. {
  773. int i;
  774. unsigned count1;
  775. unsigned count2;
  776. char **v;
  777. v = strings;
  778. count1 = 0;
  779. if (v) {
  780. while (*v) {
  781. count1++;
  782. v++;
  783. }
  784. }
  785. count2 = 0;
  786. v = add;
  787. while (*v) {
  788. count2++;
  789. v++;
  790. }
  791. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  792. v[count1 + count2] = NULL;
  793. i = count2;
  794. while (--i >= 0)
  795. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  796. return v;
  797. }
  798. #if LEAK_HUNTING
  799. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  800. {
  801. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  802. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  803. return ptr;
  804. }
  805. #define add_strings_to_strings(strings, add, need_to_dup) \
  806. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  807. #endif
  808. static char **add_string_to_strings(char **strings, char *add)
  809. {
  810. char *v[2];
  811. v[0] = add;
  812. v[1] = NULL;
  813. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  814. }
  815. #if LEAK_HUNTING
  816. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  817. {
  818. char **ptr = add_string_to_strings(strings, add);
  819. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  820. return ptr;
  821. }
  822. #define add_string_to_strings(strings, add) \
  823. xx_add_string_to_strings(__LINE__, strings, add)
  824. #endif
  825. static void putenv_all(char **strings)
  826. {
  827. if (!strings)
  828. return;
  829. while (*strings) {
  830. debug_printf_env("putenv '%s'\n", *strings);
  831. putenv(*strings++);
  832. }
  833. }
  834. static char **putenv_all_and_save_old(char **strings)
  835. {
  836. char **old = NULL;
  837. char **s = strings;
  838. if (!strings)
  839. return old;
  840. while (*strings) {
  841. char *v, *eq;
  842. eq = strchr(*strings, '=');
  843. if (eq) {
  844. *eq = '\0';
  845. v = getenv(*strings);
  846. *eq = '=';
  847. if (v) {
  848. /* v points to VAL in VAR=VAL, go back to VAR */
  849. v -= (eq - *strings) + 1;
  850. old = add_string_to_strings(old, v);
  851. }
  852. }
  853. strings++;
  854. }
  855. putenv_all(s);
  856. return old;
  857. }
  858. static void free_strings_and_unsetenv(char **strings, int unset)
  859. {
  860. char **v;
  861. if (!strings)
  862. return;
  863. v = strings;
  864. while (*v) {
  865. if (unset) {
  866. debug_printf_env("unsetenv '%s'\n", *v);
  867. bb_unsetenv(*v);
  868. }
  869. free(*v++);
  870. }
  871. free(strings);
  872. }
  873. static void free_strings(char **strings)
  874. {
  875. free_strings_and_unsetenv(strings, 0);
  876. }
  877. /* Helpers for setting new $n and restoring them back
  878. */
  879. typedef struct save_arg_t {
  880. char *sv_argv0;
  881. char **sv_g_argv;
  882. int sv_g_argc;
  883. smallint sv_g_malloced;
  884. } save_arg_t;
  885. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  886. {
  887. int n;
  888. sv->sv_argv0 = argv[0];
  889. sv->sv_g_argv = G.global_argv;
  890. sv->sv_g_argc = G.global_argc;
  891. sv->sv_g_malloced = G.global_args_malloced;
  892. argv[0] = G.global_argv[0]; /* retain $0 */
  893. G.global_argv = argv;
  894. G.global_args_malloced = 0;
  895. n = 1;
  896. while (*++argv)
  897. n++;
  898. G.global_argc = n;
  899. }
  900. static void restore_G_args(save_arg_t *sv, char **argv)
  901. {
  902. char **pp;
  903. if (G.global_args_malloced) {
  904. /* someone ran "set -- arg1 arg2 ...", undo */
  905. pp = G.global_argv;
  906. while (*++pp) /* note: does not free $0 */
  907. free(*pp);
  908. free(G.global_argv);
  909. }
  910. argv[0] = sv->sv_argv0;
  911. G.global_argv = sv->sv_g_argv;
  912. G.global_argc = sv->sv_g_argc;
  913. G.global_args_malloced = sv->sv_g_malloced;
  914. }
  915. /* Basic theory of signal handling in shell
  916. * ========================================
  917. * This does not describe what hush does, rather, it is current understanding
  918. * what it _should_ do. If it doesn't, it's a bug.
  919. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  920. *
  921. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  922. * is finished or backgrounded. It is the same in interactive and
  923. * non-interactive shells, and is the same regardless of whether
  924. * a user trap handler is installed or a shell special one is in effect.
  925. * ^C or ^Z from keyboard seem to execute "at once" because it usually
  926. * backgrounds (i.e. stops) or kills all members of currently running
  927. * pipe.
  928. *
  929. * Wait builtin in interruptible by signals for which user trap is set
  930. * or by SIGINT in interactive shell.
  931. *
  932. * Trap handlers will execute even within trap handlers. (right?)
  933. *
  934. * User trap handlers are forgotten when subshell ("(cmd)") is entered.
  935. *
  936. * If job control is off, backgrounded commands ("cmd &")
  937. * have SIGINT, SIGQUIT set to SIG_IGN.
  938. *
  939. * Commands run in command substitution ("`cmd`")
  940. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  941. *
  942. * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
  943. * by the shell from its parent.
  944. *
  945. * Siganls which differ from SIG_DFL action
  946. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  947. *
  948. * SIGQUIT: ignore
  949. * SIGTERM (interactive): ignore
  950. * SIGHUP (interactive):
  951. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  952. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  953. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  954. * that all pipe members are stopped. Try this in bash:
  955. * while :; do :; done - ^Z does not background it
  956. * (while :; do :; done) - ^Z backgrounds it
  957. * SIGINT (interactive): wait for last pipe, ignore the rest
  958. * of the command line, show prompt. NB: ^C does not send SIGINT
  959. * to interactive shell while shell is waiting for a pipe,
  960. * since shell is bg'ed (is not in foreground process group).
  961. * Example 1: this waits 5 sec, but does not execute ls:
  962. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  963. * Example 2: this does not wait and does not execute ls:
  964. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  965. * Example 3: this does not wait 5 sec, but executes ls:
  966. * "sleep 5; ls -l" + press ^C
  967. *
  968. * (What happens to signals which are IGN on shell start?)
  969. * (What happens with signal mask on shell start?)
  970. *
  971. * Implementation in hush
  972. * ======================
  973. * We use in-kernel pending signal mask to determine which signals were sent.
  974. * We block all signals which we don't want to take action immediately,
  975. * i.e. we block all signals which need to have special handling as described
  976. * above, and all signals which have traps set.
  977. * After each pipe execution, we extract any pending signals via sigtimedwait()
  978. * and act on them.
  979. *
  980. * unsigned non_DFL_mask: a mask of such "special" signals
  981. * sigset_t blocked_set: current blocked signal set
  982. *
  983. * "trap - SIGxxx":
  984. * clear bit in blocked_set unless it is also in non_DFL_mask
  985. * "trap 'cmd' SIGxxx":
  986. * set bit in blocked_set (even if 'cmd' is '')
  987. * after [v]fork, if we plan to be a shell:
  988. * unblock signals with special interactive handling
  989. * (child shell is not interactive),
  990. * unset all traps (note: regardless of child shell's type - {}, (), etc)
  991. * after [v]fork, if we plan to exec:
  992. * POSIX says pending signal mask is cleared in child - no need to clear it.
  993. * Restore blocked signal set to one inherited by shell just prior to exec.
  994. *
  995. * Note: as a result, we do not use signal handlers much. The only uses
  996. * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
  997. * and to restore tty pgrp on signal-induced exit.
  998. */
  999. enum {
  1000. SPECIAL_INTERACTIVE_SIGS = 0
  1001. #if ENABLE_HUSH_JOB
  1002. | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
  1003. | (1 << SIGHUP)
  1004. #endif
  1005. | (1 << SIGTERM)
  1006. | (1 << SIGINT)
  1007. };
  1008. //static void SIGCHLD_handler(int sig UNUSED_PARAM)
  1009. //{
  1010. // G.count_SIGCHLD++;
  1011. //}
  1012. #if ENABLE_HUSH_JOB
  1013. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1014. #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
  1015. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1016. #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
  1017. /* Restores tty foreground process group, and exits.
  1018. * May be called as signal handler for fatal signal
  1019. * (will resend signal to itself, producing correct exit state)
  1020. * or called directly with -EXITCODE.
  1021. * We also call it if xfunc is exiting. */
  1022. static void sigexit(int sig) NORETURN;
  1023. static void sigexit(int sig)
  1024. {
  1025. /* Disable all signals: job control, SIGPIPE, etc. */
  1026. sigprocmask_allsigs(SIG_BLOCK);
  1027. /* Careful: we can end up here after [v]fork. Do not restore
  1028. * tty pgrp then, only top-level shell process does that */
  1029. if (G_interactive_fd && getpid() == G.root_pid)
  1030. tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
  1031. /* Not a signal, just exit */
  1032. if (sig <= 0)
  1033. _exit(- sig);
  1034. kill_myself_with_sig(sig); /* does not return */
  1035. }
  1036. #else
  1037. #define disable_restore_tty_pgrp_on_exit() ((void)0)
  1038. #define enable_restore_tty_pgrp_on_exit() ((void)0)
  1039. #endif
  1040. /* Restores tty foreground process group, and exits. */
  1041. static void hush_exit(int exitcode) NORETURN;
  1042. static void hush_exit(int exitcode)
  1043. {
  1044. if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
  1045. /* Prevent recursion:
  1046. * trap "echo Hi; exit" EXIT; exit
  1047. */
  1048. char *argv[] = { NULL, G.traps[0], NULL };
  1049. G.traps[0] = NULL;
  1050. G.exiting = 1;
  1051. builtin_eval(argv);
  1052. free(argv[1]);
  1053. }
  1054. #if ENABLE_HUSH_JOB
  1055. fflush(NULL); /* flush all streams */
  1056. sigexit(- (exitcode & 0xff));
  1057. #else
  1058. exit(exitcode);
  1059. #endif
  1060. }
  1061. static int check_and_run_traps(int sig)
  1062. {
  1063. static const struct timespec zero_timespec = { 0, 0 };
  1064. smalluint save_rcode;
  1065. int last_sig = 0;
  1066. if (sig)
  1067. goto jump_in;
  1068. while (1) {
  1069. sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
  1070. if (sig <= 0)
  1071. break;
  1072. jump_in:
  1073. last_sig = sig;
  1074. if (G.traps && G.traps[sig]) {
  1075. if (G.traps[sig][0]) {
  1076. /* We have user-defined handler */
  1077. char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
  1078. save_rcode = G.last_exitcode;
  1079. builtin_eval(argv);
  1080. free(argv[1]);
  1081. G.last_exitcode = save_rcode;
  1082. } /* else: "" trap, ignoring signal */
  1083. continue;
  1084. }
  1085. /* not a trap: special action */
  1086. switch (sig) {
  1087. // case SIGCHLD:
  1088. // G.count_SIGCHLD++;
  1089. // break;
  1090. case SIGINT:
  1091. /* Builtin was ^C'ed, make it look prettier: */
  1092. bb_putchar('\n');
  1093. G.flag_SIGINT = 1;
  1094. break;
  1095. #if ENABLE_HUSH_JOB
  1096. case SIGHUP: {
  1097. struct pipe *job;
  1098. /* bash is observed to signal whole process groups,
  1099. * not individual processes */
  1100. for (job = G.job_list; job; job = job->next) {
  1101. if (job->pgrp <= 0)
  1102. continue;
  1103. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  1104. if (kill(- job->pgrp, SIGHUP) == 0)
  1105. kill(- job->pgrp, SIGCONT);
  1106. }
  1107. sigexit(SIGHUP);
  1108. }
  1109. #endif
  1110. default: /* ignored: */
  1111. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  1112. break;
  1113. }
  1114. }
  1115. return last_sig;
  1116. }
  1117. static const char *set_cwd(void)
  1118. {
  1119. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  1120. * we must not try to free(bb_msg_unknown) */
  1121. if (G.cwd == bb_msg_unknown)
  1122. G.cwd = NULL;
  1123. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  1124. if (!G.cwd)
  1125. G.cwd = bb_msg_unknown;
  1126. return G.cwd;
  1127. }
  1128. /* Get/check local shell variables */
  1129. static struct variable *get_local_var(const char *name)
  1130. {
  1131. struct variable *cur;
  1132. int len;
  1133. if (!name)
  1134. return NULL;
  1135. len = strlen(name);
  1136. for (cur = G.top_var; cur; cur = cur->next) {
  1137. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  1138. return cur;
  1139. }
  1140. return NULL;
  1141. }
  1142. static const char *get_local_var_value(const char *src)
  1143. {
  1144. struct variable *var = get_local_var(src);
  1145. if (var)
  1146. return strchr(var->varstr, '=') + 1;
  1147. return NULL;
  1148. }
  1149. /* str holds "NAME=VAL" and is expected to be malloced.
  1150. * We take ownership of it.
  1151. * flg_export:
  1152. * 0: do not change export flag
  1153. * (if creating new variable, flag will be 0)
  1154. * 1: set export flag and putenv the variable
  1155. * -1: clear export flag and unsetenv the variable
  1156. * flg_read_only is set only when we handle -R var=val
  1157. */
  1158. #if BB_MMU
  1159. #define set_local_var(str, flg_export, flg_read_only) \
  1160. set_local_var(str, flg_export)
  1161. #endif
  1162. static int set_local_var(char *str, int flg_export, int flg_read_only)
  1163. {
  1164. struct variable *cur;
  1165. char *eq_sign;
  1166. int name_len;
  1167. eq_sign = strchr(str, '=');
  1168. if (!eq_sign) { /* not expected to ever happen? */
  1169. free(str);
  1170. return -1;
  1171. }
  1172. name_len = eq_sign - str + 1; /* including '=' */
  1173. cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
  1174. while (1) {
  1175. if (strncmp(cur->varstr, str, name_len) != 0) {
  1176. if (!cur->next) {
  1177. /* Bail out. Note that now cur points
  1178. * to last var in linked list */
  1179. break;
  1180. }
  1181. cur = cur->next;
  1182. continue;
  1183. }
  1184. /* We found an existing var with this name */
  1185. if (cur->flg_read_only) {
  1186. #if !BB_MMU
  1187. if (!flg_read_only)
  1188. #endif
  1189. bb_error_msg("%s: readonly variable", str);
  1190. free(str);
  1191. return -1;
  1192. }
  1193. if (flg_export == -1) {
  1194. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  1195. *eq_sign = '\0';
  1196. unsetenv(str);
  1197. *eq_sign = '=';
  1198. }
  1199. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  1200. free_and_exp:
  1201. free(str);
  1202. goto exp;
  1203. }
  1204. if (cur->max_len >= strlen(str)) {
  1205. /* This one is from startup env, reuse space */
  1206. strcpy(cur->varstr, str);
  1207. goto free_and_exp;
  1208. }
  1209. /* max_len == 0 signifies "malloced" var, which we can
  1210. * (and has to) free */
  1211. if (!cur->max_len)
  1212. free(cur->varstr);
  1213. cur->max_len = 0;
  1214. goto set_str_and_exp;
  1215. }
  1216. /* Not found - create next variable struct */
  1217. cur->next = xzalloc(sizeof(*cur));
  1218. cur = cur->next;
  1219. set_str_and_exp:
  1220. cur->varstr = str;
  1221. #if !BB_MMU
  1222. cur->flg_read_only = flg_read_only;
  1223. #endif
  1224. exp:
  1225. if (flg_export == 1)
  1226. cur->flg_export = 1;
  1227. if (cur->flg_export) {
  1228. if (flg_export == -1) {
  1229. cur->flg_export = 0;
  1230. /* unsetenv was already done */
  1231. } else {
  1232. debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
  1233. return putenv(cur->varstr);
  1234. }
  1235. }
  1236. return 0;
  1237. }
  1238. static int unset_local_var(const char *name)
  1239. {
  1240. struct variable *cur;
  1241. struct variable *prev = prev; /* for gcc */
  1242. int name_len;
  1243. if (!name)
  1244. return EXIT_SUCCESS;
  1245. name_len = strlen(name);
  1246. cur = G.top_var;
  1247. while (cur) {
  1248. if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
  1249. if (cur->flg_read_only) {
  1250. bb_error_msg("%s: readonly variable", name);
  1251. return EXIT_FAILURE;
  1252. }
  1253. /* prev is ok to use here because 1st variable, HUSH_VERSION,
  1254. * is ro, and we cannot reach this code on the 1st pass */
  1255. prev->next = cur->next;
  1256. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  1257. bb_unsetenv(cur->varstr);
  1258. if (!cur->max_len)
  1259. free(cur->varstr);
  1260. free(cur);
  1261. return EXIT_SUCCESS;
  1262. }
  1263. prev = cur;
  1264. cur = cur->next;
  1265. }
  1266. return EXIT_SUCCESS;
  1267. }
  1268. #if ENABLE_SH_MATH_SUPPORT
  1269. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1270. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1271. static char *endofname(const char *name)
  1272. {
  1273. char *p;
  1274. p = (char *) name;
  1275. if (!is_name(*p))
  1276. return p;
  1277. while (*++p) {
  1278. if (!is_in_name(*p))
  1279. break;
  1280. }
  1281. return p;
  1282. }
  1283. static void arith_set_local_var(const char *name, const char *val, int flags)
  1284. {
  1285. /* arith code doesnt malloc space, so do it for it */
  1286. char *var = xasprintf("%s=%s", name, val);
  1287. set_local_var(var, flags, 0);
  1288. }
  1289. #endif
  1290. /*
  1291. * in_str support
  1292. */
  1293. static int static_get(struct in_str *i)
  1294. {
  1295. int ch = *i->p++;
  1296. if (ch != '\0')
  1297. return ch;
  1298. i->p--;
  1299. return EOF;
  1300. }
  1301. static int static_peek(struct in_str *i)
  1302. {
  1303. return *i->p;
  1304. }
  1305. #if ENABLE_HUSH_INTERACTIVE
  1306. static void cmdedit_set_initial_prompt(void)
  1307. {
  1308. if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1309. G.PS1 = getenv("PS1");
  1310. if (G.PS1 == NULL)
  1311. G.PS1 = "\\w \\$ ";
  1312. } else
  1313. G.PS1 = NULL;
  1314. }
  1315. static const char* setup_prompt_string(int promptmode)
  1316. {
  1317. const char *prompt_str;
  1318. debug_printf("setup_prompt_string %d ", promptmode);
  1319. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1320. /* Set up the prompt */
  1321. if (promptmode == 0) { /* PS1 */
  1322. free((char*)G.PS1);
  1323. G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
  1324. prompt_str = G.PS1;
  1325. } else
  1326. prompt_str = G.PS2;
  1327. } else
  1328. prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
  1329. debug_printf("result '%s'\n", prompt_str);
  1330. return prompt_str;
  1331. }
  1332. static void get_user_input(struct in_str *i)
  1333. {
  1334. int r;
  1335. const char *prompt_str;
  1336. prompt_str = setup_prompt_string(i->promptmode);
  1337. #if ENABLE_FEATURE_EDITING
  1338. /* Enable command line editing only while a command line
  1339. * is actually being read */
  1340. do {
  1341. G.flag_SIGINT = 0;
  1342. /* buglet: SIGINT will not make new prompt to appear _at once_,
  1343. * only after <Enter>. (^C will work) */
  1344. r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
  1345. /* catch *SIGINT* etc (^C is handled by read_line_input) */
  1346. check_and_run_traps(0);
  1347. } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
  1348. i->eof_flag = (r < 0);
  1349. if (i->eof_flag) { /* EOF/error detected */
  1350. G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
  1351. G.user_input_buf[1] = '\0';
  1352. }
  1353. #else
  1354. do {
  1355. G.flag_SIGINT = 0;
  1356. fputs(prompt_str, stdout);
  1357. fflush(stdout);
  1358. G.user_input_buf[0] = r = fgetc(i->file);
  1359. /*G.user_input_buf[1] = '\0'; - already is and never changed */
  1360. //do we need check_and_run_traps(0)? (maybe only if stdin)
  1361. } while (G.flag_SIGINT);
  1362. i->eof_flag = (r == EOF);
  1363. #endif
  1364. i->p = G.user_input_buf;
  1365. }
  1366. #endif /* INTERACTIVE */
  1367. /* This is the magic location that prints prompts
  1368. * and gets data back from the user */
  1369. static int file_get(struct in_str *i)
  1370. {
  1371. int ch;
  1372. /* If there is data waiting, eat it up */
  1373. if (i->p && *i->p) {
  1374. #if ENABLE_HUSH_INTERACTIVE
  1375. take_cached:
  1376. #endif
  1377. ch = *i->p++;
  1378. if (i->eof_flag && !*i->p)
  1379. ch = EOF;
  1380. /* note: ch is never NUL */
  1381. } else {
  1382. /* need to double check i->file because we might be doing something
  1383. * more complicated by now, like sourcing or substituting. */
  1384. #if ENABLE_HUSH_INTERACTIVE
  1385. if (G_interactive_fd && i->promptme && i->file == stdin) {
  1386. do {
  1387. get_user_input(i);
  1388. } while (!*i->p); /* need non-empty line */
  1389. i->promptmode = 1; /* PS2 */
  1390. i->promptme = 0;
  1391. goto take_cached;
  1392. }
  1393. #endif
  1394. do ch = fgetc(i->file); while (ch == '\0');
  1395. }
  1396. debug_printf("file_get: got '%c' %d\n", ch, ch);
  1397. #if ENABLE_HUSH_INTERACTIVE
  1398. if (ch == '\n')
  1399. i->promptme = 1;
  1400. #endif
  1401. return ch;
  1402. }
  1403. /* All callers guarantee this routine will never
  1404. * be used right after a newline, so prompting is not needed.
  1405. */
  1406. static int file_peek(struct in_str *i)
  1407. {
  1408. int ch;
  1409. if (i->p && *i->p) {
  1410. if (i->eof_flag && !i->p[1])
  1411. return EOF;
  1412. return *i->p;
  1413. /* note: ch is never NUL */
  1414. }
  1415. do ch = fgetc(i->file); while (ch == '\0');
  1416. i->eof_flag = (ch == EOF);
  1417. i->peek_buf[0] = ch;
  1418. i->peek_buf[1] = '\0';
  1419. i->p = i->peek_buf;
  1420. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  1421. return ch;
  1422. }
  1423. static void setup_file_in_str(struct in_str *i, FILE *f)
  1424. {
  1425. i->peek = file_peek;
  1426. i->get = file_get;
  1427. #if ENABLE_HUSH_INTERACTIVE
  1428. i->promptme = 1;
  1429. i->promptmode = 0; /* PS1 */
  1430. #endif
  1431. i->file = f;
  1432. i->p = NULL;
  1433. }
  1434. static void setup_string_in_str(struct in_str *i, const char *s)
  1435. {
  1436. i->peek = static_peek;
  1437. i->get = static_get;
  1438. #if ENABLE_HUSH_INTERACTIVE
  1439. i->promptme = 1;
  1440. i->promptmode = 0; /* PS1 */
  1441. #endif
  1442. i->p = s;
  1443. i->eof_flag = 0;
  1444. }
  1445. /*
  1446. * o_string support
  1447. */
  1448. #define B_CHUNK (32 * sizeof(char*))
  1449. static void o_reset_to_empty_unquoted(o_string *o)
  1450. {
  1451. o->length = 0;
  1452. o->o_quoted = 0;
  1453. if (o->data)
  1454. o->data[0] = '\0';
  1455. }
  1456. static void o_free(o_string *o)
  1457. {
  1458. free(o->data);
  1459. memset(o, 0, sizeof(*o));
  1460. }
  1461. static ALWAYS_INLINE void o_free_unsafe(o_string *o)
  1462. {
  1463. free(o->data);
  1464. }
  1465. static void o_grow_by(o_string *o, int len)
  1466. {
  1467. if (o->length + len > o->maxlen) {
  1468. o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
  1469. o->data = xrealloc(o->data, 1 + o->maxlen);
  1470. }
  1471. }
  1472. static void o_addchr(o_string *o, int ch)
  1473. {
  1474. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  1475. o_grow_by(o, 1);
  1476. o->data[o->length] = ch;
  1477. o->length++;
  1478. o->data[o->length] = '\0';
  1479. }
  1480. static void o_addblock(o_string *o, const char *str, int len)
  1481. {
  1482. o_grow_by(o, len);
  1483. memcpy(&o->data[o->length], str, len);
  1484. o->length += len;
  1485. o->data[o->length] = '\0';
  1486. }
  1487. #if !BB_MMU
  1488. static void o_addstr(o_string *o, const char *str)
  1489. {
  1490. o_addblock(o, str, strlen(str));
  1491. }
  1492. static void nommu_addchr(o_string *o, int ch)
  1493. {
  1494. if (o)
  1495. o_addchr(o, ch);
  1496. }
  1497. #else
  1498. #define nommu_addchr(o, str) ((void)0)
  1499. #endif
  1500. static void o_addstr_with_NUL(o_string *o, const char *str)
  1501. {
  1502. o_addblock(o, str, strlen(str) + 1);
  1503. }
  1504. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  1505. {
  1506. while (len) {
  1507. o_addchr(o, *str);
  1508. if (*str++ == '\\'
  1509. && (*str != '*' && *str != '?' && *str != '[')
  1510. ) {
  1511. o_addchr(o, '\\');
  1512. }
  1513. len--;
  1514. }
  1515. }
  1516. /* My analysis of quoting semantics tells me that state information
  1517. * is associated with a destination, not a source.
  1518. */
  1519. static void o_addqchr(o_string *o, int ch)
  1520. {
  1521. int sz = 1;
  1522. char *found = strchr("*?[\\", ch);
  1523. if (found)
  1524. sz++;
  1525. o_grow_by(o, sz);
  1526. if (found) {
  1527. o->data[o->length] = '\\';
  1528. o->length++;
  1529. }
  1530. o->data[o->length] = ch;
  1531. o->length++;
  1532. o->data[o->length] = '\0';
  1533. }
  1534. static void o_addQchr(o_string *o, int ch)
  1535. {
  1536. int sz = 1;
  1537. if (o->o_escape && strchr("*?[\\", ch)) {
  1538. sz++;
  1539. o->data[o->length] = '\\';
  1540. o->length++;
  1541. }
  1542. o_grow_by(o, sz);
  1543. o->data[o->length] = ch;
  1544. o->length++;
  1545. o->data[o->length] = '\0';
  1546. }
  1547. static void o_addQstr(o_string *o, const char *str, int len)
  1548. {
  1549. if (!o->o_escape) {
  1550. o_addblock(o, str, len);
  1551. return;
  1552. }
  1553. while (len) {
  1554. char ch;
  1555. int sz;
  1556. int ordinary_cnt = strcspn(str, "*?[\\");
  1557. if (ordinary_cnt > len) /* paranoia */
  1558. ordinary_cnt = len;
  1559. o_addblock(o, str, ordinary_cnt);
  1560. if (ordinary_cnt == len)
  1561. return;
  1562. str += ordinary_cnt;
  1563. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  1564. ch = *str++;
  1565. sz = 1;
  1566. if (ch) { /* it is necessarily one of "*?[\\" */
  1567. sz++;
  1568. o->data[o->length] = '\\';
  1569. o->length++;
  1570. }
  1571. o_grow_by(o, sz);
  1572. o->data[o->length] = ch;
  1573. o->length++;
  1574. o->data[o->length] = '\0';
  1575. }
  1576. }
  1577. /* A special kind of o_string for $VAR and `cmd` expansion.
  1578. * It contains char* list[] at the beginning, which is grown in 16 element
  1579. * increments. Actual string data starts at the next multiple of 16 * (char*).
  1580. * list[i] contains an INDEX (int!) into this string data.
  1581. * It means that if list[] needs to grow, data needs to be moved higher up
  1582. * but list[i]'s need not be modified.
  1583. * NB: remembering how many list[i]'s you have there is crucial.
  1584. * o_finalize_list() operation post-processes this structure - calculates
  1585. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  1586. */
  1587. #if DEBUG_EXPAND || DEBUG_GLOB
  1588. static void debug_print_list(const char *prefix, o_string *o, int n)
  1589. {
  1590. char **list = (char**)o->data;
  1591. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1592. int i = 0;
  1593. indent();
  1594. fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
  1595. prefix, list, n, string_start, o->length, o->maxlen);
  1596. while (i < n) {
  1597. indent();
  1598. fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
  1599. o->data + (int)list[i] + string_start,
  1600. o->data + (int)list[i] + string_start);
  1601. i++;
  1602. }
  1603. if (n) {
  1604. const char *p = o->data + (int)list[n - 1] + string_start;
  1605. indent();
  1606. fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  1607. }
  1608. }
  1609. #else
  1610. #define debug_print_list(prefix, o, n) ((void)0)
  1611. #endif
  1612. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  1613. * in list[n] so that it points past last stored byte so far.
  1614. * It returns n+1. */
  1615. static int o_save_ptr_helper(o_string *o, int n)
  1616. {
  1617. char **list = (char**)o->data;
  1618. int string_start;
  1619. int string_len;
  1620. if (!o->has_empty_slot) {
  1621. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1622. string_len = o->length - string_start;
  1623. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  1624. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  1625. /* list[n] points to string_start, make space for 16 more pointers */
  1626. o->maxlen += 0x10 * sizeof(list[0]);
  1627. o->data = xrealloc(o->data, o->maxlen + 1);
  1628. list = (char**)o->data;
  1629. memmove(list + n + 0x10, list + n, string_len);
  1630. o->length += 0x10 * sizeof(list[0]);
  1631. } else {
  1632. debug_printf_list("list[%d]=%d string_start=%d\n",
  1633. n, string_len, string_start);
  1634. }
  1635. } else {
  1636. /* We have empty slot at list[n], reuse without growth */
  1637. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  1638. string_len = o->length - string_start;
  1639. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  1640. n, string_len, string_start);
  1641. o->has_empty_slot = 0;
  1642. }
  1643. list[n] = (char*)(ptrdiff_t)string_len;
  1644. return n + 1;
  1645. }
  1646. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  1647. static int o_get_last_ptr(o_string *o, int n)
  1648. {
  1649. char **list = (char**)o->data;
  1650. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1651. return ((int)(ptrdiff_t)list[n-1]) + string_start;
  1652. }
  1653. /* o_glob performs globbing on last list[], saving each result
  1654. * as a new list[]. */
  1655. static int o_glob(o_string *o, int n)
  1656. {
  1657. glob_t globdata;
  1658. int gr;
  1659. char *pattern;
  1660. debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
  1661. if (!o->data)
  1662. return o_save_ptr_helper(o, n);
  1663. pattern = o->data + o_get_last_ptr(o, n);
  1664. debug_printf_glob("glob pattern '%s'\n", pattern);
  1665. if (!glob_needed(pattern)) {
  1666. literal:
  1667. o->length = unbackslash(pattern) - o->data;
  1668. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  1669. return o_save_ptr_helper(o, n);
  1670. }
  1671. memset(&globdata, 0, sizeof(globdata));
  1672. gr = glob(pattern, 0, NULL, &globdata);
  1673. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  1674. if (gr == GLOB_NOSPACE)
  1675. bb_error_msg_and_die("out of memory during glob");
  1676. if (gr == GLOB_NOMATCH) {
  1677. globfree(&globdata);
  1678. goto literal;
  1679. }
  1680. if (gr != 0) { /* GLOB_ABORTED ? */
  1681. /* TODO: testcase for bad glob pattern behavior */
  1682. bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
  1683. }
  1684. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  1685. char **argv = globdata.gl_pathv;
  1686. o->length = pattern - o->data; /* "forget" pattern */
  1687. while (1) {
  1688. o_addstr_with_NUL(o, *argv);
  1689. n = o_save_ptr_helper(o, n);
  1690. argv++;
  1691. if (!*argv)
  1692. break;
  1693. }
  1694. }
  1695. globfree(&globdata);
  1696. if (DEBUG_GLOB)
  1697. debug_print_list("o_glob returning", o, n);
  1698. return n;
  1699. }
  1700. /* If o->o_glob == 1, glob the string so far remembered.
  1701. * Otherwise, just finish current list[] and start new */
  1702. static int o_save_ptr(o_string *o, int n)
  1703. {
  1704. if (o->o_glob) { /* if globbing is requested */
  1705. /* If o->has_empty_slot, list[n] was already globbed
  1706. * (if it was requested back then when it was filled)
  1707. * so don't do that again! */
  1708. if (!o->has_empty_slot)
  1709. return o_glob(o, n); /* o_save_ptr_helper is inside */
  1710. }
  1711. return o_save_ptr_helper(o, n);
  1712. }
  1713. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  1714. static char **o_finalize_list(o_string *o, int n)
  1715. {
  1716. char **list;
  1717. int string_start;
  1718. n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
  1719. if (DEBUG_EXPAND)
  1720. debug_print_list("finalized", o, n);
  1721. debug_printf_expand("finalized n:%d\n", n);
  1722. list = (char**)o->data;
  1723. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1724. list[--n] = NULL;
  1725. while (n) {
  1726. n--;
  1727. list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
  1728. }
  1729. return list;
  1730. }
  1731. /* Expansion can recurse */
  1732. #if ENABLE_HUSH_TICK
  1733. static int process_command_subs(o_string *dest, const char *s);
  1734. #endif
  1735. static char *expand_string_to_string(const char *str);
  1736. #if BB_MMU
  1737. #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
  1738. parse_stream_dquoted(dest, input, dquote_end)
  1739. #endif
  1740. static int parse_stream_dquoted(o_string *as_string,
  1741. o_string *dest,
  1742. struct in_str *input,
  1743. int dquote_end);
  1744. /* expand_strvec_to_strvec() takes a list of strings, expands
  1745. * all variable references within and returns a pointer to
  1746. * a list of expanded strings, possibly with larger number
  1747. * of strings. (Think VAR="a b"; echo $VAR).
  1748. * This new list is allocated as a single malloc block.
  1749. * NULL-terminated list of char* pointers is at the beginning of it,
  1750. * followed by strings themself.
  1751. * Caller can deallocate entire list by single free(list). */
  1752. /* Store given string, finalizing the word and starting new one whenever
  1753. * we encounter IFS char(s). This is used for expanding variable values.
  1754. * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
  1755. static int expand_on_ifs(o_string *output, int n, const char *str)
  1756. {
  1757. while (1) {
  1758. int word_len = strcspn(str, G.ifs);
  1759. if (word_len) {
  1760. if (output->o_escape || !output->o_glob)
  1761. o_addQstr(output, str, word_len);
  1762. else /* protect backslashes against globbing up :) */
  1763. o_addblock_duplicate_backslash(output, str, word_len);
  1764. str += word_len;
  1765. }
  1766. if (!*str) /* EOL - do not finalize word */
  1767. break;
  1768. o_addchr(output, '\0');
  1769. debug_print_list("expand_on_ifs", output, n);
  1770. n = o_save_ptr(output, n);
  1771. str += strspn(str, G.ifs); /* skip ifs chars */
  1772. }
  1773. debug_print_list("expand_on_ifs[1]", output, n);
  1774. return n;
  1775. }
  1776. /* Helper to expand $((...)) and heredoc body. These act as if
  1777. * they are in double quotes, with the exception that they are not :).
  1778. * Just the rules are similar: "expand only $var and `cmd`"
  1779. *
  1780. * Returns malloced string.
  1781. * As an optimization, we return NULL if expansion is not needed.
  1782. */
  1783. static char *expand_pseudo_dquoted(const char *str)
  1784. {
  1785. char *exp_str;
  1786. struct in_str input;
  1787. o_string dest = NULL_O_STRING;
  1788. if (strchr(str, '$') == NULL
  1789. #if ENABLE_HUSH_TICK
  1790. && strchr(str, '`') == NULL
  1791. #endif
  1792. ) {
  1793. return NULL;
  1794. }
  1795. /* We need to expand. Example:
  1796. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  1797. */
  1798. setup_string_in_str(&input, str);
  1799. parse_stream_dquoted(NULL, &dest, &input, EOF);
  1800. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  1801. exp_str = expand_string_to_string(dest.data);
  1802. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  1803. o_free_unsafe(&dest);
  1804. return exp_str;
  1805. }
  1806. /* Expand all variable references in given string, adding words to list[]
  1807. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  1808. * to be filled). This routine is extremely tricky: has to deal with
  1809. * variables/parameters with whitespace, $* and $@, and constructs like
  1810. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  1811. static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
  1812. {
  1813. /* or_mask is either 0 (normal case) or 0x80
  1814. * (expansion of right-hand side of assignment == 1-element expand.
  1815. * It will also do no globbing, and thus we must not backslash-quote!) */
  1816. char first_ch, ored_ch;
  1817. int i;
  1818. const char *val;
  1819. char *dyn_val, *p;
  1820. dyn_val = NULL;
  1821. ored_ch = 0;
  1822. debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
  1823. debug_print_list("expand_vars_to_list", output, n);
  1824. n = o_save_ptr(output, n);
  1825. debug_print_list("expand_vars_to_list[0]", output, n);
  1826. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  1827. #if ENABLE_HUSH_TICK
  1828. o_string subst_result = NULL_O_STRING;
  1829. #endif
  1830. #if ENABLE_SH_MATH_SUPPORT
  1831. char arith_buf[sizeof(arith_t)*3 + 2];
  1832. #endif
  1833. o_addblock(output, arg, p - arg);
  1834. debug_print_list("expand_vars_to_list[1]", output, n);
  1835. arg = ++p;
  1836. p = strchr(p, SPECIAL_VAR_SYMBOL);
  1837. first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
  1838. /* "$@" is special. Even if quoted, it can still
  1839. * expand to nothing (not even an empty string) */
  1840. if ((first_ch & 0x7f) != '@')
  1841. ored_ch |= first_ch;
  1842. val = NULL;
  1843. switch (first_ch & 0x7f) {
  1844. /* Highest bit in first_ch indicates that var is double-quoted */
  1845. case '$': /* pid */
  1846. val = utoa(G.root_pid);
  1847. break;
  1848. case '!': /* bg pid */
  1849. val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
  1850. break;
  1851. case '?': /* exitcode */
  1852. val = utoa(G.last_exitcode);
  1853. break;
  1854. case '#': /* argc */
  1855. if (arg[1] != SPECIAL_VAR_SYMBOL)
  1856. /* actually, it's a ${#var} */
  1857. goto case_default;
  1858. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  1859. break;
  1860. case '*':
  1861. case '@':
  1862. i = 1;
  1863. if (!G.global_argv[i])
  1864. break;
  1865. ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  1866. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  1867. smallint sv = output->o_escape;
  1868. /* unquoted var's contents should be globbed, so don't escape */
  1869. output->o_escape = 0;
  1870. while (G.global_argv[i]) {
  1871. n = expand_on_ifs(output, n, G.global_argv[i]);
  1872. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  1873. if (G.global_argv[i++][0] && G.global_argv[i]) {
  1874. /* this argv[] is not empty and not last:
  1875. * put terminating NUL, start new word */
  1876. o_addchr(output, '\0');
  1877. debug_print_list("expand_vars_to_list[2]", output, n);
  1878. n = o_save_ptr(output, n);
  1879. debug_print_list("expand_vars_to_list[3]", output, n);
  1880. }
  1881. }
  1882. output->o_escape = sv;
  1883. } else
  1884. /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
  1885. * and in this case should treat it like '$*' - see 'else...' below */
  1886. if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
  1887. while (1) {
  1888. o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
  1889. if (++i >= G.global_argc)
  1890. break;
  1891. o_addchr(output, '\0');
  1892. debug_print_list("expand_vars_to_list[4]", output, n);
  1893. n = o_save_ptr(output, n);
  1894. }
  1895. } else { /* quoted $*: add as one word */
  1896. while (1) {
  1897. o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
  1898. if (!G.global_argv[++i])
  1899. break;
  1900. if (G.ifs[0])
  1901. o_addchr(output, G.ifs[0]);
  1902. }
  1903. }
  1904. break;
  1905. case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  1906. /* "Empty variable", used to make "" etc to not disappear */
  1907. arg++;
  1908. ored_ch = 0x80;
  1909. break;
  1910. #if ENABLE_HUSH_TICK
  1911. case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  1912. *p = '\0';
  1913. arg++;
  1914. /* Can't just stuff it into output o_string,
  1915. * expanded result may need to be globbed
  1916. * and $IFS-splitted */
  1917. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  1918. process_command_subs(&subst_result, arg);
  1919. debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
  1920. val = subst_result.data;
  1921. goto store_val;
  1922. #endif
  1923. #if ENABLE_SH_MATH_SUPPORT
  1924. case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
  1925. arith_eval_hooks_t hooks;
  1926. arith_t res;
  1927. int errcode;
  1928. char *exp_str;
  1929. arg++; /* skip '+' */
  1930. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  1931. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  1932. exp_str = expand_pseudo_dquoted(arg);
  1933. hooks.lookupvar = get_local_var_value;
  1934. hooks.setvar = arith_set_local_var;
  1935. hooks.endofname = endofname;
  1936. res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
  1937. free(exp_str);
  1938. if (errcode < 0) {
  1939. const char *msg = "error in arithmetic";
  1940. switch (errcode) {
  1941. case -3:
  1942. msg = "exponent less than 0";
  1943. break;
  1944. case -2:
  1945. msg = "divide by 0";
  1946. break;
  1947. case -5:
  1948. msg = "expression recursion loop detected";
  1949. break;
  1950. }
  1951. die_if_script(msg);
  1952. }
  1953. debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
  1954. sprintf(arith_buf, arith_t_fmt, res);
  1955. val = arith_buf;
  1956. break;
  1957. }
  1958. #endif
  1959. default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
  1960. case_default: {
  1961. bool exp_len = false;
  1962. bool exp_null = false;
  1963. char *var = arg;
  1964. char exp_save = exp_save; /* for compiler */
  1965. char exp_op = exp_op; /* for compiler */
  1966. char *exp_word = exp_word; /* for compiler */
  1967. size_t exp_off = 0;
  1968. *p = '\0';
  1969. arg[0] = first_ch & 0x7f;
  1970. /* prepare for expansions */
  1971. if (var[0] == '#') {
  1972. /* handle length expansion ${#var} */
  1973. exp_len = true;
  1974. ++var;
  1975. } else {
  1976. /* maybe handle parameter expansion */
  1977. exp_off = strcspn(var, ":-=+?%#");
  1978. if (!var[exp_off])
  1979. exp_off = 0;
  1980. if (exp_off) {
  1981. exp_save = var[exp_off];
  1982. exp_null = exp_save == ':';
  1983. exp_word = var + exp_off;
  1984. if (exp_null)
  1985. ++exp_word;
  1986. exp_op = *exp_word++;
  1987. var[exp_off] = '\0';
  1988. }
  1989. }
  1990. /* lookup the variable in question */
  1991. if (isdigit(var[0])) {
  1992. /* handle_dollar() should have vetted var for us */
  1993. i = xatoi_u(var);
  1994. if (i < G.global_argc)
  1995. val = G.global_argv[i];
  1996. /* else val remains NULL: $N with too big N */
  1997. } else
  1998. val = get_local_var_value(var);
  1999. /* handle any expansions */
  2000. if (exp_len) {
  2001. debug_printf_expand("expand: length of '%s' = ", val);
  2002. val = utoa(val ? strlen(val) : 0);
  2003. debug_printf_expand("%s\n", val);
  2004. } else if (exp_off) {
  2005. if (exp_op == '%' || exp_op == '#') {
  2006. if (val) {
  2007. /* we need to do a pattern match */
  2008. bool zero;
  2009. char *loc;
  2010. scan_t scan = pick_scan(exp_op, *exp_word, &zero);
  2011. if (exp_op == *exp_word) /* ## or %% */
  2012. ++exp_word;
  2013. val = dyn_val = xstrdup(val);
  2014. loc = scan(dyn_val, exp_word, zero);
  2015. if (zero)
  2016. val = loc;
  2017. else
  2018. *loc = '\0';
  2019. }
  2020. } else {
  2021. /* we need to do an expansion */
  2022. int exp_test = (!val || (exp_null && !val[0]));
  2023. if (exp_op == '+')
  2024. exp_test = !exp_test;
  2025. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  2026. exp_null ? "true" : "false", exp_test);
  2027. if (exp_test) {
  2028. if (exp_op == '?') {
  2029. //TODO: how interactive bash aborts expansion mid-command?
  2030. /* ${var?[error_msg_if_unset]} */
  2031. /* ${var:?[error_msg_if_unset_or_null]} */
  2032. /* mimic bash message */
  2033. die_if_script("%s: %s",
  2034. var,
  2035. exp_word[0] ? exp_word : "parameter null or not set"
  2036. );
  2037. } else {
  2038. val = exp_word;
  2039. }
  2040. if (exp_op == '=') {
  2041. /* ${var=[word]} or ${var:=[word]} */
  2042. if (isdigit(var[0]) || var[0] == '#') {
  2043. /* mimic bash message */
  2044. die_if_script("$%s: cannot assign in this way", var);
  2045. val = NULL;
  2046. } else {
  2047. char *new_var = xasprintf("%s=%s", var, val);
  2048. set_local_var(new_var, 0, 0);
  2049. }
  2050. }
  2051. }
  2052. }
  2053. var[exp_off] = exp_save;
  2054. }
  2055. arg[0] = first_ch;
  2056. #if ENABLE_HUSH_TICK
  2057. store_val:
  2058. #endif
  2059. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  2060. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
  2061. if (val) {
  2062. /* unquoted var's contents should be globbed, so don't escape */
  2063. smallint sv = output->o_escape;
  2064. output->o_escape = 0;
  2065. n = expand_on_ifs(output, n, val);
  2066. val = NULL;
  2067. output->o_escape = sv;
  2068. }
  2069. } else { /* quoted $VAR, val will be appended below */
  2070. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
  2071. }
  2072. } /* default: */
  2073. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  2074. if (val) {
  2075. o_addQstr(output, val, strlen(val));
  2076. }
  2077. free(dyn_val);
  2078. dyn_val = NULL;
  2079. /* Do the check to avoid writing to a const string */
  2080. if (*p != SPECIAL_VAR_SYMBOL)
  2081. *p = SPECIAL_VAR_SYMBOL;
  2082. #if ENABLE_HUSH_TICK
  2083. o_free(&subst_result);
  2084. #endif
  2085. arg = ++p;
  2086. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  2087. if (arg[0]) {
  2088. debug_print_list("expand_vars_to_list[a]", output, n);
  2089. /* this part is literal, and it was already pre-quoted
  2090. * if needed (much earlier), do not use o_addQstr here! */
  2091. o_addstr_with_NUL(output, arg);
  2092. debug_print_list("expand_vars_to_list[b]", output, n);
  2093. } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  2094. && !(ored_ch & 0x80) /* and all vars were not quoted. */
  2095. ) {
  2096. n--;
  2097. /* allow to reuse list[n] later without re-growth */
  2098. output->has_empty_slot = 1;
  2099. } else {
  2100. o_addchr(output, '\0');
  2101. }
  2102. return n;
  2103. }
  2104. static char **expand_variables(char **argv, int or_mask)
  2105. {
  2106. int n;
  2107. char **list;
  2108. char **v;
  2109. o_string output = NULL_O_STRING;
  2110. if (or_mask & 0x100) {
  2111. output.o_escape = 1; /* protect against globbing for "$var" */
  2112. /* (unquoted $var will temporarily switch it off) */
  2113. output.o_glob = 1;
  2114. }
  2115. n = 0;
  2116. v = argv;
  2117. while (*v) {
  2118. n = expand_vars_to_list(&output, n, *v, (char)or_mask);
  2119. v++;
  2120. }
  2121. debug_print_list("expand_variables", &output, n);
  2122. /* output.data (malloced in one block) gets returned in "list" */
  2123. list = o_finalize_list(&output, n);
  2124. debug_print_strings("expand_variables[1]", list);
  2125. return list;
  2126. }
  2127. static char **expand_strvec_to_strvec(char **argv)
  2128. {
  2129. return expand_variables(argv, 0x100);
  2130. }
  2131. /* Used for expansion of right hand of assignments */
  2132. /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
  2133. * "v=/bin/c*" */
  2134. static char *expand_string_to_string(const char *str)
  2135. {
  2136. char *argv[2], **list;
  2137. argv[0] = (char*)str;
  2138. argv[1] = NULL;
  2139. list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
  2140. if (HUSH_DEBUG)
  2141. if (!list[0] || list[1])
  2142. bb_error_msg_and_die("BUG in varexp2");
  2143. /* actually, just move string 2*sizeof(char*) bytes back */
  2144. overlapping_strcpy((char*)list, list[0]);
  2145. debug_printf_expand("string_to_string='%s'\n", (char*)list);
  2146. return (char*)list;
  2147. }
  2148. /* Used for "eval" builtin */
  2149. static char* expand_strvec_to_string(char **argv)
  2150. {
  2151. char **list;
  2152. list = expand_variables(argv, 0x80);
  2153. /* Convert all NULs to spaces */
  2154. if (list[0]) {
  2155. int n = 1;
  2156. while (list[n]) {
  2157. if (HUSH_DEBUG)
  2158. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  2159. bb_error_msg_and_die("BUG in varexp3");
  2160. /* bash uses ' ' regardless of $IFS contents */
  2161. list[n][-1] = ' ';
  2162. n++;
  2163. }
  2164. }
  2165. overlapping_strcpy((char*)list, list[0]);
  2166. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  2167. return (char*)list;
  2168. }
  2169. static char **expand_assignments(char **argv, int count)
  2170. {
  2171. int i;
  2172. char **p = NULL;
  2173. /* Expand assignments into one string each */
  2174. for (i = 0; i < count; i++) {
  2175. p = add_string_to_strings(p, expand_string_to_string(argv[i]));
  2176. }
  2177. return p;
  2178. }
  2179. #if BB_MMU
  2180. /* never called */
  2181. void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
  2182. static void reset_traps_to_defaults(void)
  2183. {
  2184. /* This function is always called in a child shell
  2185. * after fork (not vfork, NOMMU doesn't use this function).
  2186. * Child shells are not interactive.
  2187. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  2188. * Testcase: (while :; do :; done) + ^Z should background.
  2189. * Same goes for SIGTERM, SIGHUP, SIGINT.
  2190. */
  2191. unsigned sig;
  2192. unsigned mask;
  2193. if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
  2194. return;
  2195. /* Stupid. It can be done with *single* &= op, but we can't use
  2196. * the fact that G.blocked_set is implemented as a bitmask... */
  2197. mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
  2198. sig = 1;
  2199. while (1) {
  2200. if (mask & 1)
  2201. sigdelset(&G.blocked_set, sig);
  2202. mask >>= 1;
  2203. if (!mask)
  2204. break;
  2205. sig++;
  2206. }
  2207. G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  2208. mask = G.non_DFL_mask;
  2209. if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
  2210. if (!G.traps[sig])
  2211. continue;
  2212. free(G.traps[sig]);
  2213. G.traps[sig] = NULL;
  2214. /* There is no signal for 0 (EXIT) */
  2215. if (sig == 0)
  2216. continue;
  2217. /* There was a trap handler, we are removing it.
  2218. * But if sig still has non-DFL handling,
  2219. * we should not unblock it. */
  2220. if (mask & 1)
  2221. continue;
  2222. sigdelset(&G.blocked_set, sig);
  2223. }
  2224. sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
  2225. }
  2226. #else /* !BB_MMU */
  2227. static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
  2228. static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
  2229. {
  2230. char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
  2231. char *heredoc_argv[4];
  2232. struct variable *cur;
  2233. #if ENABLE_HUSH_FUNCTIONS
  2234. struct function *funcp;
  2235. #endif
  2236. char **argv, **pp;
  2237. unsigned cnt;
  2238. if (!g_argv0) { /* heredoc */
  2239. argv = heredoc_argv;
  2240. argv[0] = (char *) G.argv0_for_re_execing;
  2241. argv[1] = (char *) "-<";
  2242. argv[2] = (char *) s;
  2243. argv[3] = NULL;
  2244. pp = &argv[3]; /* used as pointer to empty environment */
  2245. goto do_exec;
  2246. }
  2247. sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
  2248. , (unsigned) G.root_pid
  2249. , (unsigned) G.last_bg_pid
  2250. , (unsigned) G.last_exitcode
  2251. IF_HUSH_LOOPS(, G.depth_of_loop)
  2252. );
  2253. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
  2254. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  2255. */
  2256. cnt = 6;
  2257. for (cur = G.top_var; cur; cur = cur->next) {
  2258. if (!cur->flg_export || cur->flg_read_only)
  2259. cnt += 2;
  2260. }
  2261. #if ENABLE_HUSH_FUNCTIONS
  2262. for (funcp = G.top_func; funcp; funcp = funcp->next)
  2263. cnt += 3;
  2264. #endif
  2265. pp = g_argv;
  2266. while (*pp++)
  2267. cnt++;
  2268. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  2269. *pp++ = (char *) G.argv0_for_re_execing;
  2270. *pp++ = param_buf;
  2271. for (cur = G.top_var; cur; cur = cur->next) {
  2272. if (cur->varstr == hush_version_str)
  2273. continue;
  2274. if (cur->flg_read_only) {
  2275. *pp++ = (char *) "-R";
  2276. *pp++ = cur->varstr;
  2277. } else if (!cur->flg_export) {
  2278. *pp++ = (char *) "-V";
  2279. *pp++ = cur->varstr;
  2280. }
  2281. }
  2282. #if ENABLE_HUSH_FUNCTIONS
  2283. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  2284. *pp++ = (char *) "-F";
  2285. *pp++ = funcp->name;
  2286. *pp++ = funcp->body_as_string;
  2287. }
  2288. #endif
  2289. /* We can pass activated traps here. Say, -Tnn:trap_string
  2290. *
  2291. * However, POSIX says that subshells reset signals with traps
  2292. * to SIG_DFL.
  2293. * I tested bash-3.2 and it not only does that with true subshells
  2294. * of the form ( list ), but with any forked children shells.
  2295. * I set trap "echo W" WINCH; and then tried:
  2296. *
  2297. * { echo 1; sleep 20; echo 2; } &
  2298. * while true; do echo 1; sleep 20; echo 2; break; done &
  2299. * true | { echo 1; sleep 20; echo 2; } | cat
  2300. *
  2301. * In all these cases sending SIGWINCH to the child shell
  2302. * did not run the trap. If I add trap "echo V" WINCH;
  2303. * _inside_ group (just before echo 1), it works.
  2304. *
  2305. * I conclude it means we don't need to pass active traps here.
  2306. * exec syscall below resets them to SIG_DFL for us.
  2307. */
  2308. *pp++ = (char *) "-c";
  2309. *pp++ = (char *) s;
  2310. *pp++ = g_argv0;
  2311. while (*g_argv)
  2312. *pp++ = *g_argv++;
  2313. /* *pp = NULL; - is already there */
  2314. pp = environ;
  2315. do_exec:
  2316. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  2317. sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
  2318. execve(bb_busybox_exec_path, argv, pp);
  2319. /* Fallback. Useful for init=/bin/hush usage etc */
  2320. if (argv[0][0] == '/')
  2321. execve(argv[0], argv, pp);
  2322. xfunc_error_retval = 127;
  2323. bb_error_msg_and_die("can't re-execute the shell");
  2324. }
  2325. #endif /* !BB_MMU */
  2326. static void setup_heredoc(struct redir_struct *redir)
  2327. {
  2328. struct fd_pair pair;
  2329. pid_t pid;
  2330. int len, written;
  2331. /* the _body_ of heredoc (misleading field name) */
  2332. const char *heredoc = redir->rd_filename;
  2333. char *expanded;
  2334. #if !BB_MMU
  2335. char **to_free;
  2336. #endif
  2337. expanded = NULL;
  2338. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  2339. expanded = expand_pseudo_dquoted(heredoc);
  2340. if (expanded)
  2341. heredoc = expanded;
  2342. }
  2343. len = strlen(heredoc);
  2344. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  2345. xpiped_pair(pair);
  2346. xmove_fd(pair.rd, redir->rd_fd);
  2347. /* Try writing without forking. Newer kernels have
  2348. * dynamically growing pipes. Must use non-blocking write! */
  2349. ndelay_on(pair.wr);
  2350. while (1) {
  2351. written = write(pair.wr, heredoc, len);
  2352. if (written <= 0)
  2353. break;
  2354. len -= written;
  2355. if (len == 0) {
  2356. close(pair.wr);
  2357. free(expanded);
  2358. return;
  2359. }
  2360. heredoc += written;
  2361. }
  2362. ndelay_off(pair.wr);
  2363. /* Okay, pipe buffer was not big enough */
  2364. /* Note: we must not create a stray child (bastard? :)
  2365. * for the unsuspecting parent process. Child creates a grandchild
  2366. * and exits before parent execs the process which consumes heredoc
  2367. * (that exec happens after we return from this function) */
  2368. #if !BB_MMU
  2369. to_free = NULL;
  2370. #endif
  2371. pid = vfork();
  2372. if (pid < 0)
  2373. bb_perror_msg_and_die("vfork");
  2374. if (pid == 0) {
  2375. /* child */
  2376. disable_restore_tty_pgrp_on_exit();
  2377. pid = BB_MMU ? fork() : vfork();
  2378. if (pid < 0)
  2379. bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
  2380. if (pid != 0)
  2381. _exit(0);
  2382. /* grandchild */
  2383. close(redir->rd_fd); /* read side of the pipe */
  2384. #if BB_MMU
  2385. full_write(pair.wr, heredoc, len); /* may loop or block */
  2386. _exit(0);
  2387. #else
  2388. /* Delegate blocking writes to another process */
  2389. xmove_fd(pair.wr, STDOUT_FILENO);
  2390. re_execute_shell(&to_free, heredoc, NULL, NULL);
  2391. #endif
  2392. }
  2393. /* parent */
  2394. enable_restore_tty_pgrp_on_exit();
  2395. #if !BB_MMU
  2396. free(to_free);
  2397. #endif
  2398. close(pair.wr);
  2399. free(expanded);
  2400. wait(NULL); /* wait till child has died */
  2401. }
  2402. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  2403. * and stderr if they are redirected. */
  2404. static int setup_redirects(struct command *prog, int squirrel[])
  2405. {
  2406. int openfd, mode;
  2407. struct redir_struct *redir;
  2408. for (redir = prog->redirects; redir; redir = redir->next) {
  2409. if (redir->rd_type == REDIRECT_HEREDOC2) {
  2410. /* rd_fd<<HERE case */
  2411. if (squirrel && redir->rd_fd < 3) {
  2412. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  2413. }
  2414. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  2415. * of the heredoc */
  2416. debug_printf_parse("set heredoc '%s'\n",
  2417. redir->rd_filename);
  2418. setup_heredoc(redir);
  2419. continue;
  2420. }
  2421. if (redir->rd_dup == REDIRFD_TO_FILE) {
  2422. /* rd_fd<*>file case (<*> is <,>,>>,<>) */
  2423. char *p;
  2424. if (redir->rd_filename == NULL) {
  2425. /* Something went wrong in the parse.
  2426. * Pretend it didn't happen */
  2427. bb_error_msg("bug in redirect parse");
  2428. continue;
  2429. }
  2430. mode = redir_table[redir->rd_type].mode;
  2431. p = expand_string_to_string(redir->rd_filename);
  2432. openfd = open_or_warn(p, mode);
  2433. free(p);
  2434. if (openfd < 0) {
  2435. /* this could get lost if stderr has been redirected, but
  2436. * bash and ash both lose it as well (though zsh doesn't!) */
  2437. //what the above comment tries to say?
  2438. return 1;
  2439. }
  2440. } else {
  2441. /* rd_fd<*>rd_dup or rd_fd<*>- cases */
  2442. openfd = redir->rd_dup;
  2443. }
  2444. if (openfd != redir->rd_fd) {
  2445. if (squirrel && redir->rd_fd < 3) {
  2446. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  2447. }
  2448. if (openfd == REDIRFD_CLOSE) {
  2449. /* "n>-" means "close me" */
  2450. close(redir->rd_fd);
  2451. } else {
  2452. xdup2(openfd, redir->rd_fd);
  2453. if (redir->rd_dup == REDIRFD_TO_FILE)
  2454. close(openfd);
  2455. }
  2456. }
  2457. }
  2458. return 0;
  2459. }
  2460. static void restore_redirects(int squirrel[])
  2461. {
  2462. int i, fd;
  2463. for (i = 0; i < 3; i++) {
  2464. fd = squirrel[i];
  2465. if (fd != -1) {
  2466. /* We simply die on error */
  2467. xmove_fd(fd, i);
  2468. }
  2469. }
  2470. }
  2471. static void free_pipe_list(struct pipe *head);
  2472. /* Return code is the exit status of the pipe */
  2473. static void free_pipe(struct pipe *pi)
  2474. {
  2475. char **p;
  2476. struct command *command;
  2477. struct redir_struct *r, *rnext;
  2478. int a, i;
  2479. if (pi->stopped_cmds > 0) /* why? */
  2480. return;
  2481. debug_printf_clean("run pipe: (pid %d)\n", getpid());
  2482. for (i = 0; i < pi->num_cmds; i++) {
  2483. command = &pi->cmds[i];
  2484. debug_printf_clean(" command %d:\n", i);
  2485. if (command->argv) {
  2486. for (a = 0, p = command->argv; *p; a++, p++) {
  2487. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  2488. }
  2489. free_strings(command->argv);
  2490. command->argv = NULL;
  2491. }
  2492. /* not "else if": on syntax error, we may have both! */
  2493. if (command->group) {
  2494. debug_printf_clean(" begin group (grp_type:%d)\n",
  2495. command->grp_type);
  2496. free_pipe_list(command->group);
  2497. debug_printf_clean(" end group\n");
  2498. command->group = NULL;
  2499. }
  2500. /* else is crucial here.
  2501. * If group != NULL, child_func is meaningless */
  2502. #if ENABLE_HUSH_FUNCTIONS
  2503. else if (command->child_func) {
  2504. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  2505. command->child_func->parent_cmd = NULL;
  2506. }
  2507. #endif
  2508. #if !BB_MMU
  2509. free(command->group_as_string);
  2510. command->group_as_string = NULL;
  2511. #endif
  2512. for (r = command->redirects; r; r = rnext) {
  2513. debug_printf_clean(" redirect %d%s",
  2514. r->rd_fd, redir_table[r->rd_type].descrip);
  2515. /* guard against the case >$FOO, where foo is unset or blank */
  2516. if (r->rd_filename) {
  2517. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  2518. free(r->rd_filename);
  2519. r->rd_filename = NULL;
  2520. }
  2521. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  2522. rnext = r->next;
  2523. free(r);
  2524. }
  2525. command->redirects = NULL;
  2526. }
  2527. free(pi->cmds); /* children are an array, they get freed all at once */
  2528. pi->cmds = NULL;
  2529. #if ENABLE_HUSH_JOB
  2530. free(pi->cmdtext);
  2531. pi->cmdtext = NULL;
  2532. #endif
  2533. }
  2534. static void free_pipe_list(struct pipe *head)
  2535. {
  2536. struct pipe *pi, *next;
  2537. for (pi = head; pi; pi = next) {
  2538. #if HAS_KEYWORDS
  2539. debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
  2540. #endif
  2541. free_pipe(pi);
  2542. debug_printf_clean("pipe followup code %d\n", pi->followup);
  2543. next = pi->next;
  2544. /*pi->next = NULL;*/
  2545. free(pi);
  2546. }
  2547. }
  2548. static int run_list(struct pipe *pi);
  2549. #if BB_MMU
  2550. #define parse_stream(pstring, input, end_trigger) \
  2551. parse_stream(input, end_trigger)
  2552. #endif
  2553. static struct pipe *parse_stream(char **pstring,
  2554. struct in_str *input,
  2555. int end_trigger);
  2556. static void parse_and_run_string(const char *s);
  2557. static const struct built_in_command* find_builtin(const char *name)
  2558. {
  2559. const struct built_in_command *x;
  2560. for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
  2561. if (strcmp(name, x->cmd) != 0)
  2562. continue;
  2563. debug_printf_exec("found builtin '%s'\n", name);
  2564. return x;
  2565. }
  2566. return NULL;
  2567. }
  2568. #if ENABLE_HUSH_FUNCTIONS
  2569. static const struct function *find_function(const char *name)
  2570. {
  2571. const struct function *funcp = G.top_func;
  2572. while (funcp) {
  2573. if (strcmp(name, funcp->name) == 0) {
  2574. break;
  2575. }
  2576. funcp = funcp->next;
  2577. }
  2578. if (funcp)
  2579. debug_printf_exec("found function '%s'\n", name);
  2580. return funcp;
  2581. }
  2582. /* Note: takes ownership on name ptr */
  2583. static struct function *new_function(char *name)
  2584. {
  2585. struct function *funcp;
  2586. struct function **funcpp = &G.top_func;
  2587. while ((funcp = *funcpp) != NULL) {
  2588. struct command *cmd;
  2589. if (strcmp(funcp->name, name) != 0) {
  2590. funcpp = &funcp->next;
  2591. continue;
  2592. }
  2593. cmd = funcp->parent_cmd;
  2594. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  2595. if (!cmd) {
  2596. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  2597. free(funcp->name);
  2598. /* Note: if !funcp->body, do not free body_as_string!
  2599. * This is a special case of "-F name body" function:
  2600. * body_as_string was not malloced! */
  2601. if (funcp->body) {
  2602. free_pipe_list(funcp->body);
  2603. #if !BB_MMU
  2604. free(funcp->body_as_string);
  2605. #endif
  2606. }
  2607. } else {
  2608. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  2609. cmd->argv[0] = funcp->name;
  2610. cmd->group = funcp->body;
  2611. #if !BB_MMU
  2612. cmd->group_as_string = funcp->body_as_string;
  2613. #endif
  2614. }
  2615. goto skip;
  2616. }
  2617. debug_printf_exec("remembering new function '%s'\n", name);
  2618. funcp = *funcpp = xzalloc(sizeof(*funcp));
  2619. /*funcp->next = NULL;*/
  2620. skip:
  2621. funcp->name = name;
  2622. return funcp;
  2623. }
  2624. static void unset_func(const char *name)
  2625. {
  2626. struct function *funcp;
  2627. struct function **funcpp = &G.top_func;
  2628. while ((funcp = *funcpp) != NULL) {
  2629. if (strcmp(funcp->name, name) == 0) {
  2630. *funcpp = funcp->next;
  2631. /* funcp is unlinked now, deleting it */
  2632. free(funcp->name);
  2633. /* Note: if !funcp->body, do not free body_as_string!
  2634. * This is a special case of "-F name body" function:
  2635. * body_as_string was not malloced! */
  2636. if (funcp->body) {
  2637. free_pipe_list(funcp->body);
  2638. #if !BB_MMU
  2639. free(funcp->body_as_string);
  2640. #endif
  2641. }
  2642. free(funcp);
  2643. break;
  2644. }
  2645. funcpp = &funcp->next;
  2646. }
  2647. }
  2648. #if BB_MMU
  2649. #define exec_function(nommu_save, funcp, argv) \
  2650. exec_function(funcp, argv)
  2651. #endif
  2652. static void exec_function(nommu_save_t *nommu_save,
  2653. const struct function *funcp,
  2654. char **argv) NORETURN;
  2655. static void exec_function(nommu_save_t *nommu_save,
  2656. const struct function *funcp,
  2657. char **argv)
  2658. {
  2659. # if BB_MMU
  2660. int n = 1;
  2661. argv[0] = G.global_argv[0];
  2662. G.global_argv = argv;
  2663. while (*++argv)
  2664. n++;
  2665. G.global_argc = n;
  2666. /* On MMU, funcp->body is always non-NULL */
  2667. n = run_list(funcp->body);
  2668. fflush(NULL);
  2669. _exit(n);
  2670. # else
  2671. re_execute_shell(&nommu_save->argv_from_re_execing,
  2672. funcp->body_as_string,
  2673. G.global_argv[0],
  2674. argv + 1);
  2675. # endif
  2676. }
  2677. static int run_function(const struct function *funcp, char **argv)
  2678. {
  2679. int rc;
  2680. save_arg_t sv;
  2681. #if ENABLE_HUSH_FUNCTIONS
  2682. smallint sv_flg;
  2683. #endif
  2684. save_and_replace_G_args(&sv, argv);
  2685. #if ENABLE_HUSH_FUNCTIONS
  2686. /* "we are in function, ok to use return" */
  2687. sv_flg = G.flag_return_in_progress;
  2688. G.flag_return_in_progress = -1;
  2689. #endif
  2690. /* On MMU, funcp->body is always non-NULL */
  2691. #if !BB_MMU
  2692. if (!funcp->body) {
  2693. /* Function defined by -F */
  2694. parse_and_run_string(funcp->body_as_string);
  2695. rc = G.last_exitcode;
  2696. } else
  2697. #endif
  2698. {
  2699. rc = run_list(funcp->body);
  2700. }
  2701. #if ENABLE_HUSH_FUNCTIONS
  2702. G.flag_return_in_progress = sv_flg;
  2703. #endif
  2704. restore_G_args(&sv, argv);
  2705. return rc;
  2706. }
  2707. #endif
  2708. #if BB_MMU
  2709. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  2710. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  2711. #define pseudo_exec(nommu_save, command, argv_expanded) \
  2712. pseudo_exec(command, argv_expanded)
  2713. #endif
  2714. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  2715. * Never returns.
  2716. * Don't exit() here. If you don't exec, use _exit instead.
  2717. * The at_exit handlers apparently confuse the calling process,
  2718. * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
  2719. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  2720. char **argv, int assignment_cnt,
  2721. char **argv_expanded) NORETURN;
  2722. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  2723. char **argv, int assignment_cnt,
  2724. char **argv_expanded)
  2725. {
  2726. char **new_env;
  2727. /* Case when we are here: ... | var=val | ... */
  2728. if (!argv[assignment_cnt])
  2729. _exit(EXIT_SUCCESS);
  2730. new_env = expand_assignments(argv, assignment_cnt);
  2731. #if BB_MMU
  2732. putenv_all(new_env);
  2733. free(new_env); /* optional */
  2734. #else
  2735. nommu_save->new_env = new_env;
  2736. nommu_save->old_env = putenv_all_and_save_old(new_env);
  2737. #endif
  2738. if (argv_expanded) {
  2739. argv = argv_expanded;
  2740. } else {
  2741. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  2742. #if !BB_MMU
  2743. nommu_save->argv = argv;
  2744. #endif
  2745. }
  2746. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  2747. if (strchr(argv[0], '/') != NULL)
  2748. goto skip;
  2749. #endif
  2750. /* On NOMMU, we must never block!
  2751. * Example: { sleep 99999 | read line } & echo Ok
  2752. * read builtin will block on read syscall, leaving parent blocked
  2753. * in vfork. Therefore we can't do this:
  2754. */
  2755. #if BB_MMU
  2756. /* Check if the command matches any of the builtins.
  2757. * Depending on context, this might be redundant. But it's
  2758. * easier to waste a few CPU cycles than it is to figure out
  2759. * if this is one of those cases.
  2760. */
  2761. {
  2762. int rcode;
  2763. const struct built_in_command *x = find_builtin(argv[0]);
  2764. if (x) {
  2765. rcode = x->function(argv);
  2766. fflush(NULL);
  2767. _exit(rcode);
  2768. }
  2769. }
  2770. #endif
  2771. #if ENABLE_HUSH_FUNCTIONS
  2772. /* Check if the command matches any functions */
  2773. {
  2774. const struct function *funcp = find_function(argv[0]);
  2775. if (funcp) {
  2776. exec_function(nommu_save, funcp, argv);
  2777. }
  2778. }
  2779. #endif
  2780. #if ENABLE_FEATURE_SH_STANDALONE
  2781. /* Check if the command matches any busybox applets */
  2782. {
  2783. int a = find_applet_by_name(argv[0]);
  2784. if (a >= 0) {
  2785. # if BB_MMU /* see above why on NOMMU it is not allowed */
  2786. if (APPLET_IS_NOEXEC(a)) {
  2787. debug_printf_exec("running applet '%s'\n", argv[0]);
  2788. run_applet_no_and_exit(a, argv);
  2789. }
  2790. # endif
  2791. /* Re-exec ourselves */
  2792. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  2793. sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
  2794. execv(bb_busybox_exec_path, argv);
  2795. /* If they called chroot or otherwise made the binary no longer
  2796. * executable, fall through */
  2797. }
  2798. }
  2799. #endif
  2800. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  2801. skip:
  2802. #endif
  2803. debug_printf_exec("execing '%s'\n", argv[0]);
  2804. sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
  2805. execvp(argv[0], argv);
  2806. bb_perror_msg("can't execute '%s'", argv[0]);
  2807. _exit(EXIT_FAILURE);
  2808. }
  2809. /* Called after [v]fork() in run_pipe
  2810. */
  2811. static void pseudo_exec(nommu_save_t *nommu_save,
  2812. struct command *command,
  2813. char **argv_expanded) NORETURN;
  2814. static void pseudo_exec(nommu_save_t *nommu_save,
  2815. struct command *command,
  2816. char **argv_expanded)
  2817. {
  2818. if (command->argv) {
  2819. pseudo_exec_argv(nommu_save, command->argv,
  2820. command->assignment_cnt, argv_expanded);
  2821. }
  2822. if (command->group) {
  2823. /* Cases when we are here:
  2824. * ( list )
  2825. * { list } &
  2826. * ... | ( list ) | ...
  2827. * ... | { list } | ...
  2828. */
  2829. #if BB_MMU
  2830. int rcode;
  2831. debug_printf_exec("pseudo_exec: run_list\n");
  2832. reset_traps_to_defaults();
  2833. rcode = run_list(command->group);
  2834. /* OK to leak memory by not calling free_pipe_list,
  2835. * since this process is about to exit */
  2836. _exit(rcode);
  2837. #else
  2838. re_execute_shell(&nommu_save->argv_from_re_execing,
  2839. command->group_as_string,
  2840. G.global_argv[0],
  2841. G.global_argv + 1);
  2842. #endif
  2843. }
  2844. /* Case when we are here: ... | >file */
  2845. debug_printf_exec("pseudo_exec'ed null command\n");
  2846. _exit(EXIT_SUCCESS);
  2847. }
  2848. #if ENABLE_HUSH_JOB
  2849. static const char *get_cmdtext(struct pipe *pi)
  2850. {
  2851. char **argv;
  2852. char *p;
  2853. int len;
  2854. /* This is subtle. ->cmdtext is created only on first backgrounding.
  2855. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  2856. * On subsequent bg argv is trashed, but we won't use it */
  2857. if (pi->cmdtext)
  2858. return pi->cmdtext;
  2859. argv = pi->cmds[0].argv;
  2860. if (!argv || !argv[0]) {
  2861. pi->cmdtext = xzalloc(1);
  2862. return pi->cmdtext;
  2863. }
  2864. len = 0;
  2865. do {
  2866. len += strlen(*argv) + 1;
  2867. } while (*++argv);
  2868. p = xmalloc(len);
  2869. pi->cmdtext = p;// = xmalloc(len);
  2870. argv = pi->cmds[0].argv;
  2871. do {
  2872. len = strlen(*argv);
  2873. memcpy(p, *argv, len);
  2874. p += len;
  2875. *p++ = ' ';
  2876. } while (*++argv);
  2877. p[-1] = '\0';
  2878. return pi->cmdtext;
  2879. }
  2880. static void insert_bg_job(struct pipe *pi)
  2881. {
  2882. struct pipe *job, **jobp;
  2883. int i;
  2884. /* Linear search for the ID of the job to use */
  2885. pi->jobid = 1;
  2886. for (job = G.job_list; job; job = job->next)
  2887. if (job->jobid >= pi->jobid)
  2888. pi->jobid = job->jobid + 1;
  2889. /* Add job to the list of running jobs */
  2890. jobp = &G.job_list;
  2891. while ((job = *jobp) != NULL)
  2892. jobp = &job->next;
  2893. job = *jobp = xmalloc(sizeof(*job));
  2894. *job = *pi; /* physical copy */
  2895. job->next = NULL;
  2896. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  2897. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  2898. for (i = 0; i < pi->num_cmds; i++) {
  2899. job->cmds[i].pid = pi->cmds[i].pid;
  2900. /* all other fields are not used and stay zero */
  2901. }
  2902. job->cmdtext = xstrdup(get_cmdtext(pi));
  2903. if (G_interactive_fd)
  2904. printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
  2905. /* Last command's pid goes to $! */
  2906. G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
  2907. G.last_jobid = job->jobid;
  2908. }
  2909. static void remove_bg_job(struct pipe *pi)
  2910. {
  2911. struct pipe *prev_pipe;
  2912. if (pi == G.job_list) {
  2913. G.job_list = pi->next;
  2914. } else {
  2915. prev_pipe = G.job_list;
  2916. while (prev_pipe->next != pi)
  2917. prev_pipe = prev_pipe->next;
  2918. prev_pipe->next = pi->next;
  2919. }
  2920. if (G.job_list)
  2921. G.last_jobid = G.job_list->jobid;
  2922. else
  2923. G.last_jobid = 0;
  2924. }
  2925. /* Remove a backgrounded job */
  2926. static void delete_finished_bg_job(struct pipe *pi)
  2927. {
  2928. remove_bg_job(pi);
  2929. pi->stopped_cmds = 0;
  2930. free_pipe(pi);
  2931. free(pi);
  2932. }
  2933. #endif /* JOB */
  2934. /* Check to see if any processes have exited -- if they
  2935. * have, figure out why and see if a job has completed */
  2936. static int checkjobs(struct pipe* fg_pipe)
  2937. {
  2938. int attributes;
  2939. int status;
  2940. #if ENABLE_HUSH_JOB
  2941. struct pipe *pi;
  2942. #endif
  2943. pid_t childpid;
  2944. int rcode = 0;
  2945. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  2946. errno = 0;
  2947. // if (G.handled_SIGCHLD == G.count_SIGCHLD)
  2948. // /* avoid doing syscall, nothing there anyway */
  2949. // return rcode;
  2950. attributes = WUNTRACED;
  2951. if (fg_pipe == NULL)
  2952. attributes |= WNOHANG;
  2953. /* Do we do this right?
  2954. * bash-3.00# sleep 20 | false
  2955. * <ctrl-Z pressed>
  2956. * [3]+ Stopped sleep 20 | false
  2957. * bash-3.00# echo $?
  2958. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  2959. * [hush 1.14.0: yes we do it right]
  2960. */
  2961. wait_more:
  2962. while (1) {
  2963. int i;
  2964. int dead;
  2965. // i = G.count_SIGCHLD;
  2966. childpid = waitpid(-1, &status, attributes);
  2967. if (childpid <= 0) {
  2968. if (childpid && errno != ECHILD)
  2969. bb_perror_msg("waitpid");
  2970. // else /* Until next SIGCHLD, waitpid's are useless */
  2971. // G.handled_SIGCHLD = i;
  2972. break;
  2973. }
  2974. dead = WIFEXITED(status) || WIFSIGNALED(status);
  2975. #if DEBUG_JOBS
  2976. if (WIFSTOPPED(status))
  2977. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  2978. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  2979. if (WIFSIGNALED(status))
  2980. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  2981. childpid, WTERMSIG(status), WEXITSTATUS(status));
  2982. if (WIFEXITED(status))
  2983. debug_printf_jobs("pid %d exited, exitcode %d\n",
  2984. childpid, WEXITSTATUS(status));
  2985. #endif
  2986. /* Were we asked to wait for fg pipe? */
  2987. if (fg_pipe) {
  2988. for (i = 0; i < fg_pipe->num_cmds; i++) {
  2989. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  2990. if (fg_pipe->cmds[i].pid != childpid)
  2991. continue;
  2992. if (dead) {
  2993. fg_pipe->cmds[i].pid = 0;
  2994. fg_pipe->alive_cmds--;
  2995. if (i == fg_pipe->num_cmds - 1) {
  2996. /* last process gives overall exitstatus */
  2997. /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
  2998. rcode = WEXITSTATUS(status);
  2999. IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
  3000. /* bash prints killing signal's name for *last*
  3001. * process in pipe (prints just newline for SIGINT).
  3002. * Mimic this. Example: "sleep 5" + ^\
  3003. */
  3004. if (WIFSIGNALED(status)) {
  3005. int sig = WTERMSIG(status);
  3006. printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
  3007. }
  3008. }
  3009. } else {
  3010. fg_pipe->cmds[i].is_stopped = 1;
  3011. fg_pipe->stopped_cmds++;
  3012. }
  3013. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  3014. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  3015. if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
  3016. /* All processes in fg pipe have exited or stopped */
  3017. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  3018. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  3019. * and "killall -STOP cat" */
  3020. if (G_interactive_fd) {
  3021. #if ENABLE_HUSH_JOB
  3022. if (fg_pipe->alive_cmds)
  3023. insert_bg_job(fg_pipe);
  3024. #endif
  3025. return rcode;
  3026. }
  3027. }
  3028. /* There are still running processes in the fg pipe */
  3029. goto wait_more; /* do waitpid again */
  3030. }
  3031. /* it wasnt fg_pipe, look for process in bg pipes */
  3032. }
  3033. #if ENABLE_HUSH_JOB
  3034. /* We asked to wait for bg or orphaned children */
  3035. /* No need to remember exitcode in this case */
  3036. for (pi = G.job_list; pi; pi = pi->next) {
  3037. for (i = 0; i < pi->num_cmds; i++) {
  3038. if (pi->cmds[i].pid == childpid)
  3039. goto found_pi_and_prognum;
  3040. }
  3041. }
  3042. /* Happens when shell is used as init process (init=/bin/sh) */
  3043. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  3044. continue; /* do waitpid again */
  3045. found_pi_and_prognum:
  3046. if (dead) {
  3047. /* child exited */
  3048. pi->cmds[i].pid = 0;
  3049. pi->alive_cmds--;
  3050. if (!pi->alive_cmds) {
  3051. if (G_interactive_fd)
  3052. printf(JOB_STATUS_FORMAT, pi->jobid,
  3053. "Done", pi->cmdtext);
  3054. delete_finished_bg_job(pi);
  3055. }
  3056. } else {
  3057. /* child stopped */
  3058. pi->cmds[i].is_stopped = 1;
  3059. pi->stopped_cmds++;
  3060. }
  3061. #endif
  3062. } /* while (waitpid succeeds)... */
  3063. return rcode;
  3064. }
  3065. #if ENABLE_HUSH_JOB
  3066. static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
  3067. {
  3068. pid_t p;
  3069. int rcode = checkjobs(fg_pipe);
  3070. /* Job finished, move the shell to the foreground */
  3071. p = getpgid(0); /* pgid of our process */
  3072. debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
  3073. tcsetpgrp(G_interactive_fd, p);
  3074. return rcode;
  3075. }
  3076. #endif
  3077. /* Start all the jobs, but don't wait for anything to finish.
  3078. * See checkjobs().
  3079. *
  3080. * Return code is normally -1, when the caller has to wait for children
  3081. * to finish to determine the exit status of the pipe. If the pipe
  3082. * is a simple builtin command, however, the action is done by the
  3083. * time run_pipe returns, and the exit code is provided as the
  3084. * return value.
  3085. *
  3086. * Returns -1 only if started some children. IOW: we have to
  3087. * mask out retvals of builtins etc with 0xff!
  3088. *
  3089. * The only case when we do not need to [v]fork is when the pipe
  3090. * is single, non-backgrounded, non-subshell command. Examples:
  3091. * cmd ; ... { list } ; ...
  3092. * cmd && ... { list } && ...
  3093. * cmd || ... { list } || ...
  3094. * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
  3095. * or (if SH_STANDALONE) an applet, and we can run the { list }
  3096. * with run_list. If it isn't one of these, we fork and exec cmd.
  3097. *
  3098. * Cases when we must fork:
  3099. * non-single: cmd | cmd
  3100. * backgrounded: cmd & { list } &
  3101. * subshell: ( list ) [&]
  3102. */
  3103. static int run_pipe(struct pipe *pi)
  3104. {
  3105. static const char *const null_ptr = NULL;
  3106. int i;
  3107. int nextin;
  3108. struct command *command;
  3109. char **argv_expanded;
  3110. char **argv;
  3111. char *p;
  3112. /* it is not always needed, but we aim to smaller code */
  3113. int squirrel[] = { -1, -1, -1 };
  3114. int rcode;
  3115. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  3116. debug_enter();
  3117. IF_HUSH_JOB(pi->pgrp = -1;)
  3118. pi->stopped_cmds = 0;
  3119. command = &(pi->cmds[0]);
  3120. argv_expanded = NULL;
  3121. if (pi->num_cmds != 1
  3122. || pi->followup == PIPE_BG
  3123. || command->grp_type == GRP_SUBSHELL
  3124. ) {
  3125. goto must_fork;
  3126. }
  3127. pi->alive_cmds = 1;
  3128. debug_printf_exec(": group:%p argv:'%s'\n",
  3129. command->group, command->argv ? command->argv[0] : "NONE");
  3130. if (command->group) {
  3131. #if ENABLE_HUSH_FUNCTIONS
  3132. if (command->grp_type == GRP_FUNCTION) {
  3133. /* "executing" func () { list } */
  3134. struct function *funcp;
  3135. funcp = new_function(command->argv[0]);
  3136. /* funcp->name is already set to argv[0] */
  3137. funcp->body = command->group;
  3138. #if !BB_MMU
  3139. funcp->body_as_string = command->group_as_string;
  3140. command->group_as_string = NULL;
  3141. #endif
  3142. command->group = NULL;
  3143. command->argv[0] = NULL;
  3144. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  3145. funcp->parent_cmd = command;
  3146. command->child_func = funcp;
  3147. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  3148. debug_leave();
  3149. return EXIT_SUCCESS;
  3150. }
  3151. #endif
  3152. /* { list } */
  3153. debug_printf("non-subshell group\n");
  3154. rcode = 1; /* exitcode if redir failed */
  3155. if (setup_redirects(command, squirrel) == 0) {
  3156. debug_printf_exec(": run_list\n");
  3157. rcode = run_list(command->group) & 0xff;
  3158. }
  3159. restore_redirects(squirrel);
  3160. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  3161. debug_leave();
  3162. debug_printf_exec("run_pipe: return %d\n", rcode);
  3163. return rcode;
  3164. }
  3165. argv = command->argv ? command->argv : (char **) &null_ptr;
  3166. {
  3167. const struct built_in_command *x;
  3168. #if ENABLE_HUSH_FUNCTIONS
  3169. const struct function *funcp;
  3170. #else
  3171. enum { funcp = 0 };
  3172. #endif
  3173. char **new_env = NULL;
  3174. char **old_env = NULL;
  3175. if (argv[command->assignment_cnt] == NULL) {
  3176. /* Assignments, but no command */
  3177. /* Ensure redirects take effect. Try "a=t >file" */
  3178. rcode = setup_redirects(command, squirrel);
  3179. restore_redirects(squirrel);
  3180. /* Set shell variables */
  3181. while (*argv) {
  3182. p = expand_string_to_string(*argv);
  3183. debug_printf_exec("set shell var:'%s'->'%s'\n",
  3184. *argv, p);
  3185. set_local_var(p, 0, 0);
  3186. argv++;
  3187. }
  3188. /* Do we need to flag set_local_var() errors?
  3189. * "assignment to readonly var" and "putenv error"
  3190. */
  3191. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  3192. debug_leave();
  3193. debug_printf_exec("run_pipe: return %d\n", rcode);
  3194. return rcode;
  3195. }
  3196. /* Expand the rest into (possibly) many strings each */
  3197. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  3198. x = find_builtin(argv_expanded[0]);
  3199. #if ENABLE_HUSH_FUNCTIONS
  3200. funcp = NULL;
  3201. if (!x)
  3202. funcp = find_function(argv_expanded[0]);
  3203. #endif
  3204. if (x || funcp) {
  3205. if (!funcp) {
  3206. if (x->function == builtin_exec && argv_expanded[1] == NULL) {
  3207. debug_printf("exec with redirects only\n");
  3208. rcode = setup_redirects(command, NULL);
  3209. goto clean_up_and_ret1;
  3210. }
  3211. }
  3212. /* setup_redirects acts on file descriptors, not FILEs.
  3213. * This is perfect for work that comes after exec().
  3214. * Is it really safe for inline use? Experimentally,
  3215. * things seem to work. */
  3216. rcode = setup_redirects(command, squirrel);
  3217. if (rcode == 0) {
  3218. new_env = expand_assignments(argv, command->assignment_cnt);
  3219. old_env = putenv_all_and_save_old(new_env);
  3220. if (!funcp) {
  3221. debug_printf_exec(": builtin '%s' '%s'...\n",
  3222. x->cmd, argv_expanded[1]);
  3223. rcode = x->function(argv_expanded) & 0xff;
  3224. fflush(NULL);
  3225. }
  3226. #if ENABLE_HUSH_FUNCTIONS
  3227. else {
  3228. debug_printf_exec(": function '%s' '%s'...\n",
  3229. funcp->name, argv_expanded[1]);
  3230. rcode = run_function(funcp, argv_expanded) & 0xff;
  3231. }
  3232. #endif
  3233. }
  3234. #if ENABLE_FEATURE_SH_STANDALONE
  3235. clean_up_and_ret:
  3236. #endif
  3237. restore_redirects(squirrel);
  3238. free_strings_and_unsetenv(new_env, 1);
  3239. putenv_all(old_env);
  3240. /* Free the pointers, but the strings themselves
  3241. * are in environ now, don't use free_strings! */
  3242. free(old_env);
  3243. clean_up_and_ret1:
  3244. free(argv_expanded);
  3245. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  3246. debug_leave();
  3247. debug_printf_exec("run_pipe return %d\n", rcode);
  3248. return rcode;
  3249. }
  3250. #if ENABLE_FEATURE_SH_STANDALONE
  3251. i = find_applet_by_name(argv_expanded[0]);
  3252. if (i >= 0 && APPLET_IS_NOFORK(i)) {
  3253. rcode = setup_redirects(command, squirrel);
  3254. if (rcode == 0) {
  3255. new_env = expand_assignments(argv, command->assignment_cnt);
  3256. old_env = putenv_all_and_save_old(new_env);
  3257. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  3258. argv_expanded[0], argv_expanded[1]);
  3259. rcode = run_nofork_applet(i, argv_expanded);
  3260. }
  3261. goto clean_up_and_ret;
  3262. }
  3263. #endif
  3264. /* It is neither builtin nor applet. We must fork. */
  3265. }
  3266. must_fork:
  3267. /* NB: argv_expanded may already be created, and that
  3268. * might include `cmd` runs! Do not rerun it! We *must*
  3269. * use argv_expanded if it's non-NULL */
  3270. /* Going to fork a child per each pipe member */
  3271. pi->alive_cmds = 0;
  3272. nextin = 0;
  3273. for (i = 0; i < pi->num_cmds; i++) {
  3274. struct fd_pair pipefds;
  3275. #if !BB_MMU
  3276. volatile nommu_save_t nommu_save;
  3277. nommu_save.new_env = NULL;
  3278. nommu_save.old_env = NULL;
  3279. nommu_save.argv = NULL;
  3280. nommu_save.argv_from_re_execing = NULL;
  3281. #endif
  3282. command = &(pi->cmds[i]);
  3283. if (command->argv) {
  3284. debug_printf_exec(": pipe member '%s' '%s'...\n",
  3285. command->argv[0], command->argv[1]);
  3286. } else {
  3287. debug_printf_exec(": pipe member with no argv\n");
  3288. }
  3289. /* pipes are inserted between pairs of commands */
  3290. pipefds.rd = 0;
  3291. pipefds.wr = 1;
  3292. if ((i + 1) < pi->num_cmds)
  3293. xpiped_pair(pipefds);
  3294. command->pid = BB_MMU ? fork() : vfork();
  3295. if (!command->pid) { /* child */
  3296. #if ENABLE_HUSH_JOB
  3297. disable_restore_tty_pgrp_on_exit();
  3298. /* Every child adds itself to new process group
  3299. * with pgid == pid_of_first_child_in_pipe */
  3300. if (G.run_list_level == 1 && G_interactive_fd) {
  3301. pid_t pgrp;
  3302. pgrp = pi->pgrp;
  3303. if (pgrp < 0) /* true for 1st process only */
  3304. pgrp = getpid();
  3305. if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
  3306. /* We do it in *every* child, not just first,
  3307. * to avoid races */
  3308. tcsetpgrp(G_interactive_fd, pgrp);
  3309. }
  3310. }
  3311. #endif
  3312. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  3313. /* 1st cmd in backgrounded pipe
  3314. * should have its stdin /dev/null'ed */
  3315. close(0);
  3316. if (open(bb_dev_null, O_RDONLY))
  3317. xopen("/", O_RDONLY);
  3318. } else {
  3319. xmove_fd(nextin, 0);
  3320. }
  3321. xmove_fd(pipefds.wr, 1);
  3322. if (pipefds.rd > 1)
  3323. close(pipefds.rd);
  3324. /* Like bash, explicit redirects override pipes,
  3325. * and the pipe fd is available for dup'ing. */
  3326. if (setup_redirects(command, NULL))
  3327. _exit(1);
  3328. /* Restore default handlers just prior to exec */
  3329. /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
  3330. /* Stores to nommu_save list of env vars putenv'ed
  3331. * (NOMMU, on MMU we don't need that) */
  3332. /* cast away volatility... */
  3333. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  3334. /* pseudo_exec() does not return */
  3335. }
  3336. /* parent or error */
  3337. enable_restore_tty_pgrp_on_exit();
  3338. #if !BB_MMU
  3339. /* Clean up after vforked child */
  3340. free(nommu_save.argv);
  3341. free(nommu_save.argv_from_re_execing);
  3342. free_strings_and_unsetenv(nommu_save.new_env, 1);
  3343. putenv_all(nommu_save.old_env);
  3344. /* Free the pointers, but the strings themselves
  3345. * are in environ now, don't use free_strings! */
  3346. free(nommu_save.old_env);
  3347. #endif
  3348. free(argv_expanded);
  3349. argv_expanded = NULL;
  3350. if (command->pid < 0) { /* [v]fork failed */
  3351. /* Clearly indicate, was it fork or vfork */
  3352. bb_perror_msg(BB_MMU ? "fork" : "vfork");
  3353. } else {
  3354. pi->alive_cmds++;
  3355. #if ENABLE_HUSH_JOB
  3356. /* Second and next children need to know pid of first one */
  3357. if (pi->pgrp < 0)
  3358. pi->pgrp = command->pid;
  3359. #endif
  3360. }
  3361. if (i)
  3362. close(nextin);
  3363. if ((i + 1) < pi->num_cmds)
  3364. close(pipefds.wr);
  3365. /* Pass read (output) pipe end to next iteration */
  3366. nextin = pipefds.rd;
  3367. }
  3368. if (!pi->alive_cmds) {
  3369. debug_leave();
  3370. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  3371. return 1;
  3372. }
  3373. debug_leave();
  3374. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  3375. return -1;
  3376. }
  3377. #ifndef debug_print_tree
  3378. static void debug_print_tree(struct pipe *pi, int lvl)
  3379. {
  3380. static const char *const PIPE[] = {
  3381. [PIPE_SEQ] = "SEQ",
  3382. [PIPE_AND] = "AND",
  3383. [PIPE_OR ] = "OR" ,
  3384. [PIPE_BG ] = "BG" ,
  3385. };
  3386. static const char *RES[] = {
  3387. [RES_NONE ] = "NONE" ,
  3388. #if ENABLE_HUSH_IF
  3389. [RES_IF ] = "IF" ,
  3390. [RES_THEN ] = "THEN" ,
  3391. [RES_ELIF ] = "ELIF" ,
  3392. [RES_ELSE ] = "ELSE" ,
  3393. [RES_FI ] = "FI" ,
  3394. #endif
  3395. #if ENABLE_HUSH_LOOPS
  3396. [RES_FOR ] = "FOR" ,
  3397. [RES_WHILE] = "WHILE",
  3398. [RES_UNTIL] = "UNTIL",
  3399. [RES_DO ] = "DO" ,
  3400. [RES_DONE ] = "DONE" ,
  3401. #endif
  3402. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3403. [RES_IN ] = "IN" ,
  3404. #endif
  3405. #if ENABLE_HUSH_CASE
  3406. [RES_CASE ] = "CASE" ,
  3407. [RES_MATCH] = "MATCH",
  3408. [RES_CASEI] = "CASEI",
  3409. [RES_ESAC ] = "ESAC" ,
  3410. #endif
  3411. [RES_XXXX ] = "XXXX" ,
  3412. [RES_SNTX ] = "SNTX" ,
  3413. };
  3414. static const char *const GRPTYPE[] = {
  3415. "{}",
  3416. "()",
  3417. #if ENABLE_HUSH_FUNCTIONS
  3418. "func()",
  3419. #endif
  3420. };
  3421. int pin, prn;
  3422. pin = 0;
  3423. while (pi) {
  3424. fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
  3425. pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
  3426. prn = 0;
  3427. while (prn < pi->num_cmds) {
  3428. struct command *command = &pi->cmds[prn];
  3429. char **argv = command->argv;
  3430. fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
  3431. lvl*2, "", prn,
  3432. command->assignment_cnt);
  3433. if (command->group) {
  3434. fprintf(stderr, " group %s: (argv=%p)\n",
  3435. GRPTYPE[command->grp_type],
  3436. argv);
  3437. debug_print_tree(command->group, lvl+1);
  3438. prn++;
  3439. continue;
  3440. }
  3441. if (argv) while (*argv) {
  3442. fprintf(stderr, " '%s'", *argv);
  3443. argv++;
  3444. }
  3445. fprintf(stderr, "\n");
  3446. prn++;
  3447. }
  3448. pi = pi->next;
  3449. pin++;
  3450. }
  3451. }
  3452. #endif
  3453. /* NB: called by pseudo_exec, and therefore must not modify any
  3454. * global data until exec/_exit (we can be a child after vfork!) */
  3455. static int run_list(struct pipe *pi)
  3456. {
  3457. #if ENABLE_HUSH_CASE
  3458. char *case_word = NULL;
  3459. #endif
  3460. #if ENABLE_HUSH_LOOPS
  3461. struct pipe *loop_top = NULL;
  3462. char *for_varname = NULL;
  3463. char **for_lcur = NULL;
  3464. char **for_list = NULL;
  3465. #endif
  3466. smallint last_followup;
  3467. smalluint rcode;
  3468. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  3469. smalluint cond_code = 0;
  3470. #else
  3471. enum { cond_code = 0 };
  3472. #endif
  3473. #if HAS_KEYWORDS
  3474. smallint rword; /* enum reserved_style */
  3475. smallint last_rword; /* ditto */
  3476. #endif
  3477. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  3478. debug_enter();
  3479. #if ENABLE_HUSH_LOOPS
  3480. /* Check syntax for "for" */
  3481. for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
  3482. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  3483. continue;
  3484. /* current word is FOR or IN (BOLD in comments below) */
  3485. if (cpipe->next == NULL) {
  3486. syntax_error("malformed for");
  3487. debug_leave();
  3488. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  3489. return 1;
  3490. }
  3491. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  3492. if (cpipe->next->res_word == RES_DO)
  3493. continue;
  3494. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  3495. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  3496. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  3497. ) {
  3498. syntax_error("malformed for");
  3499. debug_leave();
  3500. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  3501. return 1;
  3502. }
  3503. }
  3504. #endif
  3505. /* Past this point, all code paths should jump to ret: label
  3506. * in order to return, no direct "return" statements please.
  3507. * This helps to ensure that no memory is leaked. */
  3508. #if ENABLE_HUSH_JOB
  3509. G.run_list_level++;
  3510. #endif
  3511. #if HAS_KEYWORDS
  3512. rword = RES_NONE;
  3513. last_rword = RES_XXXX;
  3514. #endif
  3515. last_followup = PIPE_SEQ;
  3516. rcode = G.last_exitcode;
  3517. /* Go through list of pipes, (maybe) executing them. */
  3518. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  3519. if (G.flag_SIGINT)
  3520. break;
  3521. IF_HAS_KEYWORDS(rword = pi->res_word;)
  3522. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  3523. rword, cond_code, last_rword);
  3524. #if ENABLE_HUSH_LOOPS
  3525. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  3526. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  3527. ) {
  3528. /* start of a loop: remember where loop starts */
  3529. loop_top = pi;
  3530. G.depth_of_loop++;
  3531. }
  3532. #endif
  3533. /* Still in the same "if...", "then..." or "do..." branch? */
  3534. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  3535. if ((rcode == 0 && last_followup == PIPE_OR)
  3536. || (rcode != 0 && last_followup == PIPE_AND)
  3537. ) {
  3538. /* It is "<true> || CMD" or "<false> && CMD"
  3539. * and we should not execute CMD */
  3540. debug_printf_exec("skipped cmd because of || or &&\n");
  3541. last_followup = pi->followup;
  3542. continue;
  3543. }
  3544. }
  3545. last_followup = pi->followup;
  3546. IF_HAS_KEYWORDS(last_rword = rword;)
  3547. #if ENABLE_HUSH_IF
  3548. if (cond_code) {
  3549. if (rword == RES_THEN) {
  3550. /* if false; then ... fi has exitcode 0! */
  3551. G.last_exitcode = rcode = EXIT_SUCCESS;
  3552. /* "if <false> THEN cmd": skip cmd */
  3553. continue;
  3554. }
  3555. } else {
  3556. if (rword == RES_ELSE || rword == RES_ELIF) {
  3557. /* "if <true> then ... ELSE/ELIF cmd":
  3558. * skip cmd and all following ones */
  3559. break;
  3560. }
  3561. }
  3562. #endif
  3563. #if ENABLE_HUSH_LOOPS
  3564. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  3565. if (!for_lcur) {
  3566. /* first loop through for */
  3567. static const char encoded_dollar_at[] ALIGN1 = {
  3568. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  3569. }; /* encoded representation of "$@" */
  3570. static const char *const encoded_dollar_at_argv[] = {
  3571. encoded_dollar_at, NULL
  3572. }; /* argv list with one element: "$@" */
  3573. char **vals;
  3574. vals = (char**)encoded_dollar_at_argv;
  3575. if (pi->next->res_word == RES_IN) {
  3576. /* if no variable values after "in" we skip "for" */
  3577. if (!pi->next->cmds[0].argv) {
  3578. G.last_exitcode = rcode = EXIT_SUCCESS;
  3579. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  3580. break;
  3581. }
  3582. vals = pi->next->cmds[0].argv;
  3583. } /* else: "for var; do..." -> assume "$@" list */
  3584. /* create list of variable values */
  3585. debug_print_strings("for_list made from", vals);
  3586. for_list = expand_strvec_to_strvec(vals);
  3587. for_lcur = for_list;
  3588. debug_print_strings("for_list", for_list);
  3589. for_varname = pi->cmds[0].argv[0];
  3590. pi->cmds[0].argv[0] = NULL;
  3591. }
  3592. free(pi->cmds[0].argv[0]);
  3593. if (!*for_lcur) {
  3594. /* "for" loop is over, clean up */
  3595. free(for_list);
  3596. for_list = NULL;
  3597. for_lcur = NULL;
  3598. pi->cmds[0].argv[0] = for_varname;
  3599. break;
  3600. }
  3601. /* Insert next value from for_lcur */
  3602. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  3603. pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
  3604. pi->cmds[0].assignment_cnt = 1;
  3605. }
  3606. if (rword == RES_IN) {
  3607. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  3608. }
  3609. if (rword == RES_DONE) {
  3610. continue; /* "done" has no cmds too */
  3611. }
  3612. #endif
  3613. #if ENABLE_HUSH_CASE
  3614. if (rword == RES_CASE) {
  3615. case_word = expand_strvec_to_string(pi->cmds->argv);
  3616. continue;
  3617. }
  3618. if (rword == RES_MATCH) {
  3619. char **argv;
  3620. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  3621. break;
  3622. /* all prev words didn't match, does this one match? */
  3623. argv = pi->cmds->argv;
  3624. while (*argv) {
  3625. char *pattern = expand_string_to_string(*argv);
  3626. /* TODO: which FNM_xxx flags to use? */
  3627. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  3628. free(pattern);
  3629. if (cond_code == 0) { /* match! we will execute this branch */
  3630. free(case_word); /* make future "word)" stop */
  3631. case_word = NULL;
  3632. break;
  3633. }
  3634. argv++;
  3635. }
  3636. continue;
  3637. }
  3638. if (rword == RES_CASEI) { /* inside of a case branch */
  3639. if (cond_code != 0)
  3640. continue; /* not matched yet, skip this pipe */
  3641. }
  3642. #endif
  3643. /* Just pressing <enter> in shell should check for jobs.
  3644. * OTOH, in non-interactive shell this is useless
  3645. * and only leads to extra job checks */
  3646. if (pi->num_cmds == 0) {
  3647. if (G_interactive_fd)
  3648. goto check_jobs_and_continue;
  3649. continue;
  3650. }
  3651. /* After analyzing all keywords and conditions, we decided
  3652. * to execute this pipe. NB: have to do checkjobs(NULL)
  3653. * after run_pipe to collect any background children,
  3654. * even if list execution is to be stopped. */
  3655. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  3656. {
  3657. int r;
  3658. #if ENABLE_HUSH_LOOPS
  3659. G.flag_break_continue = 0;
  3660. #endif
  3661. rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
  3662. if (r != -1) {
  3663. /* We ran a builtin, function, or group.
  3664. * rcode is already known
  3665. * and we don't need to wait for anything. */
  3666. G.last_exitcode = rcode;
  3667. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  3668. check_and_run_traps(0);
  3669. #if ENABLE_HUSH_LOOPS
  3670. /* Was it "break" or "continue"? */
  3671. if (G.flag_break_continue) {
  3672. smallint fbc = G.flag_break_continue;
  3673. /* We might fall into outer *loop*,
  3674. * don't want to break it too */
  3675. if (loop_top) {
  3676. G.depth_break_continue--;
  3677. if (G.depth_break_continue == 0)
  3678. G.flag_break_continue = 0;
  3679. /* else: e.g. "continue 2" should *break* once, *then* continue */
  3680. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  3681. if (G.depth_break_continue != 0 || fbc == BC_BREAK)
  3682. goto check_jobs_and_break;
  3683. /* "continue": simulate end of loop */
  3684. rword = RES_DONE;
  3685. continue;
  3686. }
  3687. #endif
  3688. #if ENABLE_HUSH_FUNCTIONS
  3689. if (G.flag_return_in_progress == 1)
  3690. goto check_jobs_and_break;
  3691. #endif
  3692. } else if (pi->followup == PIPE_BG) {
  3693. /* What does bash do with attempts to background builtins? */
  3694. /* even bash 3.2 doesn't do that well with nested bg:
  3695. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  3696. * I'm NOT treating inner &'s as jobs */
  3697. check_and_run_traps(0);
  3698. #if ENABLE_HUSH_JOB
  3699. if (G.run_list_level == 1)
  3700. {
  3701. debug_printf_exec("insert_bg_job1\n");
  3702. insert_bg_job(pi);
  3703. debug_printf_exec("insert_bg_job2\n");
  3704. }
  3705. #endif
  3706. G.last_exitcode = rcode = EXIT_SUCCESS;
  3707. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  3708. } else {
  3709. #if ENABLE_HUSH_JOB
  3710. if (G.run_list_level == 1 && G_interactive_fd) {
  3711. /* Waits for completion, then fg's main shell */
  3712. rcode = checkjobs_and_fg_shell(pi);
  3713. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  3714. check_and_run_traps(0);
  3715. } else
  3716. #endif
  3717. { /* This one just waits for completion */
  3718. rcode = checkjobs(pi);
  3719. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  3720. check_and_run_traps(0);
  3721. }
  3722. G.last_exitcode = rcode;
  3723. }
  3724. }
  3725. /* Analyze how result affects subsequent commands */
  3726. #if ENABLE_HUSH_IF
  3727. if (rword == RES_IF || rword == RES_ELIF)
  3728. cond_code = rcode;
  3729. #endif
  3730. #if ENABLE_HUSH_LOOPS
  3731. /* Beware of "while false; true; do ..."! */
  3732. if (pi->next && pi->next->res_word == RES_DO) {
  3733. if (rword == RES_WHILE) {
  3734. if (rcode) {
  3735. /* "while false; do...done" - exitcode 0 */
  3736. G.last_exitcode = rcode = EXIT_SUCCESS;
  3737. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  3738. goto check_jobs_and_break;
  3739. }
  3740. }
  3741. if (rword == RES_UNTIL) {
  3742. if (!rcode) {
  3743. debug_printf_exec(": until expr is true: breaking\n");
  3744. check_jobs_and_break:
  3745. checkjobs(NULL);
  3746. break;
  3747. }
  3748. }
  3749. }
  3750. #endif
  3751. check_jobs_and_continue:
  3752. checkjobs(NULL);
  3753. } /* for (pi) */
  3754. #if ENABLE_HUSH_JOB
  3755. G.run_list_level--;
  3756. #endif
  3757. #if ENABLE_HUSH_LOOPS
  3758. if (loop_top)
  3759. G.depth_of_loop--;
  3760. free(for_list);
  3761. #endif
  3762. #if ENABLE_HUSH_CASE
  3763. free(case_word);
  3764. #endif
  3765. debug_leave();
  3766. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  3767. return rcode;
  3768. }
  3769. /* Select which version we will use */
  3770. static int run_and_free_list(struct pipe *pi)
  3771. {
  3772. int rcode = 0;
  3773. debug_printf_exec("run_and_free_list entered\n");
  3774. if (!G.fake_mode) {
  3775. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  3776. rcode = run_list(pi);
  3777. }
  3778. /* free_pipe_list has the side effect of clearing memory.
  3779. * In the long run that function can be merged with run_list,
  3780. * but doing that now would hobble the debugging effort. */
  3781. free_pipe_list(pi);
  3782. debug_printf_exec("run_and_free_list return %d\n", rcode);
  3783. return rcode;
  3784. }
  3785. static struct pipe *new_pipe(void)
  3786. {
  3787. struct pipe *pi;
  3788. pi = xzalloc(sizeof(struct pipe));
  3789. /*pi->followup = 0; - deliberately invalid value */
  3790. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3791. return pi;
  3792. }
  3793. /* Command (member of a pipe) is complete, or we start a new pipe
  3794. * if ctx->command is NULL.
  3795. * No errors possible here.
  3796. */
  3797. static int done_command(struct parse_context *ctx)
  3798. {
  3799. /* The command is really already in the pipe structure, so
  3800. * advance the pipe counter and make a new, null command. */
  3801. struct pipe *pi = ctx->pipe;
  3802. struct command *command = ctx->command;
  3803. if (command) {
  3804. if (IS_NULL_CMD(command)) {
  3805. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3806. goto clear_and_ret;
  3807. }
  3808. pi->num_cmds++;
  3809. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3810. //debug_print_tree(ctx->list_head, 20);
  3811. } else {
  3812. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3813. }
  3814. /* Only real trickiness here is that the uncommitted
  3815. * command structure is not counted in pi->num_cmds. */
  3816. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3817. ctx->command = command = &pi->cmds[pi->num_cmds];
  3818. clear_and_ret:
  3819. memset(command, 0, sizeof(*command));
  3820. return pi->num_cmds; /* used only for 0/nonzero check */
  3821. }
  3822. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3823. {
  3824. int not_null;
  3825. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3826. /* Close previous command */
  3827. not_null = done_command(ctx);
  3828. ctx->pipe->followup = type;
  3829. #if HAS_KEYWORDS
  3830. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3831. ctx->ctx_inverted = 0;
  3832. ctx->pipe->res_word = ctx->ctx_res_w;
  3833. #endif
  3834. /* Without this check, even just <enter> on command line generates
  3835. * tree of three NOPs (!). Which is harmless but annoying.
  3836. * IOW: it is safe to do it unconditionally. */
  3837. if (not_null
  3838. #if ENABLE_HUSH_IF
  3839. || ctx->ctx_res_w == RES_FI
  3840. #endif
  3841. #if ENABLE_HUSH_LOOPS
  3842. || ctx->ctx_res_w == RES_DONE
  3843. || ctx->ctx_res_w == RES_FOR
  3844. || ctx->ctx_res_w == RES_IN
  3845. #endif
  3846. #if ENABLE_HUSH_CASE
  3847. || ctx->ctx_res_w == RES_ESAC
  3848. #endif
  3849. ) {
  3850. struct pipe *new_p;
  3851. debug_printf_parse("done_pipe: adding new pipe: "
  3852. "not_null:%d ctx->ctx_res_w:%d\n",
  3853. not_null, ctx->ctx_res_w);
  3854. new_p = new_pipe();
  3855. ctx->pipe->next = new_p;
  3856. ctx->pipe = new_p;
  3857. /* RES_THEN, RES_DO etc are "sticky" -
  3858. * they remain set for pipes inside if/while.
  3859. * This is used to control execution.
  3860. * RES_FOR and RES_IN are NOT sticky (needed to support
  3861. * cases where variable or value happens to match a keyword):
  3862. */
  3863. #if ENABLE_HUSH_LOOPS
  3864. if (ctx->ctx_res_w == RES_FOR
  3865. || ctx->ctx_res_w == RES_IN)
  3866. ctx->ctx_res_w = RES_NONE;
  3867. #endif
  3868. #if ENABLE_HUSH_CASE
  3869. if (ctx->ctx_res_w == RES_MATCH)
  3870. ctx->ctx_res_w = RES_CASEI;
  3871. #endif
  3872. ctx->command = NULL; /* trick done_command below */
  3873. /* Create the memory for command, roughly:
  3874. * ctx->pipe->cmds = new struct command;
  3875. * ctx->command = &ctx->pipe->cmds[0];
  3876. */
  3877. done_command(ctx);
  3878. //debug_print_tree(ctx->list_head, 10);
  3879. }
  3880. debug_printf_parse("done_pipe return\n");
  3881. }
  3882. static void initialize_context(struct parse_context *ctx)
  3883. {
  3884. memset(ctx, 0, sizeof(*ctx));
  3885. ctx->pipe = ctx->list_head = new_pipe();
  3886. /* Create the memory for command, roughly:
  3887. * ctx->pipe->cmds = new struct command;
  3888. * ctx->command = &ctx->pipe->cmds[0];
  3889. */
  3890. done_command(ctx);
  3891. }
  3892. /* If a reserved word is found and processed, parse context is modified
  3893. * and 1 is returned.
  3894. */
  3895. #if HAS_KEYWORDS
  3896. struct reserved_combo {
  3897. char literal[6];
  3898. unsigned char res;
  3899. unsigned char assignment_flag;
  3900. int flag;
  3901. };
  3902. enum {
  3903. FLAG_END = (1 << RES_NONE ),
  3904. #if ENABLE_HUSH_IF
  3905. FLAG_IF = (1 << RES_IF ),
  3906. FLAG_THEN = (1 << RES_THEN ),
  3907. FLAG_ELIF = (1 << RES_ELIF ),
  3908. FLAG_ELSE = (1 << RES_ELSE ),
  3909. FLAG_FI = (1 << RES_FI ),
  3910. #endif
  3911. #if ENABLE_HUSH_LOOPS
  3912. FLAG_FOR = (1 << RES_FOR ),
  3913. FLAG_WHILE = (1 << RES_WHILE),
  3914. FLAG_UNTIL = (1 << RES_UNTIL),
  3915. FLAG_DO = (1 << RES_DO ),
  3916. FLAG_DONE = (1 << RES_DONE ),
  3917. FLAG_IN = (1 << RES_IN ),
  3918. #endif
  3919. #if ENABLE_HUSH_CASE
  3920. FLAG_MATCH = (1 << RES_MATCH),
  3921. FLAG_ESAC = (1 << RES_ESAC ),
  3922. #endif
  3923. FLAG_START = (1 << RES_XXXX ),
  3924. };
  3925. static const struct reserved_combo* match_reserved_word(o_string *word)
  3926. {
  3927. /* Mostly a list of accepted follow-up reserved words.
  3928. * FLAG_END means we are done with the sequence, and are ready
  3929. * to turn the compound list into a command.
  3930. * FLAG_START means the word must start a new compound list.
  3931. */
  3932. static const struct reserved_combo reserved_list[] = {
  3933. #if ENABLE_HUSH_IF
  3934. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3935. { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
  3936. { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3937. { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
  3938. { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
  3939. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3940. #endif
  3941. #if ENABLE_HUSH_LOOPS
  3942. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3943. { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
  3944. { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
  3945. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3946. { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
  3947. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3948. #endif
  3949. #if ENABLE_HUSH_CASE
  3950. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3951. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3952. #endif
  3953. };
  3954. const struct reserved_combo *r;
  3955. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3956. if (strcmp(word->data, r->literal) == 0)
  3957. return r;
  3958. }
  3959. return NULL;
  3960. }
  3961. /* Return 0: not a keyword, 1: keyword
  3962. */
  3963. static int reserved_word(o_string *word, struct parse_context *ctx)
  3964. {
  3965. #if ENABLE_HUSH_CASE
  3966. static const struct reserved_combo reserved_match = {
  3967. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3968. };
  3969. #endif
  3970. const struct reserved_combo *r;
  3971. if (word->o_quoted)
  3972. return 0;
  3973. r = match_reserved_word(word);
  3974. if (!r)
  3975. return 0;
  3976. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3977. #if ENABLE_HUSH_CASE
  3978. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
  3979. /* "case word IN ..." - IN part starts first match part */
  3980. r = &reserved_match;
  3981. else
  3982. #endif
  3983. if (r->flag == 0) { /* '!' */
  3984. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3985. syntax_error("! ! command");
  3986. ctx->ctx_res_w = RES_SNTX;
  3987. }
  3988. ctx->ctx_inverted = 1;
  3989. return 1;
  3990. }
  3991. if (r->flag & FLAG_START) {
  3992. struct parse_context *old;
  3993. old = xmalloc(sizeof(*old));
  3994. debug_printf_parse("push stack %p\n", old);
  3995. *old = *ctx; /* physical copy */
  3996. initialize_context(ctx);
  3997. ctx->stack = old;
  3998. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3999. syntax_error_at(word->data);
  4000. ctx->ctx_res_w = RES_SNTX;
  4001. return 1;
  4002. } else {
  4003. /* "{...} fi" is ok. "{...} if" is not
  4004. * Example:
  4005. * if { echo foo; } then { echo bar; } fi */
  4006. if (ctx->command->group)
  4007. done_pipe(ctx, PIPE_SEQ);
  4008. }
  4009. ctx->ctx_res_w = r->res;
  4010. ctx->old_flag = r->flag;
  4011. word->o_assignment = r->assignment_flag;
  4012. if (ctx->old_flag & FLAG_END) {
  4013. struct parse_context *old;
  4014. done_pipe(ctx, PIPE_SEQ);
  4015. debug_printf_parse("pop stack %p\n", ctx->stack);
  4016. old = ctx->stack;
  4017. old->command->group = ctx->list_head;
  4018. old->command->grp_type = GRP_NORMAL;
  4019. #if !BB_MMU
  4020. o_addstr(&old->as_string, ctx->as_string.data);
  4021. o_free_unsafe(&ctx->as_string);
  4022. old->command->group_as_string = xstrdup(old->as_string.data);
  4023. debug_printf_parse("pop, remembering as:'%s'\n",
  4024. old->command->group_as_string);
  4025. #endif
  4026. *ctx = *old; /* physical copy */
  4027. free(old);
  4028. }
  4029. return 1;
  4030. }
  4031. #endif
  4032. /* Word is complete, look at it and update parsing context.
  4033. * Normal return is 0. Syntax errors return 1.
  4034. * Note: on return, word is reset, but not o_free'd!
  4035. */
  4036. static int done_word(o_string *word, struct parse_context *ctx)
  4037. {
  4038. struct command *command = ctx->command;
  4039. debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
  4040. if (word->length == 0 && word->o_quoted == 0) {
  4041. debug_printf_parse("done_word return 0: true null, ignored\n");
  4042. return 0;
  4043. }
  4044. if (ctx->pending_redirect) {
  4045. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  4046. * only if run as "bash", not "sh" */
  4047. /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4048. * "2.7 Redirection
  4049. * ...the word that follows the redirection operator
  4050. * shall be subjected to tilde expansion, parameter expansion,
  4051. * command substitution, arithmetic expansion, and quote
  4052. * removal. Pathname expansion shall not be performed
  4053. * on the word by a non-interactive shell; an interactive
  4054. * shell may perform it, but shall do so only when
  4055. * the expansion would result in one word."
  4056. */
  4057. ctx->pending_redirect->rd_filename = xstrdup(word->data);
  4058. /* Cater for >\file case:
  4059. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  4060. * Same with heredocs:
  4061. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  4062. */
  4063. unbackslash(ctx->pending_redirect->rd_filename);
  4064. /* Is it <<"HEREDOC"? */
  4065. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
  4066. && word->o_quoted
  4067. ) {
  4068. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  4069. }
  4070. debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
  4071. ctx->pending_redirect = NULL;
  4072. } else {
  4073. /* If this word wasn't an assignment, next ones definitely
  4074. * can't be assignments. Even if they look like ones. */
  4075. if (word->o_assignment != DEFINITELY_ASSIGNMENT
  4076. && word->o_assignment != WORD_IS_KEYWORD
  4077. ) {
  4078. word->o_assignment = NOT_ASSIGNMENT;
  4079. } else {
  4080. if (word->o_assignment == DEFINITELY_ASSIGNMENT)
  4081. command->assignment_cnt++;
  4082. word->o_assignment = MAYBE_ASSIGNMENT;
  4083. }
  4084. #if HAS_KEYWORDS
  4085. # if ENABLE_HUSH_CASE
  4086. if (ctx->ctx_dsemicolon
  4087. && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  4088. ) {
  4089. /* already done when ctx_dsemicolon was set to 1: */
  4090. /* ctx->ctx_res_w = RES_MATCH; */
  4091. ctx->ctx_dsemicolon = 0;
  4092. } else
  4093. # endif
  4094. if (!command->argv /* if it's the first word... */
  4095. # if ENABLE_HUSH_LOOPS
  4096. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  4097. && ctx->ctx_res_w != RES_IN
  4098. # endif
  4099. ) {
  4100. debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
  4101. if (reserved_word(word, ctx)) {
  4102. o_reset_to_empty_unquoted(word);
  4103. debug_printf_parse("done_word return %d\n",
  4104. (ctx->ctx_res_w == RES_SNTX));
  4105. return (ctx->ctx_res_w == RES_SNTX);
  4106. }
  4107. }
  4108. #endif
  4109. if (command->group) {
  4110. /* "{ echo foo; } echo bar" - bad */
  4111. syntax_error_at(word->data);
  4112. debug_printf_parse("done_word return 1: syntax error, "
  4113. "groups and arglists don't mix\n");
  4114. return 1;
  4115. }
  4116. if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
  4117. /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
  4118. && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
  4119. /* (otherwise it's known to be not empty and is already safe) */
  4120. ) {
  4121. /* exclude "$@" - it can expand to no word despite "" */
  4122. char *p = word->data;
  4123. while (p[0] == SPECIAL_VAR_SYMBOL
  4124. && (p[1] & 0x7f) == '@'
  4125. && p[2] == SPECIAL_VAR_SYMBOL
  4126. ) {
  4127. p += 3;
  4128. }
  4129. if (p == word->data || p[0] != '\0') {
  4130. /* saw no "$@", or not only "$@" but some
  4131. * real text is there too */
  4132. /* insert "empty variable" reference, this makes
  4133. * e.g. "", $empty"" etc to not disappear */
  4134. o_addchr(word, SPECIAL_VAR_SYMBOL);
  4135. o_addchr(word, SPECIAL_VAR_SYMBOL);
  4136. }
  4137. }
  4138. command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
  4139. debug_print_strings("word appended to argv", command->argv);
  4140. }
  4141. #if ENABLE_HUSH_LOOPS
  4142. if (ctx->ctx_res_w == RES_FOR) {
  4143. if (word->o_quoted
  4144. || !is_well_formed_var_name(command->argv[0], '\0')
  4145. ) {
  4146. /* bash says just "not a valid identifier" */
  4147. syntax_error("not a valid identifier in for");
  4148. return 1;
  4149. }
  4150. /* Force FOR to have just one word (variable name) */
  4151. /* NB: basically, this makes hush see "for v in ..."
  4152. * syntax as if it is "for v; in ...". FOR and IN become
  4153. * two pipe structs in parse tree. */
  4154. done_pipe(ctx, PIPE_SEQ);
  4155. }
  4156. #endif
  4157. #if ENABLE_HUSH_CASE
  4158. /* Force CASE to have just one word */
  4159. if (ctx->ctx_res_w == RES_CASE) {
  4160. done_pipe(ctx, PIPE_SEQ);
  4161. }
  4162. #endif
  4163. o_reset_to_empty_unquoted(word);
  4164. debug_printf_parse("done_word return 0\n");
  4165. return 0;
  4166. }
  4167. /* Peek ahead in the input to find out if we have a "&n" construct,
  4168. * as in "2>&1", that represents duplicating a file descriptor.
  4169. * Return:
  4170. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4171. * REDIRFD_SYNTAX_ERR if syntax error,
  4172. * REDIRFD_TO_FILE if no & was seen,
  4173. * or the number found.
  4174. */
  4175. #if BB_MMU
  4176. #define parse_redir_right_fd(as_string, input) \
  4177. parse_redir_right_fd(input)
  4178. #endif
  4179. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4180. {
  4181. int ch, d, ok;
  4182. ch = i_peek(input);
  4183. if (ch != '&')
  4184. return REDIRFD_TO_FILE;
  4185. ch = i_getch(input); /* get the & */
  4186. nommu_addchr(as_string, ch);
  4187. ch = i_peek(input);
  4188. if (ch == '-') {
  4189. ch = i_getch(input);
  4190. nommu_addchr(as_string, ch);
  4191. return REDIRFD_CLOSE;
  4192. }
  4193. d = 0;
  4194. ok = 0;
  4195. while (ch != EOF && isdigit(ch)) {
  4196. d = d*10 + (ch-'0');
  4197. ok = 1;
  4198. ch = i_getch(input);
  4199. nommu_addchr(as_string, ch);
  4200. ch = i_peek(input);
  4201. }
  4202. if (ok) return d;
  4203. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4204. bb_error_msg("ambiguous redirect");
  4205. return REDIRFD_SYNTAX_ERR;
  4206. }
  4207. /* Return code is 0 normal, 1 if a syntax error is detected
  4208. */
  4209. static int parse_redirect(struct parse_context *ctx,
  4210. int fd,
  4211. redir_type style,
  4212. struct in_str *input)
  4213. {
  4214. struct command *command = ctx->command;
  4215. struct redir_struct *redir;
  4216. struct redir_struct **redirp;
  4217. int dup_num;
  4218. dup_num = REDIRFD_TO_FILE;
  4219. if (style != REDIRECT_HEREDOC) {
  4220. /* Check for a '>&1' type redirect */
  4221. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4222. if (dup_num == REDIRFD_SYNTAX_ERR)
  4223. return 1;
  4224. } else {
  4225. int ch = i_peek(input);
  4226. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4227. if (dup_num) { /* <<-... */
  4228. ch = i_getch(input);
  4229. nommu_addchr(&ctx->as_string, ch);
  4230. ch = i_peek(input);
  4231. }
  4232. }
  4233. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4234. int ch = i_peek(input);
  4235. if (ch == '|') {
  4236. /* >|FILE redirect ("clobbering" >).
  4237. * Since we do not support "set -o noclobber" yet,
  4238. * >| and > are the same for now. Just eat |.
  4239. */
  4240. ch = i_getch(input);
  4241. nommu_addchr(&ctx->as_string, ch);
  4242. }
  4243. }
  4244. /* Create a new redir_struct and append it to the linked list */
  4245. redirp = &command->redirects;
  4246. while ((redir = *redirp) != NULL) {
  4247. redirp = &(redir->next);
  4248. }
  4249. *redirp = redir = xzalloc(sizeof(*redir));
  4250. /* redir->next = NULL; */
  4251. /* redir->rd_filename = NULL; */
  4252. redir->rd_type = style;
  4253. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4254. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4255. redir_table[style].descrip);
  4256. redir->rd_dup = dup_num;
  4257. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4258. /* Erik had a check here that the file descriptor in question
  4259. * is legit; I postpone that to "run time"
  4260. * A "-" representation of "close me" shows up as a -3 here */
  4261. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4262. redir->rd_fd, redir->rd_dup);
  4263. } else {
  4264. /* Set ctx->pending_redirect, so we know what to do at the
  4265. * end of the next parsed word. */
  4266. ctx->pending_redirect = redir;
  4267. }
  4268. return 0;
  4269. }
  4270. /* If a redirect is immediately preceded by a number, that number is
  4271. * supposed to tell which file descriptor to redirect. This routine
  4272. * looks for such preceding numbers. In an ideal world this routine
  4273. * needs to handle all the following classes of redirects...
  4274. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4275. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4276. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4277. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4278. *
  4279. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4280. * "2.7 Redirection
  4281. * ... If n is quoted, the number shall not be recognized as part of
  4282. * the redirection expression. For example:
  4283. * echo \2>a
  4284. * writes the character 2 into file a"
  4285. * We are getting it right by setting ->o_quoted on any \<char>
  4286. *
  4287. * A -1 return means no valid number was found,
  4288. * the caller should use the appropriate default for this redirection.
  4289. */
  4290. static int redirect_opt_num(o_string *o)
  4291. {
  4292. int num;
  4293. if (o->data == NULL)
  4294. return -1;
  4295. num = bb_strtou(o->data, NULL, 10);
  4296. if (errno || num < 0)
  4297. return -1;
  4298. o_reset_to_empty_unquoted(o);
  4299. return num;
  4300. }
  4301. #if BB_MMU
  4302. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4303. fetch_till_str(input, word, skip_tabs)
  4304. #endif
  4305. static char *fetch_till_str(o_string *as_string,
  4306. struct in_str *input,
  4307. const char *word,
  4308. int skip_tabs)
  4309. {
  4310. o_string heredoc = NULL_O_STRING;
  4311. int past_EOL = 0;
  4312. int ch;
  4313. goto jump_in;
  4314. while (1) {
  4315. ch = i_getch(input);
  4316. nommu_addchr(as_string, ch);
  4317. if (ch == '\n') {
  4318. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4319. heredoc.data[past_EOL] = '\0';
  4320. debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
  4321. return heredoc.data;
  4322. }
  4323. do {
  4324. o_addchr(&heredoc, ch);
  4325. past_EOL = heredoc.length;
  4326. jump_in:
  4327. do {
  4328. ch = i_getch(input);
  4329. nommu_addchr(as_string, ch);
  4330. } while (skip_tabs && ch == '\t');
  4331. } while (ch == '\n');
  4332. }
  4333. if (ch == EOF) {
  4334. o_free_unsafe(&heredoc);
  4335. return NULL;
  4336. }
  4337. o_addchr(&heredoc, ch);
  4338. nommu_addchr(as_string, ch);
  4339. }
  4340. }
  4341. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4342. * and load them all. There should be exactly heredoc_cnt of them.
  4343. */
  4344. static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
  4345. {
  4346. struct pipe *pi = ctx->list_head;
  4347. while (pi && heredoc_cnt) {
  4348. int i;
  4349. struct command *cmd = pi->cmds;
  4350. debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4351. pi->num_cmds,
  4352. cmd->argv ? cmd->argv[0] : "NONE");
  4353. for (i = 0; i < pi->num_cmds; i++) {
  4354. struct redir_struct *redir = cmd->redirects;
  4355. debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
  4356. i, cmd->argv ? cmd->argv[0] : "NONE");
  4357. while (redir) {
  4358. if (redir->rd_type == REDIRECT_HEREDOC) {
  4359. char *p;
  4360. redir->rd_type = REDIRECT_HEREDOC2;
  4361. /* redir->dup is (ab)used to indicate <<- */
  4362. p = fetch_till_str(&ctx->as_string, input,
  4363. redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
  4364. if (!p) {
  4365. syntax_error("unexpected EOF in here document");
  4366. return 1;
  4367. }
  4368. free(redir->rd_filename);
  4369. redir->rd_filename = p;
  4370. heredoc_cnt--;
  4371. }
  4372. redir = redir->next;
  4373. }
  4374. cmd++;
  4375. }
  4376. pi = pi->next;
  4377. }
  4378. #if 0
  4379. /* Should be 0. If it isn't, it's a parse error */
  4380. if (heredoc_cnt)
  4381. bb_error_msg_and_die("heredoc BUG 2");
  4382. #endif
  4383. return 0;
  4384. }
  4385. #if ENABLE_HUSH_TICK
  4386. static FILE *generate_stream_from_string(const char *s)
  4387. {
  4388. FILE *pf;
  4389. int pid, channel[2];
  4390. #if !BB_MMU
  4391. char **to_free;
  4392. #endif
  4393. xpipe(channel);
  4394. pid = BB_MMU ? fork() : vfork();
  4395. if (pid < 0)
  4396. bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
  4397. if (pid == 0) { /* child */
  4398. disable_restore_tty_pgrp_on_exit();
  4399. /* Process substitution is not considered to be usual
  4400. * 'command execution'.
  4401. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  4402. */
  4403. bb_signals(0
  4404. + (1 << SIGTSTP)
  4405. + (1 << SIGTTIN)
  4406. + (1 << SIGTTOU)
  4407. , SIG_IGN);
  4408. close(channel[0]); /* NB: close _first_, then move fd! */
  4409. xmove_fd(channel[1], 1);
  4410. /* Prevent it from trying to handle ctrl-z etc */
  4411. IF_HUSH_JOB(G.run_list_level = 1;)
  4412. #if BB_MMU
  4413. reset_traps_to_defaults();
  4414. parse_and_run_string(s);
  4415. _exit(G.last_exitcode);
  4416. #else
  4417. /* We re-execute after vfork on NOMMU. This makes this script safe:
  4418. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  4419. * huge=`cat BIG` # was blocking here forever
  4420. * echo OK
  4421. */
  4422. re_execute_shell(&to_free,
  4423. s,
  4424. G.global_argv[0],
  4425. G.global_argv + 1);
  4426. #endif
  4427. }
  4428. /* parent */
  4429. enable_restore_tty_pgrp_on_exit();
  4430. #if !BB_MMU
  4431. free(to_free);
  4432. #endif
  4433. close(channel[1]);
  4434. pf = fdopen(channel[0], "r");
  4435. return pf;
  4436. }
  4437. /* Return code is exit status of the process that is run. */
  4438. static int process_command_subs(o_string *dest, const char *s)
  4439. {
  4440. FILE *pf;
  4441. struct in_str pipe_str;
  4442. int ch, eol_cnt;
  4443. pf = generate_stream_from_string(s);
  4444. if (pf == NULL)
  4445. return 1;
  4446. close_on_exec_on(fileno(pf));
  4447. /* Now send results of command back into original context */
  4448. setup_file_in_str(&pipe_str, pf);
  4449. eol_cnt = 0;
  4450. while ((ch = i_getch(&pipe_str)) != EOF) {
  4451. if (ch == '\n') {
  4452. eol_cnt++;
  4453. continue;
  4454. }
  4455. while (eol_cnt) {
  4456. o_addchr(dest, '\n');
  4457. eol_cnt--;
  4458. }
  4459. o_addQchr(dest, ch);
  4460. }
  4461. debug_printf("done reading from pipe, pclose()ing\n");
  4462. /* Note: we got EOF, and we just close the read end of the pipe.
  4463. * We do not wait for the `cmd` child to terminate. bash and ash do.
  4464. * Try these:
  4465. * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
  4466. * `false`; echo $? - bash outputs "1"
  4467. */
  4468. fclose(pf);
  4469. debug_printf("closed FILE from child. return 0\n");
  4470. return 0;
  4471. }
  4472. #endif
  4473. static int parse_group(o_string *dest, struct parse_context *ctx,
  4474. struct in_str *input, int ch)
  4475. {
  4476. /* dest contains characters seen prior to ( or {.
  4477. * Typically it's empty, but for function defs,
  4478. * it contains function name (without '()'). */
  4479. struct pipe *pipe_list;
  4480. int endch;
  4481. struct command *command = ctx->command;
  4482. debug_printf_parse("parse_group entered\n");
  4483. #if ENABLE_HUSH_FUNCTIONS
  4484. if (ch == '(' && !dest->o_quoted) {
  4485. if (dest->length)
  4486. if (done_word(dest, ctx))
  4487. return 1;
  4488. if (!command->argv)
  4489. goto skip; /* (... */
  4490. if (command->argv[1]) { /* word word ... (... */
  4491. syntax_error_unexpected_ch('(');
  4492. return 1;
  4493. }
  4494. /* it is "word(..." or "word (..." */
  4495. do
  4496. ch = i_getch(input);
  4497. while (ch == ' ' || ch == '\t');
  4498. if (ch != ')') {
  4499. syntax_error_unexpected_ch(ch);
  4500. return 1;
  4501. }
  4502. nommu_addchr(&ctx->as_string, ch);
  4503. do
  4504. ch = i_getch(input);
  4505. while (ch == ' ' || ch == '\t' || ch == '\n');
  4506. if (ch != '{') {
  4507. syntax_error_unexpected_ch(ch);
  4508. return 1;
  4509. }
  4510. nommu_addchr(&ctx->as_string, ch);
  4511. command->grp_type = GRP_FUNCTION;
  4512. goto skip;
  4513. }
  4514. #endif
  4515. if (command->argv /* word [word]{... */
  4516. || dest->length /* word{... */
  4517. || dest->o_quoted /* ""{... */
  4518. ) {
  4519. syntax_error(NULL);
  4520. debug_printf_parse("parse_group return 1: "
  4521. "syntax error, groups and arglists don't mix\n");
  4522. return 1;
  4523. }
  4524. #if ENABLE_HUSH_FUNCTIONS
  4525. skip:
  4526. #endif
  4527. endch = '}';
  4528. if (ch == '(') {
  4529. endch = ')';
  4530. command->grp_type = GRP_SUBSHELL;
  4531. } else {
  4532. /* bash does not allow "{echo...", requires whitespace */
  4533. ch = i_getch(input);
  4534. if (ch != ' ' && ch != '\t' && ch != '\n') {
  4535. syntax_error_unexpected_ch(ch);
  4536. return 1;
  4537. }
  4538. nommu_addchr(&ctx->as_string, ch);
  4539. }
  4540. {
  4541. #if !BB_MMU
  4542. char *as_string = NULL;
  4543. #endif
  4544. pipe_list = parse_stream(&as_string, input, endch);
  4545. #if !BB_MMU
  4546. if (as_string)
  4547. o_addstr(&ctx->as_string, as_string);
  4548. #endif
  4549. /* empty ()/{} or parse error? */
  4550. if (!pipe_list || pipe_list == ERR_PTR) {
  4551. /* parse_stream already emitted error msg */
  4552. #if !BB_MMU
  4553. free(as_string);
  4554. #endif
  4555. debug_printf_parse("parse_group return 1: "
  4556. "parse_stream returned %p\n", pipe_list);
  4557. return 1;
  4558. }
  4559. command->group = pipe_list;
  4560. #if !BB_MMU
  4561. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4562. command->group_as_string = as_string;
  4563. debug_printf_parse("end of group, remembering as:'%s'\n",
  4564. command->group_as_string);
  4565. #endif
  4566. }
  4567. debug_printf_parse("parse_group return 0\n");
  4568. return 0;
  4569. /* command remains "open", available for possible redirects */
  4570. }
  4571. #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
  4572. /* Subroutines for copying $(...) and `...` things */
  4573. static void add_till_backquote(o_string *dest, struct in_str *input);
  4574. /* '...' */
  4575. static void add_till_single_quote(o_string *dest, struct in_str *input)
  4576. {
  4577. while (1) {
  4578. int ch = i_getch(input);
  4579. if (ch == EOF) {
  4580. syntax_error_unterm_ch('\'');
  4581. /*xfunc_die(); - redundant */
  4582. }
  4583. if (ch == '\'')
  4584. return;
  4585. o_addchr(dest, ch);
  4586. }
  4587. }
  4588. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4589. static void add_till_double_quote(o_string *dest, struct in_str *input)
  4590. {
  4591. while (1) {
  4592. int ch = i_getch(input);
  4593. if (ch == EOF) {
  4594. syntax_error_unterm_ch('"');
  4595. /*xfunc_die(); - redundant */
  4596. }
  4597. if (ch == '"')
  4598. return;
  4599. if (ch == '\\') { /* \x. Copy both chars. */
  4600. o_addchr(dest, ch);
  4601. ch = i_getch(input);
  4602. }
  4603. o_addchr(dest, ch);
  4604. if (ch == '`') {
  4605. add_till_backquote(dest, input);
  4606. o_addchr(dest, ch);
  4607. continue;
  4608. }
  4609. //if (ch == '$') ...
  4610. }
  4611. }
  4612. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4613. * \` quoting.
  4614. * "Within the backquoted style of command substitution, backslash
  4615. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4616. * The search for the matching backquote shall be satisfied by the first
  4617. * backquote found without a preceding backslash; during this search,
  4618. * if a non-escaped backquote is encountered within a shell comment,
  4619. * a here-document, an embedded command substitution of the $(command)
  4620. * form, or a quoted string, undefined results occur. A single-quoted
  4621. * or double-quoted string that begins, but does not end, within the
  4622. * "`...`" sequence produces undefined results."
  4623. * Example Output
  4624. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4625. */
  4626. static void add_till_backquote(o_string *dest, struct in_str *input)
  4627. {
  4628. while (1) {
  4629. int ch = i_getch(input);
  4630. if (ch == EOF) {
  4631. syntax_error_unterm_ch('`');
  4632. /*xfunc_die(); - redundant */
  4633. }
  4634. if (ch == '`')
  4635. return;
  4636. if (ch == '\\') {
  4637. /* \x. Copy both chars unless it is \` */
  4638. int ch2 = i_getch(input);
  4639. if (ch2 == EOF) {
  4640. syntax_error_unterm_ch('`');
  4641. /*xfunc_die(); - redundant */
  4642. }
  4643. if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
  4644. o_addchr(dest, ch);
  4645. ch = ch2;
  4646. }
  4647. o_addchr(dest, ch);
  4648. }
  4649. }
  4650. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4651. * quoting and nested ()s.
  4652. * "With the $(command) style of command substitution, all characters
  4653. * following the open parenthesis to the matching closing parenthesis
  4654. * constitute the command. Any valid shell script can be used for command,
  4655. * except a script consisting solely of redirections which produces
  4656. * unspecified results."
  4657. * Example Output
  4658. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4659. * echo $(echo 'TEST)' BEST) TEST) BEST
  4660. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4661. */
  4662. static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
  4663. {
  4664. int count = 0;
  4665. while (1) {
  4666. int ch = i_getch(input);
  4667. if (ch == EOF) {
  4668. syntax_error_unterm_ch(')');
  4669. /*xfunc_die(); - redundant */
  4670. }
  4671. if (ch == '(')
  4672. count++;
  4673. if (ch == ')') {
  4674. if (--count < 0) {
  4675. if (!dbl)
  4676. break;
  4677. if (i_peek(input) == ')') {
  4678. i_getch(input);
  4679. break;
  4680. }
  4681. }
  4682. }
  4683. o_addchr(dest, ch);
  4684. if (ch == '\'') {
  4685. add_till_single_quote(dest, input);
  4686. o_addchr(dest, ch);
  4687. continue;
  4688. }
  4689. if (ch == '"') {
  4690. add_till_double_quote(dest, input);
  4691. o_addchr(dest, ch);
  4692. continue;
  4693. }
  4694. if (ch == '\\') {
  4695. /* \x. Copy verbatim. Important for \(, \) */
  4696. ch = i_getch(input);
  4697. if (ch == EOF) {
  4698. syntax_error_unterm_ch(')');
  4699. /*xfunc_die(); - redundant */
  4700. }
  4701. o_addchr(dest, ch);
  4702. continue;
  4703. }
  4704. }
  4705. }
  4706. #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
  4707. /* Return code: 0 for OK, 1 for syntax error */
  4708. #if BB_MMU
  4709. #define handle_dollar(as_string, dest, input) \
  4710. handle_dollar(dest, input)
  4711. #endif
  4712. static int handle_dollar(o_string *as_string,
  4713. o_string *dest,
  4714. struct in_str *input)
  4715. {
  4716. int expansion;
  4717. int ch = i_peek(input); /* first character after the $ */
  4718. unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
  4719. debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
  4720. if (isalpha(ch)) {
  4721. ch = i_getch(input);
  4722. nommu_addchr(as_string, ch);
  4723. make_var:
  4724. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4725. while (1) {
  4726. debug_printf_parse(": '%c'\n", ch);
  4727. o_addchr(dest, ch | quote_mask);
  4728. quote_mask = 0;
  4729. ch = i_peek(input);
  4730. if (!isalnum(ch) && ch != '_')
  4731. break;
  4732. ch = i_getch(input);
  4733. nommu_addchr(as_string, ch);
  4734. }
  4735. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4736. } else if (isdigit(ch)) {
  4737. make_one_char_var:
  4738. ch = i_getch(input);
  4739. nommu_addchr(as_string, ch);
  4740. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4741. debug_printf_parse(": '%c'\n", ch);
  4742. o_addchr(dest, ch | quote_mask);
  4743. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4744. } else switch (ch) {
  4745. case '$': /* pid */
  4746. case '!': /* last bg pid */
  4747. case '?': /* last exit code */
  4748. case '#': /* number of args */
  4749. case '*': /* args */
  4750. case '@': /* args */
  4751. goto make_one_char_var;
  4752. case '{': {
  4753. bool first_char, all_digits;
  4754. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4755. ch = i_getch(input);
  4756. nommu_addchr(as_string, ch);
  4757. /* TODO: maybe someone will try to escape the '}' */
  4758. expansion = 0;
  4759. first_char = true;
  4760. all_digits = false;
  4761. while (1) {
  4762. ch = i_getch(input);
  4763. nommu_addchr(as_string, ch);
  4764. if (ch == '}') {
  4765. break;
  4766. }
  4767. if (first_char) {
  4768. if (ch == '#') {
  4769. /* ${#var}: length of var contents */
  4770. goto char_ok;
  4771. }
  4772. if (isdigit(ch)) {
  4773. all_digits = true;
  4774. goto char_ok;
  4775. }
  4776. }
  4777. if (expansion < 2
  4778. && ( (all_digits && !isdigit(ch))
  4779. || (!all_digits && !isalnum(ch) && ch != '_')
  4780. )
  4781. ) {
  4782. /* handle parameter expansions
  4783. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4784. */
  4785. if (first_char)
  4786. goto case_default;
  4787. switch (ch) {
  4788. case ':': /* null modifier */
  4789. if (expansion == 0) {
  4790. debug_printf_parse(": null modifier\n");
  4791. ++expansion;
  4792. break;
  4793. }
  4794. goto case_default;
  4795. case '#': /* remove prefix */
  4796. case '%': /* remove suffix */
  4797. if (expansion == 0) {
  4798. debug_printf_parse(": remove suffix/prefix\n");
  4799. expansion = 2;
  4800. break;
  4801. }
  4802. goto case_default;
  4803. case '-': /* default value */
  4804. case '=': /* assign default */
  4805. case '+': /* alternative */
  4806. case '?': /* error indicate */
  4807. debug_printf_parse(": parameter expansion\n");
  4808. expansion = 2;
  4809. break;
  4810. default:
  4811. case_default:
  4812. syntax_error_unterm_str("${name}");
  4813. debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
  4814. return 1;
  4815. }
  4816. }
  4817. char_ok:
  4818. debug_printf_parse(": '%c'\n", ch);
  4819. o_addchr(dest, ch | quote_mask);
  4820. quote_mask = 0;
  4821. first_char = false;
  4822. } /* while (1) */
  4823. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4824. break;
  4825. }
  4826. #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
  4827. case '(': {
  4828. # if !BB_MMU
  4829. int pos;
  4830. # endif
  4831. ch = i_getch(input);
  4832. nommu_addchr(as_string, ch);
  4833. # if ENABLE_SH_MATH_SUPPORT
  4834. if (i_peek(input) == '(') {
  4835. ch = i_getch(input);
  4836. nommu_addchr(as_string, ch);
  4837. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4838. o_addchr(dest, /*quote_mask |*/ '+');
  4839. # if !BB_MMU
  4840. pos = dest->length;
  4841. # endif
  4842. add_till_closing_paren(dest, input, true);
  4843. # if !BB_MMU
  4844. if (as_string) {
  4845. o_addstr(as_string, dest->data + pos);
  4846. o_addchr(as_string, ')');
  4847. o_addchr(as_string, ')');
  4848. }
  4849. # endif
  4850. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4851. break;
  4852. }
  4853. # endif
  4854. # if ENABLE_HUSH_TICK
  4855. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4856. o_addchr(dest, quote_mask | '`');
  4857. # if !BB_MMU
  4858. pos = dest->length;
  4859. # endif
  4860. add_till_closing_paren(dest, input, false);
  4861. # if !BB_MMU
  4862. if (as_string) {
  4863. o_addstr(as_string, dest->data + pos);
  4864. o_addchr(as_string, '`');
  4865. }
  4866. # endif
  4867. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4868. # endif
  4869. break;
  4870. }
  4871. #endif
  4872. case '_':
  4873. ch = i_getch(input);
  4874. nommu_addchr(as_string, ch);
  4875. ch = i_peek(input);
  4876. if (isalnum(ch)) { /* it's $_name or $_123 */
  4877. ch = '_';
  4878. goto make_var;
  4879. }
  4880. /* else: it's $_ */
  4881. /* TODO: */
  4882. /* $_ Shell or shell script name; or last cmd name */
  4883. /* $- Option flags set by set builtin or shell options (-i etc) */
  4884. default:
  4885. o_addQchr(dest, '$');
  4886. }
  4887. debug_printf_parse("handle_dollar return 0\n");
  4888. return 0;
  4889. }
  4890. #if BB_MMU
  4891. #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
  4892. parse_stream_dquoted(dest, input, dquote_end)
  4893. #endif
  4894. static int parse_stream_dquoted(o_string *as_string,
  4895. o_string *dest,
  4896. struct in_str *input,
  4897. int dquote_end)
  4898. {
  4899. int ch;
  4900. int next;
  4901. again:
  4902. ch = i_getch(input);
  4903. if (ch != EOF)
  4904. nommu_addchr(as_string, ch);
  4905. if (ch == dquote_end) { /* may be only '"' or EOF */
  4906. if (dest->o_assignment == NOT_ASSIGNMENT)
  4907. dest->o_escape ^= 1;
  4908. debug_printf_parse("parse_stream_dquoted return 0\n");
  4909. return 0;
  4910. }
  4911. /* note: can't move it above ch == dquote_end check! */
  4912. if (ch == EOF) {
  4913. syntax_error_unterm_ch('"');
  4914. /*xfunc_die(); - redundant */
  4915. }
  4916. next = '\0';
  4917. if (ch != '\n') {
  4918. next = i_peek(input);
  4919. }
  4920. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4921. ch, ch, dest->o_escape);
  4922. if (ch == '\\') {
  4923. if (next == EOF) {
  4924. syntax_error("\\<eof>");
  4925. xfunc_die();
  4926. }
  4927. /* bash:
  4928. * "The backslash retains its special meaning [in "..."]
  4929. * only when followed by one of the following characters:
  4930. * $, `, ", \, or <newline>. A double quote may be quoted
  4931. * within double quotes by preceding it with a backslash.
  4932. */
  4933. if (strchr("$`\"\\", next) != NULL) {
  4934. o_addqchr(dest, i_getch(input));
  4935. } else {
  4936. o_addqchr(dest, '\\');
  4937. }
  4938. goto again;
  4939. }
  4940. if (ch == '$') {
  4941. if (handle_dollar(as_string, dest, input) != 0) {
  4942. debug_printf_parse("parse_stream_dquoted return 1: "
  4943. "handle_dollar returned non-0\n");
  4944. return 1;
  4945. }
  4946. goto again;
  4947. }
  4948. #if ENABLE_HUSH_TICK
  4949. if (ch == '`') {
  4950. //int pos = dest->length;
  4951. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4952. o_addchr(dest, 0x80 | '`');
  4953. add_till_backquote(dest, input);
  4954. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4955. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4956. goto again;
  4957. }
  4958. #endif
  4959. o_addQchr(dest, ch);
  4960. if (ch == '='
  4961. && (dest->o_assignment == MAYBE_ASSIGNMENT
  4962. || dest->o_assignment == WORD_IS_KEYWORD)
  4963. && is_well_formed_var_name(dest->data, '=')
  4964. ) {
  4965. dest->o_assignment = DEFINITELY_ASSIGNMENT;
  4966. }
  4967. goto again;
  4968. }
  4969. /*
  4970. * Scan input until EOF or end_trigger char.
  4971. * Return a list of pipes to execute, or NULL on EOF
  4972. * or if end_trigger character is met.
  4973. * On syntax error, exit is shell is not interactive,
  4974. * reset parsing machinery and start parsing anew,
  4975. * or return ERR_PTR.
  4976. */
  4977. static struct pipe *parse_stream(char **pstring,
  4978. struct in_str *input,
  4979. int end_trigger)
  4980. {
  4981. struct parse_context ctx;
  4982. o_string dest = NULL_O_STRING;
  4983. int is_in_dquote;
  4984. int heredoc_cnt;
  4985. /* Double-quote state is handled in the state variable is_in_dquote.
  4986. * A single-quote triggers a bypass of the main loop until its mate is
  4987. * found. When recursing, quote state is passed in via dest->o_escape.
  4988. */
  4989. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4990. end_trigger ? : 'X');
  4991. debug_enter();
  4992. G.ifs = get_local_var_value("IFS");
  4993. if (G.ifs == NULL)
  4994. G.ifs = " \t\n";
  4995. reset:
  4996. #if ENABLE_HUSH_INTERACTIVE
  4997. input->promptmode = 0; /* PS1 */
  4998. #endif
  4999. /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
  5000. initialize_context(&ctx);
  5001. is_in_dquote = 0;
  5002. heredoc_cnt = 0;
  5003. while (1) {
  5004. const char *is_ifs;
  5005. const char *is_special;
  5006. int ch;
  5007. int next;
  5008. int redir_fd;
  5009. redir_type redir_style;
  5010. if (is_in_dquote) {
  5011. /* dest.o_quoted = 1; - already is (see below) */
  5012. if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
  5013. goto parse_error;
  5014. }
  5015. /* We reached closing '"' */
  5016. is_in_dquote = 0;
  5017. }
  5018. ch = i_getch(input);
  5019. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5020. ch, ch, dest.o_escape);
  5021. if (ch == EOF) {
  5022. struct pipe *pi;
  5023. if (heredoc_cnt) {
  5024. syntax_error_unterm_str("here document");
  5025. xfunc_die();
  5026. }
  5027. if (done_word(&dest, &ctx)) {
  5028. xfunc_die();
  5029. }
  5030. o_free(&dest);
  5031. done_pipe(&ctx, PIPE_SEQ);
  5032. pi = ctx.list_head;
  5033. /* If we got nothing... */
  5034. /* (this makes bare "&" cmd a no-op.
  5035. * bash says: "syntax error near unexpected token '&'") */
  5036. if (pi->num_cmds == 0
  5037. IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
  5038. ) {
  5039. free_pipe_list(pi);
  5040. pi = NULL;
  5041. }
  5042. #if !BB_MMU
  5043. debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
  5044. if (pstring)
  5045. *pstring = ctx.as_string.data;
  5046. else
  5047. o_free_unsafe(&ctx.as_string);
  5048. #endif
  5049. debug_leave();
  5050. debug_printf_parse("parse_stream return %p\n", pi);
  5051. return pi;
  5052. }
  5053. nommu_addchr(&ctx.as_string, ch);
  5054. is_ifs = strchr(G.ifs, ch);
  5055. is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
  5056. "\\$\"" IF_HUSH_TICK("`") /* always special */
  5057. , ch);
  5058. if (!is_special && !is_ifs) { /* ordinary char */
  5059. ordinary_char:
  5060. o_addQchr(&dest, ch);
  5061. if ((dest.o_assignment == MAYBE_ASSIGNMENT
  5062. || dest.o_assignment == WORD_IS_KEYWORD)
  5063. && ch == '='
  5064. && is_well_formed_var_name(dest.data, '=')
  5065. ) {
  5066. dest.o_assignment = DEFINITELY_ASSIGNMENT;
  5067. }
  5068. continue;
  5069. }
  5070. if (is_ifs) {
  5071. if (done_word(&dest, &ctx)) {
  5072. goto parse_error;
  5073. }
  5074. if (ch == '\n') {
  5075. #if ENABLE_HUSH_CASE
  5076. /* "case ... in <newline> word) ..." -
  5077. * newlines are ignored (but ';' wouldn't be) */
  5078. if (ctx.command->argv == NULL
  5079. && ctx.ctx_res_w == RES_MATCH
  5080. ) {
  5081. continue;
  5082. }
  5083. #endif
  5084. /* Treat newline as a command separator. */
  5085. done_pipe(&ctx, PIPE_SEQ);
  5086. debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
  5087. if (heredoc_cnt) {
  5088. if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
  5089. goto parse_error;
  5090. }
  5091. heredoc_cnt = 0;
  5092. }
  5093. dest.o_assignment = MAYBE_ASSIGNMENT;
  5094. ch = ';';
  5095. /* note: if (is_ifs) continue;
  5096. * will still trigger for us */
  5097. }
  5098. }
  5099. /* "cmd}" or "cmd }..." without semicolon or &:
  5100. * } is an ordinary char in this case, even inside { cmd; }
  5101. * Pathological example: { ""}; } should exec "}" cmd
  5102. */
  5103. if (ch == '}') {
  5104. if (!IS_NULL_CMD(ctx.command) /* cmd } */
  5105. || dest.length != 0 /* word} */
  5106. || dest.o_quoted /* ""} */
  5107. ) {
  5108. goto ordinary_char;
  5109. }
  5110. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5111. goto skip_end_trigger;
  5112. /* else: } does terminate a group */
  5113. }
  5114. if (end_trigger && end_trigger == ch
  5115. && (heredoc_cnt == 0 || end_trigger != ';')
  5116. ) {
  5117. if (heredoc_cnt) {
  5118. /* This is technically valid:
  5119. * { cat <<HERE; }; echo Ok
  5120. * heredoc
  5121. * heredoc
  5122. * HERE
  5123. * but we don't support this.
  5124. * We require heredoc to be in enclosing {}/(),
  5125. * if any.
  5126. */
  5127. syntax_error_unterm_str("here document");
  5128. goto parse_error;
  5129. }
  5130. if (done_word(&dest, &ctx)) {
  5131. goto parse_error;
  5132. }
  5133. done_pipe(&ctx, PIPE_SEQ);
  5134. dest.o_assignment = MAYBE_ASSIGNMENT;
  5135. /* Do we sit outside of any if's, loops or case's? */
  5136. if (!HAS_KEYWORDS
  5137. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5138. ) {
  5139. o_free(&dest);
  5140. #if !BB_MMU
  5141. debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
  5142. if (pstring)
  5143. *pstring = ctx.as_string.data;
  5144. else
  5145. o_free_unsafe(&ctx.as_string);
  5146. #endif
  5147. debug_leave();
  5148. debug_printf_parse("parse_stream return %p: "
  5149. "end_trigger char found\n",
  5150. ctx.list_head);
  5151. return ctx.list_head;
  5152. }
  5153. }
  5154. skip_end_trigger:
  5155. if (is_ifs)
  5156. continue;
  5157. next = '\0';
  5158. if (ch != '\n') {
  5159. next = i_peek(input);
  5160. }
  5161. /* Catch <, > before deciding whether this word is
  5162. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5163. switch (ch) {
  5164. case '>':
  5165. redir_fd = redirect_opt_num(&dest);
  5166. if (done_word(&dest, &ctx)) {
  5167. goto parse_error;
  5168. }
  5169. redir_style = REDIRECT_OVERWRITE;
  5170. if (next == '>') {
  5171. redir_style = REDIRECT_APPEND;
  5172. ch = i_getch(input);
  5173. nommu_addchr(&ctx.as_string, ch);
  5174. }
  5175. #if 0
  5176. else if (next == '(') {
  5177. syntax_error(">(process) not supported");
  5178. goto parse_error;
  5179. }
  5180. #endif
  5181. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5182. goto parse_error;
  5183. continue; /* back to top of while (1) */
  5184. case '<':
  5185. redir_fd = redirect_opt_num(&dest);
  5186. if (done_word(&dest, &ctx)) {
  5187. goto parse_error;
  5188. }
  5189. redir_style = REDIRECT_INPUT;
  5190. if (next == '<') {
  5191. redir_style = REDIRECT_HEREDOC;
  5192. heredoc_cnt++;
  5193. debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
  5194. ch = i_getch(input);
  5195. nommu_addchr(&ctx.as_string, ch);
  5196. } else if (next == '>') {
  5197. redir_style = REDIRECT_IO;
  5198. ch = i_getch(input);
  5199. nommu_addchr(&ctx.as_string, ch);
  5200. }
  5201. #if 0
  5202. else if (next == '(') {
  5203. syntax_error("<(process) not supported");
  5204. goto parse_error;
  5205. }
  5206. #endif
  5207. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5208. goto parse_error;
  5209. continue; /* back to top of while (1) */
  5210. }
  5211. if (dest.o_assignment == MAYBE_ASSIGNMENT
  5212. /* check that we are not in word in "a=1 2>word b=1": */
  5213. && !ctx.pending_redirect
  5214. ) {
  5215. /* ch is a special char and thus this word
  5216. * cannot be an assignment */
  5217. dest.o_assignment = NOT_ASSIGNMENT;
  5218. }
  5219. switch (ch) {
  5220. case '#':
  5221. if (dest.length == 0) {
  5222. while (1) {
  5223. ch = i_peek(input);
  5224. if (ch == EOF || ch == '\n')
  5225. break;
  5226. i_getch(input);
  5227. /* note: we do not add it to &ctx.as_string */
  5228. }
  5229. nommu_addchr(&ctx.as_string, '\n');
  5230. } else {
  5231. o_addQchr(&dest, ch);
  5232. }
  5233. break;
  5234. case '\\':
  5235. if (next == EOF) {
  5236. syntax_error("\\<eof>");
  5237. xfunc_die();
  5238. }
  5239. o_addchr(&dest, '\\');
  5240. ch = i_getch(input);
  5241. nommu_addchr(&ctx.as_string, ch);
  5242. o_addchr(&dest, ch);
  5243. /* Example: echo Hello \2>file
  5244. * we need to know that word 2 is quoted */
  5245. dest.o_quoted = 1;
  5246. break;
  5247. case '$':
  5248. if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
  5249. debug_printf_parse("parse_stream parse error: "
  5250. "handle_dollar returned non-0\n");
  5251. goto parse_error;
  5252. }
  5253. break;
  5254. case '\'':
  5255. dest.o_quoted = 1;
  5256. while (1) {
  5257. ch = i_getch(input);
  5258. if (ch == EOF) {
  5259. syntax_error_unterm_ch('\'');
  5260. /*xfunc_die(); - redundant */
  5261. }
  5262. nommu_addchr(&ctx.as_string, ch);
  5263. if (ch == '\'')
  5264. break;
  5265. if (dest.o_assignment == NOT_ASSIGNMENT)
  5266. o_addqchr(&dest, ch);
  5267. else
  5268. o_addchr(&dest, ch);
  5269. }
  5270. break;
  5271. case '"':
  5272. dest.o_quoted = 1;
  5273. is_in_dquote ^= 1; /* invert */
  5274. if (dest.o_assignment == NOT_ASSIGNMENT)
  5275. dest.o_escape ^= 1;
  5276. break;
  5277. #if ENABLE_HUSH_TICK
  5278. case '`': {
  5279. #if !BB_MMU
  5280. int pos;
  5281. #endif
  5282. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5283. o_addchr(&dest, '`');
  5284. #if !BB_MMU
  5285. pos = dest.length;
  5286. #endif
  5287. add_till_backquote(&dest, input);
  5288. #if !BB_MMU
  5289. o_addstr(&ctx.as_string, dest.data + pos);
  5290. o_addchr(&ctx.as_string, '`');
  5291. #endif
  5292. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5293. //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
  5294. break;
  5295. }
  5296. #endif
  5297. case ';':
  5298. #if ENABLE_HUSH_CASE
  5299. case_semi:
  5300. #endif
  5301. if (done_word(&dest, &ctx)) {
  5302. goto parse_error;
  5303. }
  5304. done_pipe(&ctx, PIPE_SEQ);
  5305. #if ENABLE_HUSH_CASE
  5306. /* Eat multiple semicolons, detect
  5307. * whether it means something special */
  5308. while (1) {
  5309. ch = i_peek(input);
  5310. if (ch != ';')
  5311. break;
  5312. ch = i_getch(input);
  5313. nommu_addchr(&ctx.as_string, ch);
  5314. if (ctx.ctx_res_w == RES_CASEI) {
  5315. ctx.ctx_dsemicolon = 1;
  5316. ctx.ctx_res_w = RES_MATCH;
  5317. break;
  5318. }
  5319. }
  5320. #endif
  5321. new_cmd:
  5322. /* We just finished a cmd. New one may start
  5323. * with an assignment */
  5324. dest.o_assignment = MAYBE_ASSIGNMENT;
  5325. break;
  5326. case '&':
  5327. if (done_word(&dest, &ctx)) {
  5328. goto parse_error;
  5329. }
  5330. if (next == '&') {
  5331. ch = i_getch(input);
  5332. nommu_addchr(&ctx.as_string, ch);
  5333. done_pipe(&ctx, PIPE_AND);
  5334. } else {
  5335. done_pipe(&ctx, PIPE_BG);
  5336. }
  5337. goto new_cmd;
  5338. case '|':
  5339. if (done_word(&dest, &ctx)) {
  5340. goto parse_error;
  5341. }
  5342. #if ENABLE_HUSH_CASE
  5343. if (ctx.ctx_res_w == RES_MATCH)
  5344. break; /* we are in case's "word | word)" */
  5345. #endif
  5346. if (next == '|') { /* || */
  5347. ch = i_getch(input);
  5348. nommu_addchr(&ctx.as_string, ch);
  5349. done_pipe(&ctx, PIPE_OR);
  5350. } else {
  5351. /* we could pick up a file descriptor choice here
  5352. * with redirect_opt_num(), but bash doesn't do it.
  5353. * "echo foo 2| cat" yields "foo 2". */
  5354. done_command(&ctx);
  5355. }
  5356. goto new_cmd;
  5357. case '(':
  5358. #if ENABLE_HUSH_CASE
  5359. /* "case... in [(]word)..." - skip '(' */
  5360. if (ctx.ctx_res_w == RES_MATCH
  5361. && ctx.command->argv == NULL /* not (word|(... */
  5362. && dest.length == 0 /* not word(... */
  5363. && dest.o_quoted == 0 /* not ""(... */
  5364. ) {
  5365. continue;
  5366. }
  5367. #endif
  5368. case '{':
  5369. if (parse_group(&dest, &ctx, input, ch) != 0) {
  5370. goto parse_error;
  5371. }
  5372. goto new_cmd;
  5373. case ')':
  5374. #if ENABLE_HUSH_CASE
  5375. if (ctx.ctx_res_w == RES_MATCH)
  5376. goto case_semi;
  5377. #endif
  5378. case '}':
  5379. /* proper use of this character is caught by end_trigger:
  5380. * if we see {, we call parse_group(..., end_trigger='}')
  5381. * and it will match } earlier (not here). */
  5382. syntax_error_unexpected_ch(ch);
  5383. goto parse_error;
  5384. default:
  5385. if (HUSH_DEBUG)
  5386. bb_error_msg_and_die("BUG: unexpected %c\n", ch);
  5387. }
  5388. } /* while (1) */
  5389. parse_error:
  5390. {
  5391. struct parse_context *pctx;
  5392. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5393. /* Clean up allocated tree.
  5394. * Samples for finding leaks on syntax error recovery path.
  5395. * Run them from interactive shell, watch pmap `pidof hush`.
  5396. * while if false; then false; fi do break; done
  5397. * (bash accepts it)
  5398. * while if false; then false; fi; do break; fi
  5399. * Samples to catch leaks at execution:
  5400. * while if (true | {true;}); then echo ok; fi; do break; done
  5401. * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5402. */
  5403. pctx = &ctx;
  5404. do {
  5405. /* Update pipe/command counts,
  5406. * otherwise freeing may miss some */
  5407. done_pipe(pctx, PIPE_SEQ);
  5408. debug_printf_clean("freeing list %p from ctx %p\n",
  5409. pctx->list_head, pctx);
  5410. debug_print_tree(pctx->list_head, 0);
  5411. free_pipe_list(pctx->list_head);
  5412. debug_printf_clean("freed list %p\n", pctx->list_head);
  5413. #if !BB_MMU
  5414. o_free_unsafe(&pctx->as_string);
  5415. #endif
  5416. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5417. if (pctx != &ctx) {
  5418. free(pctx);
  5419. }
  5420. IF_HAS_KEYWORDS(pctx = p2;)
  5421. } while (HAS_KEYWORDS && pctx);
  5422. /* Free text, clear all dest fields */
  5423. o_free(&dest);
  5424. /* If we are not in top-level parse, we return,
  5425. * our caller will propagate error.
  5426. */
  5427. if (end_trigger != ';') {
  5428. #if !BB_MMU
  5429. if (pstring)
  5430. *pstring = NULL;
  5431. #endif
  5432. debug_leave();
  5433. return ERR_PTR;
  5434. }
  5435. /* Discard cached input, force prompt */
  5436. input->p = NULL;
  5437. IF_HUSH_INTERACTIVE(input->promptme = 1;)
  5438. goto reset;
  5439. }
  5440. }
  5441. /* Executing from string: eval, sh -c '...'
  5442. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  5443. * end_trigger controls how often we stop parsing
  5444. * NUL: parse all, execute, return
  5445. * ';': parse till ';' or newline, execute, repeat till EOF
  5446. */
  5447. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  5448. {
  5449. while (1) {
  5450. struct pipe *pipe_list;
  5451. pipe_list = parse_stream(NULL, inp, end_trigger);
  5452. if (!pipe_list) /* EOF */
  5453. break;
  5454. debug_print_tree(pipe_list, 0);
  5455. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  5456. run_and_free_list(pipe_list);
  5457. }
  5458. }
  5459. static void parse_and_run_string(const char *s)
  5460. {
  5461. struct in_str input;
  5462. setup_string_in_str(&input, s);
  5463. parse_and_run_stream(&input, '\0');
  5464. }
  5465. static void parse_and_run_file(FILE *f)
  5466. {
  5467. struct in_str input;
  5468. setup_file_in_str(&input, f);
  5469. parse_and_run_stream(&input, ';');
  5470. }
  5471. /* Called a few times only (or even once if "sh -c") */
  5472. static void block_signals(int second_time)
  5473. {
  5474. unsigned sig;
  5475. unsigned mask;
  5476. mask = (1 << SIGQUIT);
  5477. if (G_interactive_fd)
  5478. mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
  5479. G.non_DFL_mask = mask;
  5480. if (!second_time)
  5481. sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
  5482. sig = 0;
  5483. while (mask) {
  5484. if (mask & 1)
  5485. sigaddset(&G.blocked_set, sig);
  5486. mask >>= 1;
  5487. sig++;
  5488. }
  5489. sigdelset(&G.blocked_set, SIGCHLD);
  5490. sigprocmask(SIG_SETMASK, &G.blocked_set,
  5491. second_time ? NULL : &G.inherited_set);
  5492. /* POSIX allows shell to re-enable SIGCHLD
  5493. * even if it was SIG_IGN on entry */
  5494. // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  5495. if (!second_time)
  5496. signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
  5497. }
  5498. #if ENABLE_HUSH_JOB
  5499. /* helper */
  5500. static void maybe_set_to_sigexit(int sig)
  5501. {
  5502. void (*handler)(int);
  5503. /* non_DFL_mask'ed signals are, well, masked,
  5504. * no need to set handler for them.
  5505. */
  5506. if (!((G.non_DFL_mask >> sig) & 1)) {
  5507. handler = signal(sig, sigexit);
  5508. if (handler == SIG_IGN) /* oops... restore back to IGN! */
  5509. signal(sig, handler);
  5510. }
  5511. }
  5512. /* Set handlers to restore tty pgrp and exit */
  5513. static void set_fatal_handlers(void)
  5514. {
  5515. /* We _must_ restore tty pgrp on fatal signals */
  5516. if (HUSH_DEBUG) {
  5517. maybe_set_to_sigexit(SIGILL );
  5518. maybe_set_to_sigexit(SIGFPE );
  5519. maybe_set_to_sigexit(SIGBUS );
  5520. maybe_set_to_sigexit(SIGSEGV);
  5521. maybe_set_to_sigexit(SIGTRAP);
  5522. } /* else: hush is perfect. what SEGV? */
  5523. maybe_set_to_sigexit(SIGABRT);
  5524. /* bash 3.2 seems to handle these just like 'fatal' ones */
  5525. maybe_set_to_sigexit(SIGPIPE);
  5526. maybe_set_to_sigexit(SIGALRM);
  5527. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
  5528. * if we aren't interactive... but in this case
  5529. * we never want to restore pgrp on exit, and this fn is not called */
  5530. /*maybe_set_to_sigexit(SIGHUP );*/
  5531. /*maybe_set_to_sigexit(SIGTERM);*/
  5532. /*maybe_set_to_sigexit(SIGINT );*/
  5533. }
  5534. #endif
  5535. static int set_mode(const char cstate, const char mode)
  5536. {
  5537. int state = (cstate == '-' ? 1 : 0);
  5538. switch (mode) {
  5539. case 'n': G.fake_mode = state; break;
  5540. case 'x': /*G.debug_mode = state;*/ break;
  5541. default: return EXIT_FAILURE;
  5542. }
  5543. return EXIT_SUCCESS;
  5544. }
  5545. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  5546. int hush_main(int argc, char **argv)
  5547. {
  5548. static const struct variable const_shell_ver = {
  5549. .next = NULL,
  5550. .varstr = (char*)hush_version_str,
  5551. .max_len = 1, /* 0 can provoke free(name) */
  5552. .flg_export = 1,
  5553. .flg_read_only = 1,
  5554. };
  5555. int signal_mask_is_inited = 0;
  5556. int opt;
  5557. char **e;
  5558. struct variable *cur_var;
  5559. INIT_G();
  5560. if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
  5561. G.last_exitcode = EXIT_SUCCESS;
  5562. #if !BB_MMU
  5563. G.argv0_for_re_execing = argv[0];
  5564. #endif
  5565. /* Deal with HUSH_VERSION */
  5566. G.shell_ver = const_shell_ver; /* copying struct here */
  5567. G.top_var = &G.shell_ver;
  5568. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  5569. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  5570. /* Initialize our shell local variables with the values
  5571. * currently living in the environment */
  5572. cur_var = G.top_var;
  5573. e = environ;
  5574. if (e) while (*e) {
  5575. char *value = strchr(*e, '=');
  5576. if (value) { /* paranoia */
  5577. cur_var->next = xzalloc(sizeof(*cur_var));
  5578. cur_var = cur_var->next;
  5579. cur_var->varstr = *e;
  5580. cur_var->max_len = strlen(*e);
  5581. cur_var->flg_export = 1;
  5582. }
  5583. e++;
  5584. }
  5585. debug_printf_env("putenv '%s'\n", hush_version_str);
  5586. putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
  5587. #if ENABLE_FEATURE_EDITING
  5588. G.line_input_state = new_line_input_t(FOR_SHELL);
  5589. #endif
  5590. G.global_argc = argc;
  5591. G.global_argv = argv;
  5592. /* Initialize some more globals to non-zero values */
  5593. set_cwd();
  5594. #if ENABLE_HUSH_INTERACTIVE
  5595. if (ENABLE_FEATURE_EDITING)
  5596. cmdedit_set_initial_prompt();
  5597. G.PS2 = "> ";
  5598. #endif
  5599. if (setjmp(die_jmp)) {
  5600. /* xfunc has failed! die die die */
  5601. /* no EXIT traps, this is an escape hatch! */
  5602. G.exiting = 1;
  5603. hush_exit(xfunc_error_retval);
  5604. }
  5605. /* Shell is non-interactive at first. We need to call
  5606. * block_signals(0) if we are going to execute "sh <script>",
  5607. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  5608. * If we later decide that we are interactive, we run block_signals(0)
  5609. * (or re-run block_signals(1) if we ran block_signals(0) before)
  5610. * in order to intercept (more) signals.
  5611. */
  5612. /* Parse options */
  5613. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  5614. while (1) {
  5615. opt = getopt(argc, argv, "c:xins"
  5616. #if !BB_MMU
  5617. "<:$:R:V:"
  5618. # if ENABLE_HUSH_FUNCTIONS
  5619. "F:"
  5620. # endif
  5621. #endif
  5622. );
  5623. if (opt <= 0)
  5624. break;
  5625. switch (opt) {
  5626. case 'c':
  5627. if (!G.root_pid)
  5628. G.root_pid = getpid();
  5629. G.global_argv = argv + optind;
  5630. if (!argv[optind]) {
  5631. /* -c 'script' (no params): prevent empty $0 */
  5632. *--G.global_argv = argv[0];
  5633. optind--;
  5634. } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
  5635. G.global_argc = argc - optind;
  5636. block_signals(0); /* 0: called 1st time */
  5637. parse_and_run_string(optarg);
  5638. goto final_return;
  5639. case 'i':
  5640. /* Well, we cannot just declare interactiveness,
  5641. * we have to have some stuff (ctty, etc) */
  5642. /* G_interactive_fd++; */
  5643. break;
  5644. case 's':
  5645. /* "-s" means "read from stdin", but this is how we always
  5646. * operate, so simply do nothing here. */
  5647. break;
  5648. #if !BB_MMU
  5649. case '<': /* "big heredoc" support */
  5650. full_write(STDOUT_FILENO, optarg, strlen(optarg));
  5651. _exit(0);
  5652. case '$':
  5653. G.root_pid = bb_strtou(optarg, &optarg, 16);
  5654. optarg++;
  5655. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  5656. optarg++;
  5657. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  5658. # if ENABLE_HUSH_LOOPS
  5659. optarg++;
  5660. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  5661. # endif
  5662. break;
  5663. case 'R':
  5664. case 'V':
  5665. set_local_var(xstrdup(optarg), 0, opt == 'R');
  5666. break;
  5667. # if ENABLE_HUSH_FUNCTIONS
  5668. case 'F': {
  5669. struct function *funcp = new_function(optarg);
  5670. /* funcp->name is already set to optarg */
  5671. /* funcp->body is set to NULL. It's a special case. */
  5672. funcp->body_as_string = argv[optind];
  5673. optind++;
  5674. break;
  5675. }
  5676. # endif
  5677. #endif
  5678. case 'n':
  5679. case 'x':
  5680. if (!set_mode('-', opt))
  5681. break;
  5682. default:
  5683. #ifndef BB_VER
  5684. fprintf(stderr, "Usage: sh [FILE]...\n"
  5685. " or: sh -c command [args]...\n\n");
  5686. exit(EXIT_FAILURE);
  5687. #else
  5688. bb_show_usage();
  5689. #endif
  5690. }
  5691. } /* option parsing loop */
  5692. if (!G.root_pid)
  5693. G.root_pid = getpid();
  5694. /* If we are login shell... */
  5695. if (argv[0] && argv[0][0] == '-') {
  5696. FILE *input;
  5697. /* TODO: what should argv be while sourcing /etc/profile? */
  5698. debug_printf("sourcing /etc/profile\n");
  5699. input = fopen_for_read("/etc/profile");
  5700. if (input != NULL) {
  5701. close_on_exec_on(fileno(input));
  5702. block_signals(0); /* 0: called 1st time */
  5703. signal_mask_is_inited = 1;
  5704. parse_and_run_file(input);
  5705. fclose(input);
  5706. }
  5707. /* bash: after sourcing /etc/profile,
  5708. * tries to source (in the given order):
  5709. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  5710. * stopping of first found. --noprofile turns this off.
  5711. * bash also sources ~/.bash_logout on exit.
  5712. * If called as sh, skips .bash_XXX files.
  5713. */
  5714. }
  5715. if (argv[optind]) {
  5716. FILE *input;
  5717. /*
  5718. * "bash <script>" (which is never interactive (unless -i?))
  5719. * sources $BASH_ENV here (without scanning $PATH).
  5720. * If called as sh, does the same but with $ENV.
  5721. */
  5722. debug_printf("running script '%s'\n", argv[optind]);
  5723. G.global_argv = argv + optind;
  5724. G.global_argc = argc - optind;
  5725. input = xfopen_for_read(argv[optind]);
  5726. close_on_exec_on(fileno(input));
  5727. if (!signal_mask_is_inited)
  5728. block_signals(0); /* 0: called 1st time */
  5729. parse_and_run_file(input);
  5730. #if ENABLE_FEATURE_CLEAN_UP
  5731. fclose(input);
  5732. #endif
  5733. goto final_return;
  5734. }
  5735. /* Up to here, shell was non-interactive. Now it may become one.
  5736. * NB: don't forget to (re)run block_signals(0/1) as needed.
  5737. */
  5738. /* A shell is interactive if the '-i' flag was given, or if all of
  5739. * the following conditions are met:
  5740. * no -c command
  5741. * no arguments remaining or the -s flag given
  5742. * standard input is a terminal
  5743. * standard output is a terminal
  5744. * Refer to Posix.2, the description of the 'sh' utility.
  5745. */
  5746. #if ENABLE_HUSH_JOB
  5747. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  5748. G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  5749. debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
  5750. //TODO: "interactive" and "have job control" are two different things.
  5751. //If tcgetpgrp fails here, "have job control" is false, but "interactive"
  5752. //should stay on! Currently, we mix these into one.
  5753. if (G.saved_tty_pgrp >= 0) {
  5754. /* try to dup stdin to high fd#, >= 255 */
  5755. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  5756. if (G_interactive_fd < 0) {
  5757. /* try to dup to any fd */
  5758. G_interactive_fd = dup(STDIN_FILENO);
  5759. if (G_interactive_fd < 0)
  5760. /* give up */
  5761. G_interactive_fd = 0;
  5762. }
  5763. // TODO: track & disallow any attempts of user
  5764. // to (inadvertently) close/redirect it
  5765. }
  5766. }
  5767. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  5768. if (G_interactive_fd) {
  5769. pid_t shell_pgrp;
  5770. /* We are indeed interactive shell, and we will perform
  5771. * job control. Setting up for that. */
  5772. close_on_exec_on(G_interactive_fd);
  5773. /* If we were run as 'hush &', sleep until we are
  5774. * in the foreground (tty pgrp == our pgrp).
  5775. * If we get started under a job aware app (like bash),
  5776. * make sure we are now in charge so we don't fight over
  5777. * who gets the foreground */
  5778. while (1) {
  5779. shell_pgrp = getpgrp();
  5780. G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  5781. if (G.saved_tty_pgrp == shell_pgrp)
  5782. break;
  5783. /* send TTIN to ourself (should stop us) */
  5784. kill(- shell_pgrp, SIGTTIN);
  5785. }
  5786. /* Block some signals */
  5787. block_signals(signal_mask_is_inited);
  5788. /* Set other signals to restore saved_tty_pgrp */
  5789. set_fatal_handlers();
  5790. /* Put ourselves in our own process group */
  5791. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  5792. /* Grab control of the terminal */
  5793. tcsetpgrp(G_interactive_fd, getpid());
  5794. /* -1 is special - makes xfuncs longjmp, not exit
  5795. * (we reset die_sleep = 0 whereever we [v]fork) */
  5796. enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
  5797. } else if (!signal_mask_is_inited) {
  5798. block_signals(0); /* 0: called 1st time */
  5799. } /* else: block_signals(0) was done before */
  5800. #elif ENABLE_HUSH_INTERACTIVE
  5801. /* No job control compiled in, only prompt/line editing */
  5802. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  5803. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  5804. if (G_interactive_fd < 0) {
  5805. /* try to dup to any fd */
  5806. G_interactive_fd = dup(STDIN_FILENO);
  5807. if (G_interactive_fd < 0)
  5808. /* give up */
  5809. G_interactive_fd = 0;
  5810. }
  5811. }
  5812. if (G_interactive_fd) {
  5813. close_on_exec_on(G_interactive_fd);
  5814. block_signals(signal_mask_is_inited);
  5815. } else if (!signal_mask_is_inited) {
  5816. block_signals(0);
  5817. }
  5818. #else
  5819. /* We have interactiveness code disabled */
  5820. if (!signal_mask_is_inited) {
  5821. block_signals(0);
  5822. }
  5823. #endif
  5824. /* bash:
  5825. * if interactive but not a login shell, sources ~/.bashrc
  5826. * (--norc turns this off, --rcfile <file> overrides)
  5827. */
  5828. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  5829. printf("\n\n%s hush - the humble shell\n", bb_banner);
  5830. printf("Enter 'help' for a list of built-in commands.\n\n");
  5831. }
  5832. parse_and_run_file(stdin);
  5833. final_return:
  5834. #if ENABLE_FEATURE_CLEAN_UP
  5835. if (G.cwd != bb_msg_unknown)
  5836. free((char*)G.cwd);
  5837. cur_var = G.top_var->next;
  5838. while (cur_var) {
  5839. struct variable *tmp = cur_var;
  5840. if (!cur_var->max_len)
  5841. free(cur_var->varstr);
  5842. cur_var = cur_var->next;
  5843. free(tmp);
  5844. }
  5845. #endif
  5846. hush_exit(G.last_exitcode);
  5847. }
  5848. #if ENABLE_LASH
  5849. int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  5850. int lash_main(int argc, char **argv)
  5851. {
  5852. //bb_error_msg("lash is deprecated, please use hush instead");
  5853. return hush_main(argc, argv);
  5854. }
  5855. #endif
  5856. /*
  5857. * Built-ins
  5858. */
  5859. static int builtin_true(char **argv UNUSED_PARAM)
  5860. {
  5861. return 0;
  5862. }
  5863. static int builtin_test(char **argv)
  5864. {
  5865. int argc = 0;
  5866. while (*argv) {
  5867. argc++;
  5868. argv++;
  5869. }
  5870. return test_main(argc, argv - argc);
  5871. }
  5872. static int builtin_echo(char **argv)
  5873. {
  5874. int argc = 0;
  5875. while (*argv) {
  5876. argc++;
  5877. argv++;
  5878. }
  5879. return echo_main(argc, argv - argc);
  5880. }
  5881. static int builtin_eval(char **argv)
  5882. {
  5883. int rcode = EXIT_SUCCESS;
  5884. if (*++argv) {
  5885. char *str = expand_strvec_to_string(argv);
  5886. /* bash:
  5887. * eval "echo Hi; done" ("done" is syntax error):
  5888. * "echo Hi" will not execute too.
  5889. */
  5890. parse_and_run_string(str);
  5891. free(str);
  5892. rcode = G.last_exitcode;
  5893. }
  5894. return rcode;
  5895. }
  5896. static int builtin_cd(char **argv)
  5897. {
  5898. const char *newdir = argv[1];
  5899. if (newdir == NULL) {
  5900. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  5901. * bash says "bash: cd: HOME not set" and does nothing
  5902. * (exitcode 1)
  5903. */
  5904. newdir = getenv("HOME") ? : "/";
  5905. }
  5906. if (chdir(newdir)) {
  5907. /* Mimic bash message exactly */
  5908. bb_perror_msg("cd: %s", newdir);
  5909. return EXIT_FAILURE;
  5910. }
  5911. set_cwd();
  5912. return EXIT_SUCCESS;
  5913. }
  5914. static int builtin_exec(char **argv)
  5915. {
  5916. if (*++argv == NULL)
  5917. return EXIT_SUCCESS; /* bash does this */
  5918. {
  5919. #if !BB_MMU
  5920. nommu_save_t dummy;
  5921. #endif
  5922. /* TODO: if exec fails, bash does NOT exit! We do... */
  5923. pseudo_exec_argv(&dummy, argv, 0, NULL);
  5924. /* never returns */
  5925. }
  5926. }
  5927. static int builtin_exit(char **argv)
  5928. {
  5929. debug_printf_exec("%s()\n", __func__);
  5930. /* interactive bash:
  5931. * # trap "echo EEE" EXIT
  5932. * # exit
  5933. * exit
  5934. * There are stopped jobs.
  5935. * (if there are _stopped_ jobs, running ones don't count)
  5936. * # exit
  5937. * exit
  5938. # EEE (then bash exits)
  5939. *
  5940. * we can use G.exiting = -1 as indicator "last cmd was exit"
  5941. */
  5942. /* note: EXIT trap is run by hush_exit */
  5943. if (*++argv == NULL)
  5944. hush_exit(G.last_exitcode);
  5945. /* mimic bash: exit 123abc == exit 255 + error msg */
  5946. xfunc_error_retval = 255;
  5947. /* bash: exit -2 == exit 254, no error msg */
  5948. hush_exit(xatoi(*argv) & 0xff);
  5949. }
  5950. static void print_escaped(const char *s)
  5951. {
  5952. do {
  5953. if (*s != '\'') {
  5954. const char *p;
  5955. p = strchrnul(s, '\'');
  5956. /* print 'xxxx', possibly just '' */
  5957. printf("'%.*s'", (int)(p - s), s);
  5958. if (*p == '\0')
  5959. break;
  5960. s = p;
  5961. }
  5962. /* s points to '; print "'''...'''" */
  5963. putchar('"');
  5964. do putchar('\''); while (*++s == '\'');
  5965. putchar('"');
  5966. } while (*s);
  5967. }
  5968. static int builtin_export(char **argv)
  5969. {
  5970. unsigned opt_unexport;
  5971. if (argv[1] == NULL) {
  5972. char **e = environ;
  5973. if (e) {
  5974. while (*e) {
  5975. #if 0
  5976. puts(*e++);
  5977. #else
  5978. /* ash emits: export VAR='VAL'
  5979. * bash: declare -x VAR="VAL"
  5980. * we follow ash example */
  5981. const char *s = *e++;
  5982. const char *p = strchr(s, '=');
  5983. if (!p) /* wtf? take next variable */
  5984. continue;
  5985. /* export var= */
  5986. printf("export %.*s", (int)(p - s) + 1, s);
  5987. print_escaped(p + 1);
  5988. putchar('\n');
  5989. #endif
  5990. }
  5991. /*fflush(stdout); - done after each builtin anyway */
  5992. }
  5993. return EXIT_SUCCESS;
  5994. }
  5995. #if ENABLE_HUSH_EXPORT_N
  5996. opt_unexport = getopt32(argv, "+n"); /* "+": stop at 1st non-option */
  5997. argv += optind;
  5998. #else
  5999. opt_unexport = 0;
  6000. argv++;
  6001. #endif
  6002. do {
  6003. char *name = *argv;
  6004. /* So far we do not check that name is valid (TODO?) */
  6005. if (strchr(name, '=') == NULL) {
  6006. struct variable *var;
  6007. var = get_local_var(name);
  6008. if (opt_unexport) {
  6009. /* export -n NAME (without =VALUE) */
  6010. if (var) {
  6011. var->flg_export = 0;
  6012. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  6013. unsetenv(name);
  6014. } /* else: export -n NOT_EXISTING_VAR: no-op */
  6015. continue;
  6016. }
  6017. /* export NAME (without =VALUE) */
  6018. if (var) {
  6019. var->flg_export = 1;
  6020. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  6021. putenv(var->varstr);
  6022. continue;
  6023. }
  6024. /* Exporting non-existing variable.
  6025. * bash does not put it in environment,
  6026. * but remembers that it is exported,
  6027. * and does put it in env when it is set later.
  6028. * We just set it to "" and export. */
  6029. name = xasprintf("%s=", name);
  6030. } else {
  6031. /* (Un)exporting NAME=VALUE */
  6032. name = xstrdup(name);
  6033. }
  6034. set_local_var(name,
  6035. /*export:*/ (opt_unexport ? -1 : 1),
  6036. /*readonly:*/ 0
  6037. );
  6038. } while (*++argv);
  6039. return EXIT_SUCCESS;
  6040. }
  6041. static int builtin_trap(char **argv)
  6042. {
  6043. int sig;
  6044. char *new_cmd;
  6045. if (!G.traps)
  6046. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  6047. argv++;
  6048. if (!*argv) {
  6049. int i;
  6050. /* No args: print all trapped */
  6051. for (i = 0; i < NSIG; ++i) {
  6052. if (G.traps[i]) {
  6053. printf("trap -- ");
  6054. print_escaped(G.traps[i]);
  6055. printf(" %s\n", get_signame(i));
  6056. }
  6057. }
  6058. /*fflush(stdout); - done after each builtin anyway */
  6059. return EXIT_SUCCESS;
  6060. }
  6061. new_cmd = NULL;
  6062. /* If first arg is a number: reset all specified signals */
  6063. sig = bb_strtou(*argv, NULL, 10);
  6064. if (errno == 0) {
  6065. int ret;
  6066. process_sig_list:
  6067. ret = EXIT_SUCCESS;
  6068. while (*argv) {
  6069. sig = get_signum(*argv++);
  6070. if (sig < 0 || sig >= NSIG) {
  6071. ret = EXIT_FAILURE;
  6072. /* Mimic bash message exactly */
  6073. bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
  6074. continue;
  6075. }
  6076. free(G.traps[sig]);
  6077. G.traps[sig] = xstrdup(new_cmd);
  6078. debug_printf("trap: setting SIG%s (%i) to '%s'",
  6079. get_signame(sig), sig, G.traps[sig]);
  6080. /* There is no signal for 0 (EXIT) */
  6081. if (sig == 0)
  6082. continue;
  6083. if (new_cmd) {
  6084. sigaddset(&G.blocked_set, sig);
  6085. } else {
  6086. /* There was a trap handler, we are removing it
  6087. * (if sig has non-DFL handling,
  6088. * we don't need to do anything) */
  6089. if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
  6090. continue;
  6091. sigdelset(&G.blocked_set, sig);
  6092. }
  6093. }
  6094. sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
  6095. return ret;
  6096. }
  6097. if (!argv[1]) { /* no second arg */
  6098. bb_error_msg("trap: invalid arguments");
  6099. return EXIT_FAILURE;
  6100. }
  6101. /* First arg is "-": reset all specified to default */
  6102. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  6103. /* Everything else: set arg as signal handler
  6104. * (includes "" case, which ignores signal) */
  6105. if (argv[0][0] == '-') {
  6106. if (argv[0][1] == '\0') { /* "-" */
  6107. /* new_cmd remains NULL: "reset these sigs" */
  6108. goto reset_traps;
  6109. }
  6110. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  6111. argv++;
  6112. }
  6113. /* else: "-something", no special meaning */
  6114. }
  6115. new_cmd = *argv;
  6116. reset_traps:
  6117. argv++;
  6118. goto process_sig_list;
  6119. }
  6120. #if ENABLE_HUSH_JOB
  6121. /* built-in 'fg' and 'bg' handler */
  6122. static int builtin_fg_bg(char **argv)
  6123. {
  6124. int i, jobnum;
  6125. struct pipe *pi;
  6126. if (!G_interactive_fd)
  6127. return EXIT_FAILURE;
  6128. /* If they gave us no args, assume they want the last backgrounded task */
  6129. if (!argv[1]) {
  6130. for (pi = G.job_list; pi; pi = pi->next) {
  6131. if (pi->jobid == G.last_jobid) {
  6132. goto found;
  6133. }
  6134. }
  6135. bb_error_msg("%s: no current job", argv[0]);
  6136. return EXIT_FAILURE;
  6137. }
  6138. if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
  6139. bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
  6140. return EXIT_FAILURE;
  6141. }
  6142. for (pi = G.job_list; pi; pi = pi->next) {
  6143. if (pi->jobid == jobnum) {
  6144. goto found;
  6145. }
  6146. }
  6147. bb_error_msg("%s: %d: no such job", argv[0], jobnum);
  6148. return EXIT_FAILURE;
  6149. found:
  6150. /* TODO: bash prints a string representation
  6151. * of job being foregrounded (like "sleep 1 | cat") */
  6152. if (argv[0][0] == 'f') {
  6153. /* Put the job into the foreground. */
  6154. tcsetpgrp(G_interactive_fd, pi->pgrp);
  6155. }
  6156. /* Restart the processes in the job */
  6157. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  6158. for (i = 0; i < pi->num_cmds; i++) {
  6159. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  6160. pi->cmds[i].is_stopped = 0;
  6161. }
  6162. pi->stopped_cmds = 0;
  6163. i = kill(- pi->pgrp, SIGCONT);
  6164. if (i < 0) {
  6165. if (errno == ESRCH) {
  6166. delete_finished_bg_job(pi);
  6167. return EXIT_SUCCESS;
  6168. }
  6169. bb_perror_msg("kill (SIGCONT)");
  6170. }
  6171. if (argv[0][0] == 'f') {
  6172. remove_bg_job(pi);
  6173. return checkjobs_and_fg_shell(pi);
  6174. }
  6175. return EXIT_SUCCESS;
  6176. }
  6177. #endif
  6178. #if ENABLE_HUSH_HELP
  6179. static int builtin_help(char **argv UNUSED_PARAM)
  6180. {
  6181. const struct built_in_command *x;
  6182. printf("\n"
  6183. "Built-in commands:\n"
  6184. "------------------\n");
  6185. for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
  6186. printf("%s\t%s\n", x->cmd, x->descr);
  6187. }
  6188. printf("\n\n");
  6189. return EXIT_SUCCESS;
  6190. }
  6191. #endif
  6192. #if ENABLE_HUSH_JOB
  6193. static int builtin_jobs(char **argv UNUSED_PARAM)
  6194. {
  6195. struct pipe *job;
  6196. const char *status_string;
  6197. for (job = G.job_list; job; job = job->next) {
  6198. if (job->alive_cmds == job->stopped_cmds)
  6199. status_string = "Stopped";
  6200. else
  6201. status_string = "Running";
  6202. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  6203. }
  6204. return EXIT_SUCCESS;
  6205. }
  6206. #endif
  6207. #if HUSH_DEBUG
  6208. static int builtin_memleak(char **argv UNUSED_PARAM)
  6209. {
  6210. void *p;
  6211. unsigned long l;
  6212. /* Crude attempt to find where "free memory" starts,
  6213. * sans fragmentation. */
  6214. p = malloc(240);
  6215. l = (unsigned long)p;
  6216. free(p);
  6217. p = malloc(3400);
  6218. if (l < (unsigned long)p) l = (unsigned long)p;
  6219. free(p);
  6220. if (!G.memleak_value)
  6221. G.memleak_value = l;
  6222. l -= G.memleak_value;
  6223. if ((long)l < 0)
  6224. l = 0;
  6225. l /= 1024;
  6226. if (l > 127)
  6227. l = 127;
  6228. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  6229. return l;
  6230. }
  6231. #endif
  6232. static int builtin_pwd(char **argv UNUSED_PARAM)
  6233. {
  6234. puts(set_cwd());
  6235. return EXIT_SUCCESS;
  6236. }
  6237. static int builtin_read(char **argv)
  6238. {
  6239. char *string;
  6240. const char *name = "REPLY";
  6241. if (argv[1]) {
  6242. name = argv[1];
  6243. /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
  6244. * and _after_ that_ it will complain */
  6245. if (!is_well_formed_var_name(name, '\0')) {
  6246. /* Mimic bash message */
  6247. bb_error_msg("read: '%s': not a valid identifier", name);
  6248. return 1;
  6249. }
  6250. }
  6251. //TODO: bash unbackslashes input, splits words and puts them in argv[i]
  6252. string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
  6253. return set_local_var(string, 0, 0);
  6254. }
  6255. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  6256. * built-in 'set' handler
  6257. * SUSv3 says:
  6258. * set [-abCefhmnuvx] [-o option] [argument...]
  6259. * set [+abCefhmnuvx] [+o option] [argument...]
  6260. * set -- [argument...]
  6261. * set -o
  6262. * set +o
  6263. * Implementations shall support the options in both their hyphen and
  6264. * plus-sign forms. These options can also be specified as options to sh.
  6265. * Examples:
  6266. * Write out all variables and their values: set
  6267. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  6268. * Turn on the -x and -v options: set -xv
  6269. * Unset all positional parameters: set --
  6270. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  6271. * Set the positional parameters to the expansion of x, even if x expands
  6272. * with a leading '-' or '+': set -- $x
  6273. *
  6274. * So far, we only support "set -- [argument...]" and some of the short names.
  6275. */
  6276. static int builtin_set(char **argv)
  6277. {
  6278. int n;
  6279. char **pp, **g_argv;
  6280. char *arg = *++argv;
  6281. if (arg == NULL) {
  6282. struct variable *e;
  6283. for (e = G.top_var; e; e = e->next)
  6284. puts(e->varstr);
  6285. return EXIT_SUCCESS;
  6286. }
  6287. do {
  6288. if (!strcmp(arg, "--")) {
  6289. ++argv;
  6290. goto set_argv;
  6291. }
  6292. if (arg[0] != '+' && arg[0] != '-')
  6293. break;
  6294. for (n = 1; arg[n]; ++n)
  6295. if (set_mode(arg[0], arg[n]))
  6296. goto error;
  6297. } while ((arg = *++argv) != NULL);
  6298. /* Now argv[0] is 1st argument */
  6299. if (arg == NULL)
  6300. return EXIT_SUCCESS;
  6301. set_argv:
  6302. /* NB: G.global_argv[0] ($0) is never freed/changed */
  6303. g_argv = G.global_argv;
  6304. if (G.global_args_malloced) {
  6305. pp = g_argv;
  6306. while (*++pp)
  6307. free(*pp);
  6308. g_argv[1] = NULL;
  6309. } else {
  6310. G.global_args_malloced = 1;
  6311. pp = xzalloc(sizeof(pp[0]) * 2);
  6312. pp[0] = g_argv[0]; /* retain $0 */
  6313. g_argv = pp;
  6314. }
  6315. /* This realloc's G.global_argv */
  6316. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  6317. n = 1;
  6318. while (*++pp)
  6319. n++;
  6320. G.global_argc = n;
  6321. return EXIT_SUCCESS;
  6322. /* Nothing known, so abort */
  6323. error:
  6324. bb_error_msg("set: %s: invalid option", arg);
  6325. return EXIT_FAILURE;
  6326. }
  6327. static int builtin_shift(char **argv)
  6328. {
  6329. int n = 1;
  6330. if (argv[1]) {
  6331. n = atoi(argv[1]);
  6332. }
  6333. if (n >= 0 && n < G.global_argc) {
  6334. if (G.global_args_malloced) {
  6335. int m = 1;
  6336. while (m <= n)
  6337. free(G.global_argv[m++]);
  6338. }
  6339. G.global_argc -= n;
  6340. memmove(&G.global_argv[1], &G.global_argv[n+1],
  6341. G.global_argc * sizeof(G.global_argv[0]));
  6342. return EXIT_SUCCESS;
  6343. }
  6344. return EXIT_FAILURE;
  6345. }
  6346. static int builtin_source(char **argv)
  6347. {
  6348. FILE *input;
  6349. save_arg_t sv;
  6350. #if ENABLE_HUSH_FUNCTIONS
  6351. smallint sv_flg;
  6352. #endif
  6353. if (*++argv == NULL)
  6354. return EXIT_FAILURE;
  6355. // TODO: search through $PATH is missing
  6356. input = fopen_or_warn(*argv, "r");
  6357. if (!input) {
  6358. /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
  6359. return EXIT_FAILURE;
  6360. }
  6361. close_on_exec_on(fileno(input));
  6362. #if ENABLE_HUSH_FUNCTIONS
  6363. sv_flg = G.flag_return_in_progress;
  6364. /* "we are inside sourced file, ok to use return" */
  6365. G.flag_return_in_progress = -1;
  6366. #endif
  6367. save_and_replace_G_args(&sv, argv);
  6368. parse_and_run_file(input);
  6369. fclose(input);
  6370. restore_G_args(&sv, argv);
  6371. #if ENABLE_HUSH_FUNCTIONS
  6372. G.flag_return_in_progress = sv_flg;
  6373. #endif
  6374. return G.last_exitcode;
  6375. }
  6376. static int builtin_umask(char **argv)
  6377. {
  6378. int rc;
  6379. mode_t mask;
  6380. mask = umask(0);
  6381. if (argv[1]) {
  6382. mode_t old_mask = mask;
  6383. mask ^= 0777;
  6384. rc = bb_parse_mode(argv[1], &mask);
  6385. mask ^= 0777;
  6386. if (rc == 0) {
  6387. mask = old_mask;
  6388. /* bash messages:
  6389. * bash: umask: 'q': invalid symbolic mode operator
  6390. * bash: umask: 999: octal number out of range
  6391. */
  6392. bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
  6393. }
  6394. } else {
  6395. rc = 1;
  6396. /* Mimic bash */
  6397. printf("%04o\n", (unsigned) mask);
  6398. /* fall through and restore mask which we set to 0 */
  6399. }
  6400. umask(mask);
  6401. return !rc; /* rc != 0 - success */
  6402. }
  6403. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  6404. static int builtin_unset(char **argv)
  6405. {
  6406. int ret;
  6407. char var;
  6408. char *arg;
  6409. if (!*++argv)
  6410. return EXIT_SUCCESS;
  6411. var = 0;
  6412. while ((arg = *argv) != NULL && arg[0] == '-') {
  6413. arg++;
  6414. do {
  6415. switch (*arg) {
  6416. case 'v':
  6417. case 'f':
  6418. if (var == 0 || var == *arg) {
  6419. var = *arg;
  6420. break;
  6421. }
  6422. /* else: unset -vf, which is illegal.
  6423. * fall through */
  6424. default:
  6425. bb_error_msg("unset: %s: invalid option", *argv);
  6426. return EXIT_FAILURE;
  6427. }
  6428. } while (*++arg);
  6429. argv++;
  6430. }
  6431. ret = EXIT_SUCCESS;
  6432. while (*argv) {
  6433. if (var != 'f') {
  6434. if (unset_local_var(*argv)) {
  6435. /* unset <nonexistent_var> doesn't fail.
  6436. * Error is when one tries to unset RO var.
  6437. * Message was printed by unset_local_var. */
  6438. ret = EXIT_FAILURE;
  6439. }
  6440. }
  6441. #if ENABLE_HUSH_FUNCTIONS
  6442. else {
  6443. unset_func(*argv);
  6444. }
  6445. #endif
  6446. argv++;
  6447. }
  6448. return ret;
  6449. }
  6450. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  6451. static int builtin_wait(char **argv)
  6452. {
  6453. int ret = EXIT_SUCCESS;
  6454. int status, sig;
  6455. if (*++argv == NULL) {
  6456. /* Don't care about wait results */
  6457. /* Note 1: must wait until there are no more children */
  6458. /* Note 2: must be interruptible */
  6459. /* Examples:
  6460. * $ sleep 3 & sleep 6 & wait
  6461. * [1] 30934 sleep 3
  6462. * [2] 30935 sleep 6
  6463. * [1] Done sleep 3
  6464. * [2] Done sleep 6
  6465. * $ sleep 3 & sleep 6 & wait
  6466. * [1] 30936 sleep 3
  6467. * [2] 30937 sleep 6
  6468. * [1] Done sleep 3
  6469. * ^C <-- after ~4 sec from keyboard
  6470. * $
  6471. */
  6472. sigaddset(&G.blocked_set, SIGCHLD);
  6473. sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
  6474. while (1) {
  6475. checkjobs(NULL);
  6476. if (errno == ECHILD)
  6477. break;
  6478. /* Wait for SIGCHLD or any other signal of interest */
  6479. /* sigtimedwait with infinite timeout: */
  6480. sig = sigwaitinfo(&G.blocked_set, NULL);
  6481. if (sig > 0) {
  6482. sig = check_and_run_traps(sig);
  6483. if (sig && sig != SIGCHLD) { /* see note 2 */
  6484. ret = 128 + sig;
  6485. break;
  6486. }
  6487. }
  6488. }
  6489. sigdelset(&G.blocked_set, SIGCHLD);
  6490. sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
  6491. return ret;
  6492. }
  6493. /* This is probably buggy wrt interruptible-ness */
  6494. while (*argv) {
  6495. pid_t pid = bb_strtou(*argv, NULL, 10);
  6496. if (errno) {
  6497. /* mimic bash message */
  6498. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  6499. return EXIT_FAILURE;
  6500. }
  6501. if (waitpid(pid, &status, 0) == pid) {
  6502. if (WIFSIGNALED(status))
  6503. ret = 128 + WTERMSIG(status);
  6504. else if (WIFEXITED(status))
  6505. ret = WEXITSTATUS(status);
  6506. else /* wtf? */
  6507. ret = EXIT_FAILURE;
  6508. } else {
  6509. bb_perror_msg("wait %s", *argv);
  6510. ret = 127;
  6511. }
  6512. argv++;
  6513. }
  6514. return ret;
  6515. }
  6516. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  6517. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  6518. {
  6519. if (argv[1]) {
  6520. def = bb_strtou(argv[1], NULL, 10);
  6521. if (errno || def < def_min || argv[2]) {
  6522. bb_error_msg("%s: bad arguments", argv[0]);
  6523. def = UINT_MAX;
  6524. }
  6525. }
  6526. return def;
  6527. }
  6528. #endif
  6529. #if ENABLE_HUSH_LOOPS
  6530. static int builtin_break(char **argv)
  6531. {
  6532. unsigned depth;
  6533. if (G.depth_of_loop == 0) {
  6534. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  6535. return EXIT_SUCCESS; /* bash compat */
  6536. }
  6537. G.flag_break_continue++; /* BC_BREAK = 1 */
  6538. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  6539. if (depth == UINT_MAX)
  6540. G.flag_break_continue = BC_BREAK;
  6541. if (G.depth_of_loop < depth)
  6542. G.depth_break_continue = G.depth_of_loop;
  6543. return EXIT_SUCCESS;
  6544. }
  6545. static int builtin_continue(char **argv)
  6546. {
  6547. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  6548. return builtin_break(argv);
  6549. }
  6550. #endif
  6551. #if ENABLE_HUSH_FUNCTIONS
  6552. static int builtin_return(char **argv)
  6553. {
  6554. int rc;
  6555. if (G.flag_return_in_progress != -1) {
  6556. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  6557. return EXIT_FAILURE; /* bash compat */
  6558. }
  6559. G.flag_return_in_progress = 1;
  6560. /* bash:
  6561. * out of range: wraps around at 256, does not error out
  6562. * non-numeric param:
  6563. * f() { false; return qwe; }; f; echo $?
  6564. * bash: return: qwe: numeric argument required <== we do this
  6565. * 255 <== we also do this
  6566. */
  6567. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  6568. return rc;
  6569. }
  6570. #endif