hush.c 201 KB

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