hush.c 248 KB

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