hush.c 248 KB

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