hush.c 321 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714
  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. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (64 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support process substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef O_CLOEXEC
  356. # define O_CLOEXEC 0
  357. #endif
  358. #ifndef F_DUPFD_CLOEXEC
  359. # define F_DUPFD_CLOEXEC F_DUPFD
  360. #endif
  361. #ifndef PIPE_BUF
  362. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  363. #endif
  364. /* So far, all bash compat is controlled by one config option */
  365. /* Separate defines document which part of code implements what */
  366. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  367. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  368. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  369. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  370. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  371. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  372. /* Build knobs */
  373. #define LEAK_HUNTING 0
  374. #define BUILD_AS_NOMMU 0
  375. /* Enable/disable sanity checks. Ok to enable in production,
  376. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  377. * Keeping 1 for now even in released versions.
  378. */
  379. #define HUSH_DEBUG 1
  380. /* Slightly bigger (+200 bytes), but faster hush.
  381. * So far it only enables a trick with counting SIGCHLDs and forks,
  382. * which allows us to do fewer waitpid's.
  383. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  384. * and therefore waitpid will return the same result as last time)
  385. */
  386. #define ENABLE_HUSH_FAST 0
  387. /* TODO: implement simplified code for users which do not need ${var%...} ops
  388. * So far ${var%...} ops are always enabled:
  389. */
  390. #define ENABLE_HUSH_DOLLAR_OPS 1
  391. #if BUILD_AS_NOMMU
  392. # undef BB_MMU
  393. # undef USE_FOR_NOMMU
  394. # undef USE_FOR_MMU
  395. # define BB_MMU 0
  396. # define USE_FOR_NOMMU(...) __VA_ARGS__
  397. # define USE_FOR_MMU(...)
  398. #endif
  399. #include "NUM_APPLETS.h"
  400. #if NUM_APPLETS == 1
  401. /* STANDALONE does not make sense, and won't compile */
  402. # undef CONFIG_FEATURE_SH_STANDALONE
  403. # undef ENABLE_FEATURE_SH_STANDALONE
  404. # undef IF_FEATURE_SH_STANDALONE
  405. # undef IF_NOT_FEATURE_SH_STANDALONE
  406. # define ENABLE_FEATURE_SH_STANDALONE 0
  407. # define IF_FEATURE_SH_STANDALONE(...)
  408. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  409. #endif
  410. #if !ENABLE_HUSH_INTERACTIVE
  411. # undef ENABLE_FEATURE_EDITING
  412. # define ENABLE_FEATURE_EDITING 0
  413. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  414. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  415. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  416. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  417. #endif
  418. /* Do we support ANY keywords? */
  419. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  420. # define HAS_KEYWORDS 1
  421. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  422. # define IF_HAS_NO_KEYWORDS(...)
  423. #else
  424. # define HAS_KEYWORDS 0
  425. # define IF_HAS_KEYWORDS(...)
  426. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  427. #endif
  428. /* If you comment out one of these below, it will be #defined later
  429. * to perform debug printfs to stderr: */
  430. #define debug_printf(...) do {} while (0)
  431. /* Finer-grained debug switches */
  432. #define debug_printf_parse(...) do {} while (0)
  433. #define debug_printf_heredoc(...) do {} while (0)
  434. #define debug_print_tree(a, b) do {} while (0)
  435. #define debug_printf_exec(...) do {} while (0)
  436. #define debug_printf_env(...) do {} while (0)
  437. #define debug_printf_jobs(...) do {} while (0)
  438. #define debug_printf_expand(...) do {} while (0)
  439. #define debug_printf_varexp(...) do {} while (0)
  440. #define debug_printf_glob(...) do {} while (0)
  441. #define debug_printf_redir(...) do {} while (0)
  442. #define debug_printf_list(...) do {} while (0)
  443. #define debug_printf_subst(...) do {} while (0)
  444. #define debug_printf_prompt(...) do {} while (0)
  445. #define debug_printf_clean(...) do {} while (0)
  446. #define ERR_PTR ((void*)(long)1)
  447. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  448. #define _SPECIAL_VARS_STR "_*@$!?#"
  449. #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
  450. #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
  451. #if BASH_PATTERN_SUBST
  452. /* Support / and // replace ops */
  453. /* Note that // is stored as \ in "encoded" string representation */
  454. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  455. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  456. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  457. #else
  458. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  459. # define VAR_SUBST_OPS "%#:-=+?"
  460. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  461. #endif
  462. #define SPECIAL_VAR_SYMBOL_STR "\3"
  463. #define SPECIAL_VAR_SYMBOL 3
  464. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  465. #define SPECIAL_VAR_QUOTED_SVS 1
  466. struct variable;
  467. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  468. /* This supports saving pointers malloced in vfork child,
  469. * to be freed in the parent.
  470. */
  471. #if !BB_MMU
  472. typedef struct nommu_save_t {
  473. struct variable *old_vars;
  474. char **argv;
  475. char **argv_from_re_execing;
  476. } nommu_save_t;
  477. #endif
  478. enum {
  479. RES_NONE = 0,
  480. #if ENABLE_HUSH_IF
  481. RES_IF ,
  482. RES_THEN ,
  483. RES_ELIF ,
  484. RES_ELSE ,
  485. RES_FI ,
  486. #endif
  487. #if ENABLE_HUSH_LOOPS
  488. RES_FOR ,
  489. RES_WHILE ,
  490. RES_UNTIL ,
  491. RES_DO ,
  492. RES_DONE ,
  493. #endif
  494. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  495. RES_IN ,
  496. #endif
  497. #if ENABLE_HUSH_CASE
  498. RES_CASE ,
  499. /* three pseudo-keywords support contrived "case" syntax: */
  500. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  501. RES_MATCH , /* "word)" */
  502. RES_CASE_BODY, /* "this command is inside CASE" */
  503. RES_ESAC ,
  504. #endif
  505. RES_XXXX ,
  506. RES_SNTX
  507. };
  508. typedef struct o_string {
  509. char *data;
  510. int length; /* position where data is appended */
  511. int maxlen;
  512. int o_expflags;
  513. /* At least some part of the string was inside '' or "",
  514. * possibly empty one: word"", wo''rd etc. */
  515. smallint has_quoted_part;
  516. smallint has_empty_slot;
  517. smallint ended_in_ifs;
  518. } o_string;
  519. enum {
  520. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  521. EXP_FLAG_GLOB = 0x2,
  522. /* Protect newly added chars against globbing
  523. * by prepending \ to *, ?, [, \ */
  524. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  525. };
  526. /* Used for initialization: o_string foo = NULL_O_STRING; */
  527. #define NULL_O_STRING { NULL }
  528. #ifndef debug_printf_parse
  529. static const char *const assignment_flag[] = {
  530. "MAYBE_ASSIGNMENT",
  531. "DEFINITELY_ASSIGNMENT",
  532. "NOT_ASSIGNMENT",
  533. "WORD_IS_KEYWORD",
  534. };
  535. #endif
  536. /* We almost can use standard FILE api, but we need an ability to move
  537. * its fd when redirects coincide with it. No api exists for that
  538. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  539. * HFILE is our internal alternative. Only supports reading.
  540. * Since we now can, we incorporate linked list of all opened HFILEs
  541. * into the struct (used to be a separate mini-list).
  542. */
  543. typedef struct HFILE {
  544. char *cur;
  545. char *end;
  546. struct HFILE *next_hfile;
  547. int is_stdin;
  548. int fd;
  549. char buf[1024];
  550. } HFILE;
  551. typedef struct in_str {
  552. const char *p;
  553. int peek_buf[2];
  554. int last_char;
  555. HFILE *file;
  556. } in_str;
  557. /* The descrip member of this structure is only used to make
  558. * debugging output pretty */
  559. static const struct {
  560. int mode;
  561. signed char default_fd;
  562. char descrip[3];
  563. } redir_table[] = {
  564. { O_RDONLY, 0, "<" },
  565. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  566. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  567. { O_CREAT|O_RDWR, 1, "<>" },
  568. { O_RDONLY, 0, "<<" },
  569. /* Should not be needed. Bogus default_fd helps in debugging */
  570. /* { O_RDONLY, 77, "<<" }, */
  571. };
  572. struct redir_struct {
  573. struct redir_struct *next;
  574. char *rd_filename; /* filename */
  575. int rd_fd; /* fd to redirect */
  576. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  577. int rd_dup;
  578. smallint rd_type; /* (enum redir_type) */
  579. /* note: for heredocs, rd_filename contains heredoc delimiter,
  580. * and subsequently heredoc itself; and rd_dup is a bitmask:
  581. * bit 0: do we need to trim leading tabs?
  582. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  583. */
  584. };
  585. typedef enum redir_type {
  586. REDIRECT_INPUT = 0,
  587. REDIRECT_OVERWRITE = 1,
  588. REDIRECT_APPEND = 2,
  589. REDIRECT_IO = 3,
  590. REDIRECT_HEREDOC = 4,
  591. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  592. REDIRFD_CLOSE = -3,
  593. REDIRFD_SYNTAX_ERR = -2,
  594. REDIRFD_TO_FILE = -1,
  595. /* otherwise, rd_fd is redirected to rd_dup */
  596. HEREDOC_SKIPTABS = 1,
  597. HEREDOC_QUOTED = 2,
  598. } redir_type;
  599. struct command {
  600. pid_t pid; /* 0 if exited */
  601. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  602. #if ENABLE_HUSH_LINENO_VAR
  603. unsigned lineno;
  604. #endif
  605. smallint cmd_type; /* CMD_xxx */
  606. #define CMD_NORMAL 0
  607. #define CMD_SUBSHELL 1
  608. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  609. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  610. * "export v=t*"
  611. */
  612. # define CMD_SINGLEWORD_NOGLOB 2
  613. #endif
  614. #if ENABLE_HUSH_FUNCTIONS
  615. # define CMD_FUNCDEF 3
  616. #endif
  617. smalluint cmd_exitcode;
  618. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  619. struct pipe *group;
  620. #if !BB_MMU
  621. char *group_as_string;
  622. #endif
  623. #if ENABLE_HUSH_FUNCTIONS
  624. struct function *child_func;
  625. /* This field is used to prevent a bug here:
  626. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  627. * When we execute "f1() {a;}" cmd, we create new function and clear
  628. * cmd->group, cmd->group_as_string, cmd->argv[0].
  629. * When we execute "f1() {b;}", we notice that f1 exists,
  630. * and that its "parent cmd" struct is still "alive",
  631. * we put those fields back into cmd->xxx
  632. * (struct function has ->parent_cmd ptr to facilitate that).
  633. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  634. * Without this trick, loop would execute a;b;b;b;...
  635. * instead of correct sequence a;b;a;b;...
  636. * When command is freed, it severs the link
  637. * (sets ->child_func->parent_cmd to NULL).
  638. */
  639. #endif
  640. char **argv; /* command name and arguments */
  641. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  642. * and on execution these are substituted with their values.
  643. * Substitution can make _several_ words out of one argv[n]!
  644. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  645. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  646. */
  647. struct redir_struct *redirects; /* I/O redirections */
  648. };
  649. /* Is there anything in this command at all? */
  650. #define IS_NULL_CMD(cmd) \
  651. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  652. struct pipe {
  653. struct pipe *next;
  654. int num_cmds; /* total number of commands in pipe */
  655. int alive_cmds; /* number of commands running (not exited) */
  656. int stopped_cmds; /* number of commands alive, but stopped */
  657. #if ENABLE_HUSH_JOB
  658. unsigned jobid; /* job number */
  659. pid_t pgrp; /* process group ID for the job */
  660. char *cmdtext; /* name of job */
  661. #endif
  662. struct command *cmds; /* array of commands in pipe */
  663. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  664. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  665. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  666. };
  667. typedef enum pipe_style {
  668. PIPE_SEQ = 0,
  669. PIPE_AND = 1,
  670. PIPE_OR = 2,
  671. PIPE_BG = 3,
  672. } pipe_style;
  673. /* Is there anything in this pipe at all? */
  674. #define IS_NULL_PIPE(pi) \
  675. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  676. /* This holds pointers to the various results of parsing */
  677. struct parse_context {
  678. /* linked list of pipes */
  679. struct pipe *list_head;
  680. /* last pipe (being constructed right now) */
  681. struct pipe *pipe;
  682. /* last command in pipe (being constructed right now) */
  683. struct command *command;
  684. /* last redirect in command->redirects list */
  685. struct redir_struct *pending_redirect;
  686. o_string word;
  687. #if !BB_MMU
  688. o_string as_string;
  689. #endif
  690. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  691. #if HAS_KEYWORDS
  692. smallint ctx_res_w;
  693. smallint ctx_inverted; /* "! cmd | cmd" */
  694. #if ENABLE_HUSH_CASE
  695. smallint ctx_dsemicolon; /* ";;" seen */
  696. #endif
  697. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  698. int old_flag;
  699. /* group we are enclosed in:
  700. * example: "if pipe1; pipe2; then pipe3; fi"
  701. * when we see "if" or "then", we malloc and copy current context,
  702. * and make ->stack point to it. then we parse pipeN.
  703. * when closing "then" / fi" / whatever is found,
  704. * we move list_head into ->stack->command->group,
  705. * copy ->stack into current context, and delete ->stack.
  706. * (parsing of { list } and ( list ) doesn't use this method)
  707. */
  708. struct parse_context *stack;
  709. #endif
  710. };
  711. enum {
  712. MAYBE_ASSIGNMENT = 0,
  713. DEFINITELY_ASSIGNMENT = 1,
  714. NOT_ASSIGNMENT = 2,
  715. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  716. WORD_IS_KEYWORD = 3,
  717. };
  718. /* On program start, environ points to initial environment.
  719. * putenv adds new pointers into it, unsetenv removes them.
  720. * Neither of these (de)allocates the strings.
  721. * setenv allocates new strings in malloc space and does putenv,
  722. * and thus setenv is unusable (leaky) for shell's purposes */
  723. #define setenv(...) setenv_is_leaky_dont_use()
  724. struct variable {
  725. struct variable *next;
  726. char *varstr; /* points to "name=" portion */
  727. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  728. uint16_t var_nest_level;
  729. smallint flg_export; /* putenv should be done on this var */
  730. smallint flg_read_only;
  731. };
  732. enum {
  733. BC_BREAK = 1,
  734. BC_CONTINUE = 2,
  735. };
  736. #if ENABLE_HUSH_FUNCTIONS
  737. struct function {
  738. struct function *next;
  739. char *name;
  740. struct command *parent_cmd;
  741. struct pipe *body;
  742. # if !BB_MMU
  743. char *body_as_string;
  744. # endif
  745. };
  746. #endif
  747. /* set -/+o OPT support. (TODO: make it optional)
  748. * bash supports the following opts:
  749. * allexport off
  750. * braceexpand on
  751. * emacs on
  752. * errexit off
  753. * errtrace off
  754. * functrace off
  755. * hashall on
  756. * histexpand off
  757. * history on
  758. * ignoreeof off
  759. * interactive-comments on
  760. * keyword off
  761. * monitor on
  762. * noclobber off
  763. * noexec off
  764. * noglob off
  765. * nolog off
  766. * notify off
  767. * nounset off
  768. * onecmd off
  769. * physical off
  770. * pipefail off
  771. * posix off
  772. * privileged off
  773. * verbose off
  774. * vi off
  775. * xtrace off
  776. */
  777. static const char o_opt_strings[] ALIGN1 =
  778. "pipefail\0"
  779. "noexec\0"
  780. "errexit\0"
  781. #if ENABLE_HUSH_MODE_X
  782. "xtrace\0"
  783. #endif
  784. ;
  785. enum {
  786. OPT_O_PIPEFAIL,
  787. OPT_O_NOEXEC,
  788. OPT_O_ERREXIT,
  789. #if ENABLE_HUSH_MODE_X
  790. OPT_O_XTRACE,
  791. #endif
  792. NUM_OPT_O
  793. };
  794. /* "Globals" within this file */
  795. /* Sorted roughly by size (smaller offsets == smaller code) */
  796. struct globals {
  797. /* interactive_fd != 0 means we are an interactive shell.
  798. * If we are, then saved_tty_pgrp can also be != 0, meaning
  799. * that controlling tty is available. With saved_tty_pgrp == 0,
  800. * job control still works, but terminal signals
  801. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  802. * process groups can only be created with "cmd &".
  803. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  804. * to give tty to the foreground process group,
  805. * and will take it back when the group is stopped (^Z)
  806. * or killed (^C).
  807. */
  808. #if ENABLE_HUSH_INTERACTIVE
  809. /* 'interactive_fd' is a fd# open to ctty, if we have one
  810. * _AND_ if we decided to act interactively */
  811. int interactive_fd;
  812. const char *PS1;
  813. IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
  814. # define G_interactive_fd (G.interactive_fd)
  815. #else
  816. # define G_interactive_fd 0
  817. #endif
  818. #if ENABLE_FEATURE_EDITING
  819. line_input_t *line_input_state;
  820. #endif
  821. pid_t root_pid;
  822. pid_t root_ppid;
  823. pid_t last_bg_pid;
  824. #if ENABLE_HUSH_RANDOM_SUPPORT
  825. random_t random_gen;
  826. #endif
  827. #if ENABLE_HUSH_JOB
  828. int run_list_level;
  829. unsigned last_jobid;
  830. pid_t saved_tty_pgrp;
  831. struct pipe *job_list;
  832. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  833. #else
  834. # define G_saved_tty_pgrp 0
  835. #endif
  836. /* How deeply are we in context where "set -e" is ignored */
  837. int errexit_depth;
  838. /* "set -e" rules (do we follow them correctly?):
  839. * Exit if pipe, list, or compound command exits with a non-zero status.
  840. * Shell does not exit if failed command is part of condition in
  841. * if/while, part of && or || list except the last command, any command
  842. * in a pipe but the last, or if the command's return value is being
  843. * inverted with !. If a compound command other than a subshell returns a
  844. * non-zero status because a command failed while -e was being ignored, the
  845. * shell does not exit. A trap on ERR, if set, is executed before the shell
  846. * exits [ERR is a bashism].
  847. *
  848. * If a compound command or function executes in a context where -e is
  849. * ignored, none of the commands executed within are affected by the -e
  850. * setting. If a compound command or function sets -e while executing in a
  851. * context where -e is ignored, that setting does not have any effect until
  852. * the compound command or the command containing the function call completes.
  853. */
  854. char o_opt[NUM_OPT_O];
  855. #if ENABLE_HUSH_MODE_X
  856. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  857. #else
  858. # define G_x_mode 0
  859. #endif
  860. #if ENABLE_HUSH_INTERACTIVE
  861. smallint promptmode; /* 0: PS1, 1: PS2 */
  862. #endif
  863. smallint flag_SIGINT;
  864. #if ENABLE_HUSH_LOOPS
  865. smallint flag_break_continue;
  866. #endif
  867. #if ENABLE_HUSH_FUNCTIONS
  868. /* 0: outside of a function (or sourced file)
  869. * -1: inside of a function, ok to use return builtin
  870. * 1: return is invoked, skip all till end of func
  871. */
  872. smallint flag_return_in_progress;
  873. # define G_flag_return_in_progress (G.flag_return_in_progress)
  874. #else
  875. # define G_flag_return_in_progress 0
  876. #endif
  877. smallint exiting; /* used to prevent EXIT trap recursion */
  878. /* These support $?, $#, and $1 */
  879. smalluint last_exitcode;
  880. smalluint expand_exitcode;
  881. smalluint last_bg_pid_exitcode;
  882. #if ENABLE_HUSH_SET
  883. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  884. smalluint global_args_malloced;
  885. # define G_global_args_malloced (G.global_args_malloced)
  886. #else
  887. # define G_global_args_malloced 0
  888. #endif
  889. /* how many non-NULL argv's we have. NB: $# + 1 */
  890. int global_argc;
  891. char **global_argv;
  892. #if !BB_MMU
  893. char *argv0_for_re_execing;
  894. #endif
  895. #if ENABLE_HUSH_LOOPS
  896. unsigned depth_break_continue;
  897. unsigned depth_of_loop;
  898. #endif
  899. #if ENABLE_HUSH_GETOPTS
  900. unsigned getopt_count;
  901. #endif
  902. const char *ifs;
  903. char *ifs_whitespace; /* = G.ifs or malloced */
  904. const char *cwd;
  905. struct variable *top_var;
  906. char **expanded_assignments;
  907. struct variable **shadowed_vars_pp;
  908. unsigned var_nest_level;
  909. #if ENABLE_HUSH_FUNCTIONS
  910. # if ENABLE_HUSH_LOCAL
  911. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  912. # endif
  913. struct function *top_func;
  914. #endif
  915. /* Signal and trap handling */
  916. #if ENABLE_HUSH_FAST
  917. unsigned count_SIGCHLD;
  918. unsigned handled_SIGCHLD;
  919. smallint we_have_children;
  920. #endif
  921. #if ENABLE_HUSH_LINENO_VAR
  922. unsigned lineno;
  923. char *lineno_var;
  924. #endif
  925. HFILE *HFILE_list;
  926. /* Which signals have non-DFL handler (even with no traps set)?
  927. * Set at the start to:
  928. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  929. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  930. * The rest is cleared right before execv syscalls.
  931. * Other than these two times, never modified.
  932. */
  933. unsigned special_sig_mask;
  934. #if ENABLE_HUSH_JOB
  935. unsigned fatal_sig_mask;
  936. # define G_fatal_sig_mask (G.fatal_sig_mask)
  937. #else
  938. # define G_fatal_sig_mask 0
  939. #endif
  940. #if ENABLE_HUSH_TRAP
  941. char **traps; /* char *traps[NSIG] */
  942. # define G_traps G.traps
  943. #else
  944. # define G_traps ((char**)NULL)
  945. #endif
  946. sigset_t pending_set;
  947. #if ENABLE_HUSH_MEMLEAK
  948. unsigned long memleak_value;
  949. #endif
  950. #if ENABLE_HUSH_MODE_X
  951. unsigned x_mode_depth;
  952. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  953. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  954. * for all subsequent output.
  955. */
  956. int x_mode_fd;
  957. o_string x_mode_buf;
  958. #endif
  959. #if HUSH_DEBUG >= 2
  960. int debug_indent;
  961. #endif
  962. struct sigaction sa;
  963. #if ENABLE_FEATURE_EDITING
  964. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  965. #endif
  966. };
  967. #define G (*ptr_to_globals)
  968. /* Not #defining name to G.name - this quickly gets unwieldy
  969. * (too many defines). Also, I actually prefer to see when a variable
  970. * is global, thus "G." prefix is a useful hint */
  971. #define INIT_G() do { \
  972. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  973. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  974. sigfillset(&G.sa.sa_mask); \
  975. G.sa.sa_flags = SA_RESTART; \
  976. } while (0)
  977. /* Function prototypes for builtins */
  978. static int builtin_cd(char **argv) FAST_FUNC;
  979. #if ENABLE_HUSH_ECHO
  980. static int builtin_echo(char **argv) FAST_FUNC;
  981. #endif
  982. static int builtin_eval(char **argv) FAST_FUNC;
  983. static int builtin_exec(char **argv) FAST_FUNC;
  984. static int builtin_exit(char **argv) FAST_FUNC;
  985. #if ENABLE_HUSH_EXPORT
  986. static int builtin_export(char **argv) FAST_FUNC;
  987. #endif
  988. #if ENABLE_HUSH_READONLY
  989. static int builtin_readonly(char **argv) FAST_FUNC;
  990. #endif
  991. #if ENABLE_HUSH_JOB
  992. static int builtin_fg_bg(char **argv) FAST_FUNC;
  993. static int builtin_jobs(char **argv) FAST_FUNC;
  994. #endif
  995. #if ENABLE_HUSH_GETOPTS
  996. static int builtin_getopts(char **argv) FAST_FUNC;
  997. #endif
  998. #if ENABLE_HUSH_HELP
  999. static int builtin_help(char **argv) FAST_FUNC;
  1000. #endif
  1001. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1002. static int builtin_history(char **argv) FAST_FUNC;
  1003. #endif
  1004. #if ENABLE_HUSH_LOCAL
  1005. static int builtin_local(char **argv) FAST_FUNC;
  1006. #endif
  1007. #if ENABLE_HUSH_MEMLEAK
  1008. static int builtin_memleak(char **argv) FAST_FUNC;
  1009. #endif
  1010. #if ENABLE_HUSH_PRINTF
  1011. static int builtin_printf(char **argv) FAST_FUNC;
  1012. #endif
  1013. static int builtin_pwd(char **argv) FAST_FUNC;
  1014. #if ENABLE_HUSH_READ
  1015. static int builtin_read(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_SET
  1018. static int builtin_set(char **argv) FAST_FUNC;
  1019. #endif
  1020. static int builtin_shift(char **argv) FAST_FUNC;
  1021. static int builtin_source(char **argv) FAST_FUNC;
  1022. #if ENABLE_HUSH_TEST || BASH_TEST2
  1023. static int builtin_test(char **argv) FAST_FUNC;
  1024. #endif
  1025. #if ENABLE_HUSH_TRAP
  1026. static int builtin_trap(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if ENABLE_HUSH_TYPE
  1029. static int builtin_type(char **argv) FAST_FUNC;
  1030. #endif
  1031. #if ENABLE_HUSH_TIMES
  1032. static int builtin_times(char **argv) FAST_FUNC;
  1033. #endif
  1034. static int builtin_true(char **argv) FAST_FUNC;
  1035. #if ENABLE_HUSH_UMASK
  1036. static int builtin_umask(char **argv) FAST_FUNC;
  1037. #endif
  1038. #if ENABLE_HUSH_UNSET
  1039. static int builtin_unset(char **argv) FAST_FUNC;
  1040. #endif
  1041. #if ENABLE_HUSH_KILL
  1042. static int builtin_kill(char **argv) FAST_FUNC;
  1043. #endif
  1044. #if ENABLE_HUSH_WAIT
  1045. static int builtin_wait(char **argv) FAST_FUNC;
  1046. #endif
  1047. #if ENABLE_HUSH_LOOPS
  1048. static int builtin_break(char **argv) FAST_FUNC;
  1049. static int builtin_continue(char **argv) FAST_FUNC;
  1050. #endif
  1051. #if ENABLE_HUSH_FUNCTIONS
  1052. static int builtin_return(char **argv) FAST_FUNC;
  1053. #endif
  1054. /* Table of built-in functions. They can be forked or not, depending on
  1055. * context: within pipes, they fork. As simple commands, they do not.
  1056. * When used in non-forking context, they can change global variables
  1057. * in the parent shell process. If forked, of course they cannot.
  1058. * For example, 'unset foo | whatever' will parse and run, but foo will
  1059. * still be set at the end. */
  1060. struct built_in_command {
  1061. const char *b_cmd;
  1062. int (*b_function)(char **argv) FAST_FUNC;
  1063. #if ENABLE_HUSH_HELP
  1064. const char *b_descr;
  1065. # define BLTIN(cmd, func, help) { cmd, func, help }
  1066. #else
  1067. # define BLTIN(cmd, func, help) { cmd, func }
  1068. #endif
  1069. };
  1070. static const struct built_in_command bltins1[] = {
  1071. BLTIN("." , builtin_source , "Run commands in file"),
  1072. BLTIN(":" , builtin_true , NULL),
  1073. #if ENABLE_HUSH_JOB
  1074. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1075. #endif
  1076. #if ENABLE_HUSH_LOOPS
  1077. BLTIN("break" , builtin_break , "Exit loop"),
  1078. #endif
  1079. BLTIN("cd" , builtin_cd , "Change directory"),
  1080. #if ENABLE_HUSH_LOOPS
  1081. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1082. #endif
  1083. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1084. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1085. BLTIN("exit" , builtin_exit , NULL),
  1086. #if ENABLE_HUSH_EXPORT
  1087. BLTIN("export" , builtin_export , "Set environment variables"),
  1088. #endif
  1089. #if ENABLE_HUSH_JOB
  1090. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1091. #endif
  1092. #if ENABLE_HUSH_GETOPTS
  1093. BLTIN("getopts" , builtin_getopts , NULL),
  1094. #endif
  1095. #if ENABLE_HUSH_HELP
  1096. BLTIN("help" , builtin_help , NULL),
  1097. #endif
  1098. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1099. BLTIN("history" , builtin_history , "Show history"),
  1100. #endif
  1101. #if ENABLE_HUSH_JOB
  1102. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1103. #endif
  1104. #if ENABLE_HUSH_KILL
  1105. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1106. #endif
  1107. #if ENABLE_HUSH_LOCAL
  1108. BLTIN("local" , builtin_local , "Set local variables"),
  1109. #endif
  1110. #if ENABLE_HUSH_MEMLEAK
  1111. BLTIN("memleak" , builtin_memleak , NULL),
  1112. #endif
  1113. #if ENABLE_HUSH_READ
  1114. BLTIN("read" , builtin_read , "Input into variable"),
  1115. #endif
  1116. #if ENABLE_HUSH_READONLY
  1117. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1118. #endif
  1119. #if ENABLE_HUSH_FUNCTIONS
  1120. BLTIN("return" , builtin_return , "Return from function"),
  1121. #endif
  1122. #if ENABLE_HUSH_SET
  1123. BLTIN("set" , builtin_set , "Set positional parameters"),
  1124. #endif
  1125. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1126. #if BASH_SOURCE
  1127. BLTIN("source" , builtin_source , NULL),
  1128. #endif
  1129. #if ENABLE_HUSH_TIMES
  1130. BLTIN("times" , builtin_times , NULL),
  1131. #endif
  1132. #if ENABLE_HUSH_TRAP
  1133. BLTIN("trap" , builtin_trap , "Trap signals"),
  1134. #endif
  1135. BLTIN("true" , builtin_true , NULL),
  1136. #if ENABLE_HUSH_TYPE
  1137. BLTIN("type" , builtin_type , "Show command type"),
  1138. #endif
  1139. #if ENABLE_HUSH_ULIMIT
  1140. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1141. #endif
  1142. #if ENABLE_HUSH_UMASK
  1143. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1144. #endif
  1145. #if ENABLE_HUSH_UNSET
  1146. BLTIN("unset" , builtin_unset , "Unset variables"),
  1147. #endif
  1148. #if ENABLE_HUSH_WAIT
  1149. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1150. #endif
  1151. };
  1152. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1153. * (it's cheaper to run an external program in this case):
  1154. */
  1155. static const struct built_in_command bltins2[] = {
  1156. #if ENABLE_HUSH_TEST
  1157. BLTIN("[" , builtin_test , NULL),
  1158. #endif
  1159. #if BASH_TEST2
  1160. BLTIN("[[" , builtin_test , NULL),
  1161. #endif
  1162. #if ENABLE_HUSH_ECHO
  1163. BLTIN("echo" , builtin_echo , NULL),
  1164. #endif
  1165. #if ENABLE_HUSH_PRINTF
  1166. BLTIN("printf" , builtin_printf , NULL),
  1167. #endif
  1168. BLTIN("pwd" , builtin_pwd , NULL),
  1169. #if ENABLE_HUSH_TEST
  1170. BLTIN("test" , builtin_test , NULL),
  1171. #endif
  1172. };
  1173. /* Debug printouts.
  1174. */
  1175. #if HUSH_DEBUG >= 2
  1176. /* prevent disasters with G.debug_indent < 0 */
  1177. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1178. # define debug_enter() (G.debug_indent++)
  1179. # define debug_leave() (G.debug_indent--)
  1180. #else
  1181. # define indent() ((void)0)
  1182. # define debug_enter() ((void)0)
  1183. # define debug_leave() ((void)0)
  1184. #endif
  1185. #ifndef debug_printf
  1186. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1187. #endif
  1188. #ifndef debug_printf_parse
  1189. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1190. #endif
  1191. #ifndef debug_printf_heredoc
  1192. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1193. #endif
  1194. #ifndef debug_printf_exec
  1195. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1196. #endif
  1197. #ifndef debug_printf_env
  1198. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1199. #endif
  1200. #ifndef debug_printf_jobs
  1201. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1202. # define DEBUG_JOBS 1
  1203. #else
  1204. # define DEBUG_JOBS 0
  1205. #endif
  1206. #ifndef debug_printf_expand
  1207. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1208. # define DEBUG_EXPAND 1
  1209. #else
  1210. # define DEBUG_EXPAND 0
  1211. #endif
  1212. #ifndef debug_printf_varexp
  1213. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1214. #endif
  1215. #ifndef debug_printf_glob
  1216. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. # define DEBUG_GLOB 1
  1218. #else
  1219. # define DEBUG_GLOB 0
  1220. #endif
  1221. #ifndef debug_printf_redir
  1222. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. #endif
  1224. #ifndef debug_printf_list
  1225. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. #endif
  1227. #ifndef debug_printf_subst
  1228. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. #endif
  1230. #ifndef debug_printf_prompt
  1231. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1232. #endif
  1233. #ifndef debug_printf_clean
  1234. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1235. # define DEBUG_CLEAN 1
  1236. #else
  1237. # define DEBUG_CLEAN 0
  1238. #endif
  1239. #if DEBUG_EXPAND
  1240. static void debug_print_strings(const char *prefix, char **vv)
  1241. {
  1242. indent();
  1243. fdprintf(2, "%s:\n", prefix);
  1244. while (*vv)
  1245. fdprintf(2, " '%s'\n", *vv++);
  1246. }
  1247. #else
  1248. # define debug_print_strings(prefix, vv) ((void)0)
  1249. #endif
  1250. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1251. */
  1252. #if LEAK_HUNTING
  1253. static void *xxmalloc(int lineno, size_t size)
  1254. {
  1255. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1256. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1257. return ptr;
  1258. }
  1259. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1260. {
  1261. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1262. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1263. return ptr;
  1264. }
  1265. static char *xxstrdup(int lineno, const char *str)
  1266. {
  1267. char *ptr = xstrdup(str);
  1268. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1269. return ptr;
  1270. }
  1271. static void xxfree(void *ptr)
  1272. {
  1273. fdprintf(2, "free %p\n", ptr);
  1274. free(ptr);
  1275. }
  1276. # define xmalloc(s) xxmalloc(__LINE__, s)
  1277. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1278. # define xstrdup(s) xxstrdup(__LINE__, s)
  1279. # define free(p) xxfree(p)
  1280. #endif
  1281. /* Syntax and runtime errors. They always abort scripts.
  1282. * In interactive use they usually discard unparsed and/or unexecuted commands
  1283. * and return to the prompt.
  1284. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1285. */
  1286. #if HUSH_DEBUG < 2
  1287. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1288. # define syntax_error(lineno, msg) syntax_error(msg)
  1289. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1290. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1291. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1292. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1293. #endif
  1294. static void die_if_script(void)
  1295. {
  1296. if (!G_interactive_fd) {
  1297. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1298. xfunc_error_retval = G.last_exitcode;
  1299. xfunc_die();
  1300. }
  1301. }
  1302. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1303. {
  1304. va_list p;
  1305. #if HUSH_DEBUG >= 2
  1306. bb_error_msg("hush.c:%u", lineno);
  1307. #endif
  1308. va_start(p, fmt);
  1309. bb_verror_msg(fmt, p, NULL);
  1310. va_end(p);
  1311. die_if_script();
  1312. }
  1313. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1314. {
  1315. if (msg)
  1316. bb_error_msg("syntax error: %s", msg);
  1317. else
  1318. bb_error_msg("syntax error");
  1319. die_if_script();
  1320. }
  1321. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1322. {
  1323. bb_error_msg("syntax error at '%s'", msg);
  1324. die_if_script();
  1325. }
  1326. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1327. {
  1328. bb_error_msg("syntax error: unterminated %s", s);
  1329. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1330. // die_if_script();
  1331. }
  1332. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1333. {
  1334. char msg[2] = { ch, '\0' };
  1335. syntax_error_unterm_str(lineno, msg);
  1336. }
  1337. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1338. {
  1339. char msg[2];
  1340. msg[0] = ch;
  1341. msg[1] = '\0';
  1342. #if HUSH_DEBUG >= 2
  1343. bb_error_msg("hush.c:%u", lineno);
  1344. #endif
  1345. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1346. die_if_script();
  1347. }
  1348. #if HUSH_DEBUG < 2
  1349. # undef msg_and_die_if_script
  1350. # undef syntax_error
  1351. # undef syntax_error_at
  1352. # undef syntax_error_unterm_ch
  1353. # undef syntax_error_unterm_str
  1354. # undef syntax_error_unexpected_ch
  1355. #else
  1356. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1357. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1358. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1359. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1360. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1361. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1362. #endif
  1363. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1364. static void cmdedit_update_prompt(void);
  1365. #else
  1366. # define cmdedit_update_prompt() ((void)0)
  1367. #endif
  1368. /* Utility functions
  1369. */
  1370. /* Replace each \x with x in place, return ptr past NUL. */
  1371. static char *unbackslash(char *src)
  1372. {
  1373. char *dst = src = strchrnul(src, '\\');
  1374. while (1) {
  1375. if (*src == '\\') {
  1376. src++;
  1377. if (*src != '\0') {
  1378. /* \x -> x */
  1379. *dst++ = *src++;
  1380. continue;
  1381. }
  1382. /* else: "\<nul>". Do not delete this backslash.
  1383. * Testcase: eval 'echo ok\'
  1384. */
  1385. *dst++ = '\\';
  1386. /* fallthrough */
  1387. }
  1388. if ((*dst++ = *src++) == '\0')
  1389. break;
  1390. }
  1391. return dst;
  1392. }
  1393. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1394. {
  1395. int i;
  1396. unsigned count1;
  1397. unsigned count2;
  1398. char **v;
  1399. v = strings;
  1400. count1 = 0;
  1401. if (v) {
  1402. while (*v) {
  1403. count1++;
  1404. v++;
  1405. }
  1406. }
  1407. count2 = 0;
  1408. v = add;
  1409. while (*v) {
  1410. count2++;
  1411. v++;
  1412. }
  1413. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1414. v[count1 + count2] = NULL;
  1415. i = count2;
  1416. while (--i >= 0)
  1417. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1418. return v;
  1419. }
  1420. #if LEAK_HUNTING
  1421. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1422. {
  1423. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1424. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1425. return ptr;
  1426. }
  1427. #define add_strings_to_strings(strings, add, need_to_dup) \
  1428. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1429. #endif
  1430. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1431. static char **add_string_to_strings(char **strings, char *add)
  1432. {
  1433. char *v[2];
  1434. v[0] = add;
  1435. v[1] = NULL;
  1436. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1437. }
  1438. #if LEAK_HUNTING
  1439. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1440. {
  1441. char **ptr = add_string_to_strings(strings, add);
  1442. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1443. return ptr;
  1444. }
  1445. #define add_string_to_strings(strings, add) \
  1446. xx_add_string_to_strings(__LINE__, strings, add)
  1447. #endif
  1448. static void free_strings(char **strings)
  1449. {
  1450. char **v;
  1451. if (!strings)
  1452. return;
  1453. v = strings;
  1454. while (*v) {
  1455. free(*v);
  1456. v++;
  1457. }
  1458. free(strings);
  1459. }
  1460. static int dup_CLOEXEC(int fd, int avoid_fd)
  1461. {
  1462. int newfd;
  1463. repeat:
  1464. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1465. if (newfd >= 0) {
  1466. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1467. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1468. } else { /* newfd < 0 */
  1469. if (errno == EBUSY)
  1470. goto repeat;
  1471. if (errno == EINTR)
  1472. goto repeat;
  1473. }
  1474. return newfd;
  1475. }
  1476. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1477. {
  1478. int newfd;
  1479. repeat:
  1480. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1481. if (newfd < 0) {
  1482. if (errno == EBUSY)
  1483. goto repeat;
  1484. if (errno == EINTR)
  1485. goto repeat;
  1486. /* fd was not open? */
  1487. if (errno == EBADF)
  1488. return fd;
  1489. xfunc_die();
  1490. }
  1491. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1492. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1493. close(fd);
  1494. return newfd;
  1495. }
  1496. /* Manipulating HFILEs */
  1497. static HFILE *hfopen(const char *name)
  1498. {
  1499. HFILE *fp;
  1500. int fd;
  1501. fd = STDIN_FILENO;
  1502. if (name) {
  1503. fd = open(name, O_RDONLY | O_CLOEXEC);
  1504. if (fd < 0)
  1505. return NULL;
  1506. if (O_CLOEXEC == 0) /* ancient libc */
  1507. close_on_exec_on(fd);
  1508. }
  1509. fp = xmalloc(sizeof(*fp));
  1510. fp->is_stdin = (name == NULL);
  1511. fp->fd = fd;
  1512. fp->cur = fp->end = fp->buf;
  1513. fp->next_hfile = G.HFILE_list;
  1514. G.HFILE_list = fp;
  1515. return fp;
  1516. }
  1517. static void hfclose(HFILE *fp)
  1518. {
  1519. HFILE **pp = &G.HFILE_list;
  1520. while (*pp) {
  1521. HFILE *cur = *pp;
  1522. if (cur == fp) {
  1523. *pp = cur->next_hfile;
  1524. break;
  1525. }
  1526. pp = &cur->next_hfile;
  1527. }
  1528. if (fp->fd >= 0)
  1529. close(fp->fd);
  1530. free(fp);
  1531. }
  1532. static int refill_HFILE_and_getc(HFILE *fp)
  1533. {
  1534. int n;
  1535. if (fp->fd < 0) {
  1536. /* Already saw EOF */
  1537. return EOF;
  1538. }
  1539. /* Try to buffer more input */
  1540. fp->cur = fp->buf;
  1541. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1542. if (n < 0) {
  1543. bb_perror_msg("read error");
  1544. n = 0;
  1545. }
  1546. fp->end = fp->buf + n;
  1547. if (n == 0) {
  1548. /* EOF/error */
  1549. close(fp->fd);
  1550. fp->fd = -1;
  1551. return EOF;
  1552. }
  1553. return (unsigned char)(*fp->cur++);
  1554. }
  1555. /* Inlined for common case of non-empty buffer.
  1556. */
  1557. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1558. {
  1559. if (fp->cur < fp->end)
  1560. return (unsigned char)(*fp->cur++);
  1561. /* Buffer empty */
  1562. return refill_HFILE_and_getc(fp);
  1563. }
  1564. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1565. {
  1566. HFILE *fl = G.HFILE_list;
  1567. while (fl) {
  1568. if (fd == fl->fd) {
  1569. /* We use it only on script files, they are all CLOEXEC */
  1570. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1571. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1572. return 1; /* "found and moved" */
  1573. }
  1574. fl = fl->next_hfile;
  1575. }
  1576. #if ENABLE_HUSH_MODE_X
  1577. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1578. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1579. return 1; /* "found and moved" */
  1580. }
  1581. #endif
  1582. return 0; /* "not in the list" */
  1583. }
  1584. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1585. static void close_all_HFILE_list(void)
  1586. {
  1587. HFILE *fl = G.HFILE_list;
  1588. while (fl) {
  1589. /* hfclose would also free HFILE object.
  1590. * It is disastrous if we share memory with a vforked parent.
  1591. * I'm not sure we never come here after vfork.
  1592. * Therefore just close fd, nothing more.
  1593. *
  1594. * ">" instead of ">=": we don't close fd#0,
  1595. * interactive shell uses hfopen(NULL) as stdin input
  1596. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1597. * If we'd close it here, then e.g. interactive "set | sort"
  1598. * with NOFORKed sort, would have sort's input fd closed.
  1599. */
  1600. if (fl->fd > 0)
  1601. /*hfclose(fl); - unsafe */
  1602. close(fl->fd);
  1603. fl = fl->next_hfile;
  1604. }
  1605. }
  1606. #endif
  1607. static int fd_in_HFILEs(int fd)
  1608. {
  1609. HFILE *fl = G.HFILE_list;
  1610. while (fl) {
  1611. if (fl->fd == fd)
  1612. return 1;
  1613. fl = fl->next_hfile;
  1614. }
  1615. return 0;
  1616. }
  1617. /* Helpers for setting new $n and restoring them back
  1618. */
  1619. typedef struct save_arg_t {
  1620. char *sv_argv0;
  1621. char **sv_g_argv;
  1622. int sv_g_argc;
  1623. IF_HUSH_SET(smallint sv_g_malloced;)
  1624. } save_arg_t;
  1625. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1626. {
  1627. sv->sv_argv0 = argv[0];
  1628. sv->sv_g_argv = G.global_argv;
  1629. sv->sv_g_argc = G.global_argc;
  1630. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1631. argv[0] = G.global_argv[0]; /* retain $0 */
  1632. G.global_argv = argv;
  1633. IF_HUSH_SET(G.global_args_malloced = 0;)
  1634. G.global_argc = 1 + string_array_len(argv + 1);
  1635. }
  1636. static void restore_G_args(save_arg_t *sv, char **argv)
  1637. {
  1638. #if ENABLE_HUSH_SET
  1639. if (G.global_args_malloced) {
  1640. /* someone ran "set -- arg1 arg2 ...", undo */
  1641. char **pp = G.global_argv;
  1642. while (*++pp) /* note: does not free $0 */
  1643. free(*pp);
  1644. free(G.global_argv);
  1645. }
  1646. #endif
  1647. argv[0] = sv->sv_argv0;
  1648. G.global_argv = sv->sv_g_argv;
  1649. G.global_argc = sv->sv_g_argc;
  1650. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1651. }
  1652. /* Basic theory of signal handling in shell
  1653. * ========================================
  1654. * This does not describe what hush does, rather, it is current understanding
  1655. * what it _should_ do. If it doesn't, it's a bug.
  1656. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1657. *
  1658. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1659. * is finished or backgrounded. It is the same in interactive and
  1660. * non-interactive shells, and is the same regardless of whether
  1661. * a user trap handler is installed or a shell special one is in effect.
  1662. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1663. * backgrounds (i.e. stops) or kills all members of currently running
  1664. * pipe.
  1665. *
  1666. * Wait builtin is interruptible by signals for which user trap is set
  1667. * or by SIGINT in interactive shell.
  1668. *
  1669. * Trap handlers will execute even within trap handlers. (right?)
  1670. *
  1671. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1672. * except for handlers set to '' (empty string).
  1673. *
  1674. * If job control is off, backgrounded commands ("cmd &")
  1675. * have SIGINT, SIGQUIT set to SIG_IGN.
  1676. *
  1677. * Commands which are run in command substitution ("`cmd`")
  1678. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1679. *
  1680. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1681. * by the shell from its parent.
  1682. *
  1683. * Signals which differ from SIG_DFL action
  1684. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1685. *
  1686. * SIGQUIT: ignore
  1687. * SIGTERM (interactive): ignore
  1688. * SIGHUP (interactive):
  1689. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1690. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1691. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1692. * that all pipe members are stopped. Try this in bash:
  1693. * while :; do :; done - ^Z does not background it
  1694. * (while :; do :; done) - ^Z backgrounds it
  1695. * SIGINT (interactive): wait for last pipe, ignore the rest
  1696. * of the command line, show prompt. NB: ^C does not send SIGINT
  1697. * to interactive shell while shell is waiting for a pipe,
  1698. * since shell is bg'ed (is not in foreground process group).
  1699. * Example 1: this waits 5 sec, but does not execute ls:
  1700. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1701. * Example 2: this does not wait and does not execute ls:
  1702. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1703. * Example 3: this does not wait 5 sec, but executes ls:
  1704. * "sleep 5; ls -l" + press ^C
  1705. * Example 4: this does not wait and does not execute ls:
  1706. * "sleep 5 & wait; ls -l" + press ^C
  1707. *
  1708. * (What happens to signals which are IGN on shell start?)
  1709. * (What happens with signal mask on shell start?)
  1710. *
  1711. * Old implementation
  1712. * ==================
  1713. * We use in-kernel pending signal mask to determine which signals were sent.
  1714. * We block all signals which we don't want to take action immediately,
  1715. * i.e. we block all signals which need to have special handling as described
  1716. * above, and all signals which have traps set.
  1717. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1718. * and act on them.
  1719. *
  1720. * unsigned special_sig_mask: a mask of such "special" signals
  1721. * sigset_t blocked_set: current blocked signal set
  1722. *
  1723. * "trap - SIGxxx":
  1724. * clear bit in blocked_set unless it is also in special_sig_mask
  1725. * "trap 'cmd' SIGxxx":
  1726. * set bit in blocked_set (even if 'cmd' is '')
  1727. * after [v]fork, if we plan to be a shell:
  1728. * unblock signals with special interactive handling
  1729. * (child shell is not interactive),
  1730. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1731. * after [v]fork, if we plan to exec:
  1732. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1733. * Restore blocked signal set to one inherited by shell just prior to exec.
  1734. *
  1735. * Note: as a result, we do not use signal handlers much. The only uses
  1736. * are to count SIGCHLDs
  1737. * and to restore tty pgrp on signal-induced exit.
  1738. *
  1739. * Note 2 (compat):
  1740. * Standard says "When a subshell is entered, traps that are not being ignored
  1741. * are set to the default actions". bash interprets it so that traps which
  1742. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1743. *
  1744. * Problem: the above approach makes it unwieldy to catch signals while
  1745. * we are in read builtin, or while we read commands from stdin:
  1746. * masked signals are not visible!
  1747. *
  1748. * New implementation
  1749. * ==================
  1750. * We record each signal we are interested in by installing signal handler
  1751. * for them - a bit like emulating kernel pending signal mask in userspace.
  1752. * We are interested in: signals which need to have special handling
  1753. * as described above, and all signals which have traps set.
  1754. * Signals are recorded in pending_set.
  1755. * After each pipe execution, we extract any pending signals
  1756. * and act on them.
  1757. *
  1758. * unsigned special_sig_mask: a mask of shell-special signals.
  1759. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1760. * char *traps[sig] if trap for sig is set (even if it's '').
  1761. * sigset_t pending_set: set of sigs we received.
  1762. *
  1763. * "trap - SIGxxx":
  1764. * if sig is in special_sig_mask, set handler back to:
  1765. * record_pending_signo, or to IGN if it's a tty stop signal
  1766. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1767. * else: set handler back to SIG_DFL
  1768. * "trap 'cmd' SIGxxx":
  1769. * set handler to record_pending_signo.
  1770. * "trap '' SIGxxx":
  1771. * set handler to SIG_IGN.
  1772. * after [v]fork, if we plan to be a shell:
  1773. * set signals with special interactive handling to SIG_DFL
  1774. * (because child shell is not interactive),
  1775. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1776. * after [v]fork, if we plan to exec:
  1777. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1778. *
  1779. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1780. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1781. *
  1782. * Note (compat):
  1783. * Standard says "When a subshell is entered, traps that are not being ignored
  1784. * are set to the default actions". bash interprets it so that traps which
  1785. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1786. */
  1787. enum {
  1788. SPECIAL_INTERACTIVE_SIGS = 0
  1789. | (1 << SIGTERM)
  1790. | (1 << SIGINT)
  1791. | (1 << SIGHUP)
  1792. ,
  1793. SPECIAL_JOBSTOP_SIGS = 0
  1794. #if ENABLE_HUSH_JOB
  1795. | (1 << SIGTTIN)
  1796. | (1 << SIGTTOU)
  1797. | (1 << SIGTSTP)
  1798. #endif
  1799. ,
  1800. };
  1801. static void record_pending_signo(int sig)
  1802. {
  1803. sigaddset(&G.pending_set, sig);
  1804. #if ENABLE_HUSH_FAST
  1805. if (sig == SIGCHLD) {
  1806. G.count_SIGCHLD++;
  1807. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1808. }
  1809. #endif
  1810. }
  1811. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1812. {
  1813. struct sigaction old_sa;
  1814. /* We could use signal() to install handlers... almost:
  1815. * except that we need to mask ALL signals while handlers run.
  1816. * I saw signal nesting in strace, race window isn't small.
  1817. * SA_RESTART is also needed, but in Linux, signal()
  1818. * sets SA_RESTART too.
  1819. */
  1820. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1821. /* sigfillset(&G.sa.sa_mask); - already done */
  1822. /* G.sa.sa_flags = SA_RESTART; - already done */
  1823. G.sa.sa_handler = handler;
  1824. sigaction(sig, &G.sa, &old_sa);
  1825. return old_sa.sa_handler;
  1826. }
  1827. static void hush_exit(int exitcode) NORETURN;
  1828. static void restore_ttypgrp_and__exit(void) NORETURN;
  1829. static void restore_ttypgrp_and__exit(void)
  1830. {
  1831. /* xfunc has failed! die die die */
  1832. /* no EXIT traps, this is an escape hatch! */
  1833. G.exiting = 1;
  1834. hush_exit(xfunc_error_retval);
  1835. }
  1836. #if ENABLE_HUSH_JOB
  1837. /* Needed only on some libc:
  1838. * It was observed that on exit(), fgetc'ed buffered data
  1839. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1840. * With the net effect that even after fork(), not vfork(),
  1841. * exit() in NOEXECed applet in "sh SCRIPT":
  1842. * noexec_applet_here
  1843. * echo END_OF_SCRIPT
  1844. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1845. * This makes "echo END_OF_SCRIPT" executed twice.
  1846. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1847. * and in `cmd` handling.
  1848. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1849. */
  1850. static void fflush_and__exit(void) NORETURN;
  1851. static void fflush_and__exit(void)
  1852. {
  1853. fflush_all();
  1854. _exit(xfunc_error_retval);
  1855. }
  1856. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1857. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1858. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1859. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1860. /* Restores tty foreground process group, and exits.
  1861. * May be called as signal handler for fatal signal
  1862. * (will resend signal to itself, producing correct exit state)
  1863. * or called directly with -EXITCODE.
  1864. * We also call it if xfunc is exiting.
  1865. */
  1866. static void sigexit(int sig) NORETURN;
  1867. static void sigexit(int sig)
  1868. {
  1869. /* Careful: we can end up here after [v]fork. Do not restore
  1870. * tty pgrp then, only top-level shell process does that */
  1871. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1872. /* Disable all signals: job control, SIGPIPE, etc.
  1873. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1874. */
  1875. sigprocmask_allsigs(SIG_BLOCK);
  1876. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1877. }
  1878. /* Not a signal, just exit */
  1879. if (sig <= 0)
  1880. _exit(- sig);
  1881. kill_myself_with_sig(sig); /* does not return */
  1882. }
  1883. #else
  1884. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1885. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1886. #endif
  1887. static sighandler_t pick_sighandler(unsigned sig)
  1888. {
  1889. sighandler_t handler = SIG_DFL;
  1890. if (sig < sizeof(unsigned)*8) {
  1891. unsigned sigmask = (1 << sig);
  1892. #if ENABLE_HUSH_JOB
  1893. /* is sig fatal? */
  1894. if (G_fatal_sig_mask & sigmask)
  1895. handler = sigexit;
  1896. else
  1897. #endif
  1898. /* sig has special handling? */
  1899. if (G.special_sig_mask & sigmask) {
  1900. handler = record_pending_signo;
  1901. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1902. * in order to ignore them: they will be raised
  1903. * in an endless loop when we try to do some
  1904. * terminal ioctls! We do have to _ignore_ these.
  1905. */
  1906. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1907. handler = SIG_IGN;
  1908. }
  1909. }
  1910. return handler;
  1911. }
  1912. /* Restores tty foreground process group, and exits. */
  1913. static void hush_exit(int exitcode)
  1914. {
  1915. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1916. save_history(G.line_input_state);
  1917. #endif
  1918. fflush_all();
  1919. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1920. char *argv[3];
  1921. /* argv[0] is unused */
  1922. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1923. argv[2] = NULL;
  1924. G.exiting = 1; /* prevent EXIT trap recursion */
  1925. /* Note: G_traps[0] is not cleared!
  1926. * "trap" will still show it, if executed
  1927. * in the handler */
  1928. builtin_eval(argv);
  1929. }
  1930. #if ENABLE_FEATURE_CLEAN_UP
  1931. {
  1932. struct variable *cur_var;
  1933. if (G.cwd != bb_msg_unknown)
  1934. free((char*)G.cwd);
  1935. cur_var = G.top_var;
  1936. while (cur_var) {
  1937. struct variable *tmp = cur_var;
  1938. if (!cur_var->max_len)
  1939. free(cur_var->varstr);
  1940. cur_var = cur_var->next;
  1941. free(tmp);
  1942. }
  1943. }
  1944. #endif
  1945. fflush_all();
  1946. #if ENABLE_HUSH_JOB
  1947. sigexit(- (exitcode & 0xff));
  1948. #else
  1949. _exit(exitcode);
  1950. #endif
  1951. }
  1952. //TODO: return a mask of ALL handled sigs?
  1953. static int check_and_run_traps(void)
  1954. {
  1955. int last_sig = 0;
  1956. while (1) {
  1957. int sig;
  1958. if (sigisemptyset(&G.pending_set))
  1959. break;
  1960. sig = 0;
  1961. do {
  1962. sig++;
  1963. if (sigismember(&G.pending_set, sig)) {
  1964. sigdelset(&G.pending_set, sig);
  1965. goto got_sig;
  1966. }
  1967. } while (sig < NSIG);
  1968. break;
  1969. got_sig:
  1970. if (G_traps && G_traps[sig]) {
  1971. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1972. if (G_traps[sig][0]) {
  1973. /* We have user-defined handler */
  1974. smalluint save_rcode;
  1975. char *argv[3];
  1976. /* argv[0] is unused */
  1977. argv[1] = xstrdup(G_traps[sig]);
  1978. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1979. argv[2] = NULL;
  1980. save_rcode = G.last_exitcode;
  1981. builtin_eval(argv);
  1982. free(argv[1]);
  1983. //FIXME: shouldn't it be set to 128 + sig instead?
  1984. G.last_exitcode = save_rcode;
  1985. last_sig = sig;
  1986. } /* else: "" trap, ignoring signal */
  1987. continue;
  1988. }
  1989. /* not a trap: special action */
  1990. switch (sig) {
  1991. case SIGINT:
  1992. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  1993. G.flag_SIGINT = 1;
  1994. last_sig = sig;
  1995. break;
  1996. #if ENABLE_HUSH_JOB
  1997. case SIGHUP: {
  1998. //TODO: why are we doing this? ash and dash don't do this,
  1999. //they have no handler for SIGHUP at all,
  2000. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2001. struct pipe *job;
  2002. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2003. /* bash is observed to signal whole process groups,
  2004. * not individual processes */
  2005. for (job = G.job_list; job; job = job->next) {
  2006. if (job->pgrp <= 0)
  2007. continue;
  2008. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2009. if (kill(- job->pgrp, SIGHUP) == 0)
  2010. kill(- job->pgrp, SIGCONT);
  2011. }
  2012. sigexit(SIGHUP);
  2013. }
  2014. #endif
  2015. #if ENABLE_HUSH_FAST
  2016. case SIGCHLD:
  2017. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2018. G.count_SIGCHLD++;
  2019. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2020. /* Note:
  2021. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2022. * This simplifies wait builtin a bit.
  2023. */
  2024. break;
  2025. #endif
  2026. default: /* ignored: */
  2027. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2028. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2029. /* Note:
  2030. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2031. * Example: wait is not interrupted by TERM
  2032. * in interactive shell, because TERM is ignored.
  2033. */
  2034. break;
  2035. }
  2036. }
  2037. return last_sig;
  2038. }
  2039. static const char *get_cwd(int force)
  2040. {
  2041. if (force || G.cwd == NULL) {
  2042. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2043. * we must not try to free(bb_msg_unknown) */
  2044. if (G.cwd == bb_msg_unknown)
  2045. G.cwd = NULL;
  2046. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2047. if (!G.cwd)
  2048. G.cwd = bb_msg_unknown;
  2049. }
  2050. return G.cwd;
  2051. }
  2052. /*
  2053. * Shell and environment variable support
  2054. */
  2055. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2056. {
  2057. struct variable **pp;
  2058. struct variable *cur;
  2059. pp = &G.top_var;
  2060. while ((cur = *pp) != NULL) {
  2061. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2062. return pp;
  2063. pp = &cur->next;
  2064. }
  2065. return NULL;
  2066. }
  2067. static const char* FAST_FUNC get_local_var_value(const char *name)
  2068. {
  2069. struct variable **vpp;
  2070. unsigned len = strlen(name);
  2071. if (G.expanded_assignments) {
  2072. char **cpp = G.expanded_assignments;
  2073. while (*cpp) {
  2074. char *cp = *cpp;
  2075. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2076. return cp + len + 1;
  2077. cpp++;
  2078. }
  2079. }
  2080. vpp = get_ptr_to_local_var(name, len);
  2081. if (vpp)
  2082. return (*vpp)->varstr + len + 1;
  2083. if (strcmp(name, "PPID") == 0)
  2084. return utoa(G.root_ppid);
  2085. // bash compat: UID? EUID?
  2086. #if ENABLE_HUSH_RANDOM_SUPPORT
  2087. if (strcmp(name, "RANDOM") == 0)
  2088. return utoa(next_random(&G.random_gen));
  2089. #endif
  2090. return NULL;
  2091. }
  2092. static void handle_changed_special_names(const char *name, unsigned name_len)
  2093. {
  2094. if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2095. && name_len == 3 && name[0] == 'P' && name[1] == 'S'
  2096. ) {
  2097. cmdedit_update_prompt();
  2098. return;
  2099. }
  2100. if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
  2101. && name_len == 6
  2102. ) {
  2103. #if ENABLE_HUSH_LINENO_VAR
  2104. if (strncmp(name, "LINENO", 6) == 0) {
  2105. G.lineno_var = NULL;
  2106. return;
  2107. }
  2108. #endif
  2109. #if ENABLE_HUSH_GETOPTS
  2110. if (strncmp(name, "OPTIND", 6) == 0) {
  2111. G.getopt_count = 0;
  2112. return;
  2113. }
  2114. #endif
  2115. }
  2116. }
  2117. /* str holds "NAME=VAL" and is expected to be malloced.
  2118. * We take ownership of it.
  2119. */
  2120. #define SETFLAG_EXPORT (1 << 0)
  2121. #define SETFLAG_UNEXPORT (1 << 1)
  2122. #define SETFLAG_MAKE_RO (1 << 2)
  2123. #define SETFLAG_VARLVL_SHIFT 3
  2124. static int set_local_var(char *str, unsigned flags)
  2125. {
  2126. struct variable **cur_pp;
  2127. struct variable *cur;
  2128. char *free_me = NULL;
  2129. char *eq_sign;
  2130. int name_len;
  2131. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2132. eq_sign = strchr(str, '=');
  2133. if (HUSH_DEBUG && !eq_sign)
  2134. bb_error_msg_and_die("BUG in setvar");
  2135. name_len = eq_sign - str + 1; /* including '=' */
  2136. cur_pp = &G.top_var;
  2137. while ((cur = *cur_pp) != NULL) {
  2138. if (strncmp(cur->varstr, str, name_len) != 0) {
  2139. cur_pp = &cur->next;
  2140. continue;
  2141. }
  2142. /* We found an existing var with this name */
  2143. if (cur->flg_read_only) {
  2144. bb_error_msg("%s: readonly variable", str);
  2145. free(str);
  2146. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2147. //but export per se succeeds (does put the var in env). We don't mimic that.
  2148. return -1;
  2149. }
  2150. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2151. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2152. *eq_sign = '\0';
  2153. unsetenv(str);
  2154. *eq_sign = '=';
  2155. }
  2156. if (cur->var_nest_level < local_lvl) {
  2157. /* bash 3.2.33(1) and exported vars:
  2158. * # export z=z
  2159. * # f() { local z=a; env | grep ^z; }
  2160. * # f
  2161. * z=a
  2162. * # env | grep ^z
  2163. * z=z
  2164. */
  2165. if (cur->flg_export)
  2166. flags |= SETFLAG_EXPORT;
  2167. /* New variable is local ("local VAR=VAL" or
  2168. * "VAR=VAL cmd")
  2169. * and existing one is global, or local
  2170. * on a lower level that new one.
  2171. * Remove it from global variable list:
  2172. */
  2173. *cur_pp = cur->next;
  2174. if (G.shadowed_vars_pp) {
  2175. /* Save in "shadowed" list */
  2176. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2177. cur->flg_export ? "exported " : "",
  2178. cur->varstr, cur->var_nest_level, str, local_lvl
  2179. );
  2180. cur->next = *G.shadowed_vars_pp;
  2181. *G.shadowed_vars_pp = cur;
  2182. } else {
  2183. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2184. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2185. cur->flg_export ? "exported " : "",
  2186. cur->varstr, cur->var_nest_level, str, local_lvl
  2187. );
  2188. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2189. free_me = cur->varstr; /* then free it later */
  2190. free(cur);
  2191. }
  2192. break;
  2193. }
  2194. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2195. debug_printf_env("assignement '%s' does not change anything\n", str);
  2196. free_and_exp:
  2197. free(str);
  2198. goto exp;
  2199. }
  2200. /* Replace the value in the found "struct variable" */
  2201. if (cur->max_len != 0) {
  2202. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2203. /* This one is from startup env, reuse space */
  2204. debug_printf_env("reusing startup env for '%s'\n", str);
  2205. strcpy(cur->varstr, str);
  2206. goto free_and_exp;
  2207. }
  2208. /* Can't reuse */
  2209. cur->max_len = 0;
  2210. goto set_str_and_exp;
  2211. }
  2212. /* max_len == 0 signifies "malloced" var, which we can
  2213. * (and have to) free. But we can't free(cur->varstr) here:
  2214. * if cur->flg_export is 1, it is in the environment.
  2215. * We should either unsetenv+free, or wait until putenv,
  2216. * then putenv(new)+free(old).
  2217. */
  2218. free_me = cur->varstr;
  2219. goto set_str_and_exp;
  2220. }
  2221. /* Not found or shadowed - create new variable struct */
  2222. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2223. cur = xzalloc(sizeof(*cur));
  2224. cur->var_nest_level = local_lvl;
  2225. cur->next = *cur_pp;
  2226. *cur_pp = cur;
  2227. set_str_and_exp:
  2228. cur->varstr = str;
  2229. exp:
  2230. #if !BB_MMU || ENABLE_HUSH_READONLY
  2231. if (flags & SETFLAG_MAKE_RO) {
  2232. cur->flg_read_only = 1;
  2233. }
  2234. #endif
  2235. if (flags & SETFLAG_EXPORT)
  2236. cur->flg_export = 1;
  2237. if (cur->flg_export) {
  2238. if (flags & SETFLAG_UNEXPORT) {
  2239. cur->flg_export = 0;
  2240. /* unsetenv was already done */
  2241. } else {
  2242. int i;
  2243. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2244. i = putenv(cur->varstr);
  2245. /* only now we can free old exported malloced string */
  2246. free(free_me);
  2247. return i;
  2248. }
  2249. }
  2250. free(free_me);
  2251. handle_changed_special_names(cur->varstr, name_len - 1);
  2252. return 0;
  2253. }
  2254. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2255. {
  2256. char *var = xasprintf("%s=%s", name, val);
  2257. set_local_var(var, /*flag:*/ 0);
  2258. }
  2259. /* Used at startup and after each cd */
  2260. static void set_pwd_var(unsigned flag)
  2261. {
  2262. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2263. }
  2264. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2265. static int unset_local_var_len(const char *name, int name_len)
  2266. {
  2267. struct variable *cur;
  2268. struct variable **cur_pp;
  2269. cur_pp = &G.top_var;
  2270. while ((cur = *cur_pp) != NULL) {
  2271. if (strncmp(cur->varstr, name, name_len) == 0
  2272. && cur->varstr[name_len] == '='
  2273. ) {
  2274. if (cur->flg_read_only) {
  2275. bb_error_msg("%s: readonly variable", name);
  2276. return EXIT_FAILURE;
  2277. }
  2278. *cur_pp = cur->next;
  2279. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2280. bb_unsetenv(cur->varstr);
  2281. if (!cur->max_len)
  2282. free(cur->varstr);
  2283. free(cur);
  2284. break;
  2285. }
  2286. cur_pp = &cur->next;
  2287. }
  2288. /* Handle "unset PS1" et al even if did not find the variable to unset */
  2289. handle_changed_special_names(name, name_len);
  2290. return EXIT_SUCCESS;
  2291. }
  2292. static int unset_local_var(const char *name)
  2293. {
  2294. return unset_local_var_len(name, strlen(name));
  2295. }
  2296. #endif
  2297. /*
  2298. * Helpers for "var1=val1 var2=val2 cmd" feature
  2299. */
  2300. static void add_vars(struct variable *var)
  2301. {
  2302. struct variable *next;
  2303. while (var) {
  2304. next = var->next;
  2305. var->next = G.top_var;
  2306. G.top_var = var;
  2307. if (var->flg_export) {
  2308. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2309. putenv(var->varstr);
  2310. } else {
  2311. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2312. }
  2313. var = next;
  2314. }
  2315. }
  2316. /* We put strings[i] into variable table and possibly putenv them.
  2317. * If variable is read only, we can free the strings[i]
  2318. * which attempts to overwrite it.
  2319. * The strings[] vector itself is freed.
  2320. */
  2321. static void set_vars_and_save_old(char **strings)
  2322. {
  2323. char **s;
  2324. if (!strings)
  2325. return;
  2326. s = strings;
  2327. while (*s) {
  2328. struct variable *var_p;
  2329. struct variable **var_pp;
  2330. char *eq;
  2331. eq = strchr(*s, '=');
  2332. if (HUSH_DEBUG && !eq)
  2333. bb_error_msg_and_die("BUG in varexp4");
  2334. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2335. if (var_pp) {
  2336. var_p = *var_pp;
  2337. if (var_p->flg_read_only) {
  2338. char **p;
  2339. bb_error_msg("%s: readonly variable", *s);
  2340. /*
  2341. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2342. * If VAR is readonly, leaving it in the list
  2343. * after asssignment error (msg above)
  2344. * causes doubled error message later, on unset.
  2345. */
  2346. debug_printf_env("removing/freeing '%s' element\n", *s);
  2347. free(*s);
  2348. p = s;
  2349. do { *p = p[1]; p++; } while (*p);
  2350. goto next;
  2351. }
  2352. /* below, set_local_var() with nest level will
  2353. * "shadow" (remove) this variable from
  2354. * global linked list.
  2355. */
  2356. }
  2357. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2358. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2359. s++;
  2360. next: ;
  2361. }
  2362. free(strings);
  2363. }
  2364. /*
  2365. * Unicode helper
  2366. */
  2367. static void reinit_unicode_for_hush(void)
  2368. {
  2369. /* Unicode support should be activated even if LANG is set
  2370. * _during_ shell execution, not only if it was set when
  2371. * shell was started. Therefore, re-check LANG every time:
  2372. */
  2373. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2374. || ENABLE_UNICODE_USING_LOCALE
  2375. ) {
  2376. const char *s = get_local_var_value("LC_ALL");
  2377. if (!s) s = get_local_var_value("LC_CTYPE");
  2378. if (!s) s = get_local_var_value("LANG");
  2379. reinit_unicode(s);
  2380. }
  2381. }
  2382. /*
  2383. * in_str support (strings, and "strings" read from files).
  2384. */
  2385. #if ENABLE_HUSH_INTERACTIVE
  2386. /* To test correct lineedit/interactive behavior, type from command line:
  2387. * echo $P\
  2388. * \
  2389. * AT\
  2390. * H\
  2391. * \
  2392. * It exercises a lot of corner cases.
  2393. */
  2394. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2395. static void cmdedit_update_prompt(void)
  2396. {
  2397. G.PS1 = get_local_var_value("PS1");
  2398. if (G.PS1 == NULL)
  2399. G.PS1 = "";
  2400. G.PS2 = get_local_var_value("PS2");
  2401. if (G.PS2 == NULL)
  2402. G.PS2 = "";
  2403. }
  2404. # endif
  2405. static const char *setup_prompt_string(void)
  2406. {
  2407. const char *prompt_str;
  2408. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2409. IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
  2410. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
  2411. if (G.promptmode == 0) { /* PS1 */
  2412. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  2413. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2414. free((char*)G.PS1);
  2415. /* bash uses $PWD value, even if it is set by user.
  2416. * It uses current dir only if PWD is unset.
  2417. * We always use current dir. */
  2418. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2419. }
  2420. prompt_str = G.PS1;
  2421. }
  2422. debug_printf("prompt_str '%s'\n", prompt_str);
  2423. return prompt_str;
  2424. }
  2425. static int get_user_input(struct in_str *i)
  2426. {
  2427. int r;
  2428. const char *prompt_str;
  2429. prompt_str = setup_prompt_string();
  2430. # if ENABLE_FEATURE_EDITING
  2431. for (;;) {
  2432. reinit_unicode_for_hush();
  2433. if (G.flag_SIGINT) {
  2434. /* There was ^C'ed, make it look prettier: */
  2435. bb_putchar('\n');
  2436. G.flag_SIGINT = 0;
  2437. }
  2438. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2439. * only after <Enter>. (^C works immediately) */
  2440. r = read_line_input(G.line_input_state, prompt_str,
  2441. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2442. );
  2443. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2444. if (r == 0)
  2445. raise(SIGINT);
  2446. check_and_run_traps();
  2447. if (r != 0 && !G.flag_SIGINT)
  2448. break;
  2449. /* ^C or SIGINT: repeat */
  2450. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2451. write(STDOUT_FILENO, "^C", 2);
  2452. G.last_exitcode = 128 + SIGINT;
  2453. }
  2454. if (r < 0) {
  2455. /* EOF/error detected */
  2456. i->p = NULL;
  2457. i->peek_buf[0] = r = EOF;
  2458. return r;
  2459. }
  2460. i->p = G.user_input_buf;
  2461. return (unsigned char)*i->p++;
  2462. # else
  2463. for (;;) {
  2464. G.flag_SIGINT = 0;
  2465. if (i->last_char == '\0' || i->last_char == '\n') {
  2466. /* Why check_and_run_traps here? Try this interactively:
  2467. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2468. * $ <[enter], repeatedly...>
  2469. * Without check_and_run_traps, handler never runs.
  2470. */
  2471. check_and_run_traps();
  2472. fputs(prompt_str, stdout);
  2473. }
  2474. fflush_all();
  2475. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2476. r = hfgetc(i->file);
  2477. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2478. * no ^C masking happens during fgetc, no special code for ^C:
  2479. * it generates SIGINT as usual.
  2480. */
  2481. check_and_run_traps();
  2482. if (G.flag_SIGINT)
  2483. G.last_exitcode = 128 + SIGINT;
  2484. if (r != '\0')
  2485. break;
  2486. }
  2487. return r;
  2488. # endif
  2489. }
  2490. /* This is the magic location that prints prompts
  2491. * and gets data back from the user */
  2492. static int fgetc_interactive(struct in_str *i)
  2493. {
  2494. int ch;
  2495. /* If it's interactive stdin, get new line. */
  2496. if (G_interactive_fd && i->file->is_stdin) {
  2497. /* Returns first char (or EOF), the rest is in i->p[] */
  2498. ch = get_user_input(i);
  2499. G.promptmode = 1; /* PS2 */
  2500. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2501. } else {
  2502. /* Not stdin: script file, sourced file, etc */
  2503. do ch = hfgetc(i->file); while (ch == '\0');
  2504. }
  2505. return ch;
  2506. }
  2507. #else
  2508. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2509. {
  2510. int ch;
  2511. do ch = hfgetc(i->file); while (ch == '\0');
  2512. return ch;
  2513. }
  2514. #endif /* INTERACTIVE */
  2515. static int i_getch(struct in_str *i)
  2516. {
  2517. int ch;
  2518. if (!i->file) {
  2519. /* string-based in_str */
  2520. ch = (unsigned char)*i->p;
  2521. if (ch != '\0') {
  2522. i->p++;
  2523. i->last_char = ch;
  2524. return ch;
  2525. }
  2526. return EOF;
  2527. }
  2528. /* FILE-based in_str */
  2529. #if ENABLE_FEATURE_EDITING
  2530. /* This can be stdin, check line editing char[] buffer */
  2531. if (i->p && *i->p != '\0') {
  2532. ch = (unsigned char)*i->p++;
  2533. goto out;
  2534. }
  2535. #endif
  2536. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2537. ch = i->peek_buf[0];
  2538. if (ch != 0) {
  2539. int ch2 = i->peek_buf[1];
  2540. i->peek_buf[0] = ch2;
  2541. if (ch2 == 0) /* very likely, avoid redundant write */
  2542. goto out;
  2543. i->peek_buf[1] = 0;
  2544. goto out;
  2545. }
  2546. ch = fgetc_interactive(i);
  2547. out:
  2548. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2549. i->last_char = ch;
  2550. #if ENABLE_HUSH_LINENO_VAR
  2551. if (ch == '\n') {
  2552. G.lineno++;
  2553. debug_printf_parse("G.lineno++ = %u\n", G.lineno);
  2554. }
  2555. #endif
  2556. return ch;
  2557. }
  2558. static int i_peek(struct in_str *i)
  2559. {
  2560. int ch;
  2561. if (!i->file) {
  2562. /* string-based in_str */
  2563. /* Doesn't report EOF on NUL. None of the callers care. */
  2564. return (unsigned char)*i->p;
  2565. }
  2566. /* FILE-based in_str */
  2567. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2568. /* This can be stdin, check line editing char[] buffer */
  2569. if (i->p && *i->p != '\0')
  2570. return (unsigned char)*i->p;
  2571. #endif
  2572. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2573. ch = i->peek_buf[0];
  2574. if (ch != 0)
  2575. return ch;
  2576. /* Need to get a new char */
  2577. ch = fgetc_interactive(i);
  2578. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2579. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2580. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2581. if (i->p) {
  2582. i->p -= 1;
  2583. return ch;
  2584. }
  2585. #endif
  2586. i->peek_buf[0] = ch;
  2587. /*i->peek_buf[1] = 0; - already is */
  2588. return ch;
  2589. }
  2590. /* Only ever called if i_peek() was called, and did not return EOF.
  2591. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2592. * not end-of-line. Therefore we never need to read a new editing line here.
  2593. */
  2594. static int i_peek2(struct in_str *i)
  2595. {
  2596. int ch;
  2597. /* There are two cases when i->p[] buffer exists.
  2598. * (1) it's a string in_str.
  2599. * (2) It's a file, and we have a saved line editing buffer.
  2600. * In both cases, we know that i->p[0] exists and not NUL, and
  2601. * the peek2 result is in i->p[1].
  2602. */
  2603. if (i->p)
  2604. return (unsigned char)i->p[1];
  2605. /* Now we know it is a file-based in_str. */
  2606. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2607. /* Is there 2nd char? */
  2608. ch = i->peek_buf[1];
  2609. if (ch == 0) {
  2610. /* We did not read it yet, get it now */
  2611. do ch = hfgetc(i->file); while (ch == '\0');
  2612. i->peek_buf[1] = ch;
  2613. }
  2614. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2615. return ch;
  2616. }
  2617. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2618. {
  2619. for (;;) {
  2620. int ch, ch2;
  2621. ch = i_getch(input);
  2622. if (ch != '\\')
  2623. return ch;
  2624. ch2 = i_peek(input);
  2625. if (ch2 != '\n')
  2626. return ch;
  2627. /* backslash+newline, skip it */
  2628. i_getch(input);
  2629. }
  2630. }
  2631. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2632. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2633. */
  2634. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2635. {
  2636. for (;;) {
  2637. int ch, ch2;
  2638. ch = i_peek(input);
  2639. if (ch != '\\')
  2640. return ch;
  2641. ch2 = i_peek2(input);
  2642. if (ch2 != '\n')
  2643. return ch;
  2644. /* backslash+newline, skip it */
  2645. i_getch(input);
  2646. i_getch(input);
  2647. }
  2648. }
  2649. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2650. {
  2651. memset(i, 0, sizeof(*i));
  2652. i->file = fp;
  2653. /* i->p = NULL; */
  2654. }
  2655. static void setup_string_in_str(struct in_str *i, const char *s)
  2656. {
  2657. memset(i, 0, sizeof(*i));
  2658. /*i->file = NULL */;
  2659. i->p = s;
  2660. }
  2661. /*
  2662. * o_string support
  2663. */
  2664. #define B_CHUNK (32 * sizeof(char*))
  2665. static void o_reset_to_empty_unquoted(o_string *o)
  2666. {
  2667. o->length = 0;
  2668. o->has_quoted_part = 0;
  2669. if (o->data)
  2670. o->data[0] = '\0';
  2671. }
  2672. static void o_free_and_set_NULL(o_string *o)
  2673. {
  2674. free(o->data);
  2675. memset(o, 0, sizeof(*o));
  2676. }
  2677. static ALWAYS_INLINE void o_free(o_string *o)
  2678. {
  2679. free(o->data);
  2680. }
  2681. static void o_grow_by(o_string *o, int len)
  2682. {
  2683. if (o->length + len > o->maxlen) {
  2684. o->maxlen += (2 * len) | (B_CHUNK-1);
  2685. o->data = xrealloc(o->data, 1 + o->maxlen);
  2686. }
  2687. }
  2688. static void o_addchr(o_string *o, int ch)
  2689. {
  2690. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2691. if (o->length < o->maxlen) {
  2692. /* likely. avoid o_grow_by() call */
  2693. add:
  2694. o->data[o->length] = ch;
  2695. o->length++;
  2696. o->data[o->length] = '\0';
  2697. return;
  2698. }
  2699. o_grow_by(o, 1);
  2700. goto add;
  2701. }
  2702. #if 0
  2703. /* Valid only if we know o_string is not empty */
  2704. static void o_delchr(o_string *o)
  2705. {
  2706. o->length--;
  2707. o->data[o->length] = '\0';
  2708. }
  2709. #endif
  2710. static void o_addblock(o_string *o, const char *str, int len)
  2711. {
  2712. o_grow_by(o, len);
  2713. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2714. o->length += len;
  2715. }
  2716. static void o_addstr(o_string *o, const char *str)
  2717. {
  2718. o_addblock(o, str, strlen(str));
  2719. }
  2720. static void o_addstr_with_NUL(o_string *o, const char *str)
  2721. {
  2722. o_addblock(o, str, strlen(str) + 1);
  2723. }
  2724. #if !BB_MMU
  2725. static void nommu_addchr(o_string *o, int ch)
  2726. {
  2727. if (o)
  2728. o_addchr(o, ch);
  2729. }
  2730. #else
  2731. # define nommu_addchr(o, str) ((void)0)
  2732. #endif
  2733. #if ENABLE_HUSH_MODE_X
  2734. static void x_mode_addchr(int ch)
  2735. {
  2736. o_addchr(&G.x_mode_buf, ch);
  2737. }
  2738. static void x_mode_addstr(const char *str)
  2739. {
  2740. o_addstr(&G.x_mode_buf, str);
  2741. }
  2742. static void x_mode_addblock(const char *str, int len)
  2743. {
  2744. o_addblock(&G.x_mode_buf, str, len);
  2745. }
  2746. static void x_mode_prefix(void)
  2747. {
  2748. int n = G.x_mode_depth;
  2749. do x_mode_addchr('+'); while (--n >= 0);
  2750. }
  2751. static void x_mode_flush(void)
  2752. {
  2753. int len = G.x_mode_buf.length;
  2754. if (len <= 0)
  2755. return;
  2756. if (G.x_mode_fd > 0) {
  2757. G.x_mode_buf.data[len] = '\n';
  2758. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2759. }
  2760. G.x_mode_buf.length = 0;
  2761. }
  2762. #endif
  2763. /*
  2764. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2765. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2766. * Apparently, on unquoted $v bash still does globbing
  2767. * ("v='*.txt'; echo $v" prints all .txt files),
  2768. * but NOT brace expansion! Thus, there should be TWO independent
  2769. * quoting mechanisms on $v expansion side: one protects
  2770. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2771. * We have only second one.
  2772. */
  2773. #if ENABLE_HUSH_BRACE_EXPANSION
  2774. # define MAYBE_BRACES "{}"
  2775. #else
  2776. # define MAYBE_BRACES ""
  2777. #endif
  2778. /* My analysis of quoting semantics tells me that state information
  2779. * is associated with a destination, not a source.
  2780. */
  2781. static void o_addqchr(o_string *o, int ch)
  2782. {
  2783. int sz = 1;
  2784. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2785. if (found)
  2786. sz++;
  2787. o_grow_by(o, sz);
  2788. if (found) {
  2789. o->data[o->length] = '\\';
  2790. o->length++;
  2791. }
  2792. o->data[o->length] = ch;
  2793. o->length++;
  2794. o->data[o->length] = '\0';
  2795. }
  2796. static void o_addQchr(o_string *o, int ch)
  2797. {
  2798. int sz = 1;
  2799. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2800. && strchr("*?[\\" MAYBE_BRACES, ch)
  2801. ) {
  2802. sz++;
  2803. o->data[o->length] = '\\';
  2804. o->length++;
  2805. }
  2806. o_grow_by(o, sz);
  2807. o->data[o->length] = ch;
  2808. o->length++;
  2809. o->data[o->length] = '\0';
  2810. }
  2811. static void o_addqblock(o_string *o, const char *str, int len)
  2812. {
  2813. while (len) {
  2814. char ch;
  2815. int sz;
  2816. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2817. if (ordinary_cnt > len) /* paranoia */
  2818. ordinary_cnt = len;
  2819. o_addblock(o, str, ordinary_cnt);
  2820. if (ordinary_cnt == len)
  2821. return; /* NUL is already added by o_addblock */
  2822. str += ordinary_cnt;
  2823. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2824. ch = *str++;
  2825. sz = 1;
  2826. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2827. sz++;
  2828. o->data[o->length] = '\\';
  2829. o->length++;
  2830. }
  2831. o_grow_by(o, sz);
  2832. o->data[o->length] = ch;
  2833. o->length++;
  2834. }
  2835. o->data[o->length] = '\0';
  2836. }
  2837. static void o_addQblock(o_string *o, const char *str, int len)
  2838. {
  2839. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2840. o_addblock(o, str, len);
  2841. return;
  2842. }
  2843. o_addqblock(o, str, len);
  2844. }
  2845. static void o_addQstr(o_string *o, const char *str)
  2846. {
  2847. o_addQblock(o, str, strlen(str));
  2848. }
  2849. /* A special kind of o_string for $VAR and `cmd` expansion.
  2850. * It contains char* list[] at the beginning, which is grown in 16 element
  2851. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2852. * list[i] contains an INDEX (int!) into this string data.
  2853. * It means that if list[] needs to grow, data needs to be moved higher up
  2854. * but list[i]'s need not be modified.
  2855. * NB: remembering how many list[i]'s you have there is crucial.
  2856. * o_finalize_list() operation post-processes this structure - calculates
  2857. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2858. */
  2859. #if DEBUG_EXPAND || DEBUG_GLOB
  2860. static void debug_print_list(const char *prefix, o_string *o, int n)
  2861. {
  2862. char **list = (char**)o->data;
  2863. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2864. int i = 0;
  2865. indent();
  2866. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2867. prefix, list, n, string_start, o->length, o->maxlen,
  2868. !!(o->o_expflags & EXP_FLAG_GLOB),
  2869. o->has_quoted_part,
  2870. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2871. while (i < n) {
  2872. indent();
  2873. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2874. o->data + (int)(uintptr_t)list[i] + string_start,
  2875. o->data + (int)(uintptr_t)list[i] + string_start);
  2876. i++;
  2877. }
  2878. if (n) {
  2879. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2880. indent();
  2881. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2882. }
  2883. }
  2884. #else
  2885. # define debug_print_list(prefix, o, n) ((void)0)
  2886. #endif
  2887. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2888. * in list[n] so that it points past last stored byte so far.
  2889. * It returns n+1. */
  2890. static int o_save_ptr_helper(o_string *o, int n)
  2891. {
  2892. char **list = (char**)o->data;
  2893. int string_start;
  2894. int string_len;
  2895. if (!o->has_empty_slot) {
  2896. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2897. string_len = o->length - string_start;
  2898. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2899. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2900. /* list[n] points to string_start, make space for 16 more pointers */
  2901. o->maxlen += 0x10 * sizeof(list[0]);
  2902. o->data = xrealloc(o->data, o->maxlen + 1);
  2903. list = (char**)o->data;
  2904. memmove(list + n + 0x10, list + n, string_len);
  2905. /*
  2906. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2907. * check. (grep for -prev-ifs-check-).
  2908. * Ensure that argv[-1][last] is not garbage
  2909. * but zero bytes, to save index check there.
  2910. */
  2911. list[n + 0x10 - 1] = 0;
  2912. o->length += 0x10 * sizeof(list[0]);
  2913. } else {
  2914. debug_printf_list("list[%d]=%d string_start=%d\n",
  2915. n, string_len, string_start);
  2916. }
  2917. } else {
  2918. /* We have empty slot at list[n], reuse without growth */
  2919. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2920. string_len = o->length - string_start;
  2921. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2922. n, string_len, string_start);
  2923. o->has_empty_slot = 0;
  2924. }
  2925. o->has_quoted_part = 0;
  2926. list[n] = (char*)(uintptr_t)string_len;
  2927. return n + 1;
  2928. }
  2929. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2930. static int o_get_last_ptr(o_string *o, int n)
  2931. {
  2932. char **list = (char**)o->data;
  2933. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2934. return ((int)(uintptr_t)list[n-1]) + string_start;
  2935. }
  2936. /*
  2937. * Globbing routines.
  2938. *
  2939. * Most words in commands need to be globbed, even ones which are
  2940. * (single or double) quoted. This stems from the possiblity of
  2941. * constructs like "abc"* and 'abc'* - these should be globbed.
  2942. * Having a different code path for fully-quoted strings ("abc",
  2943. * 'abc') would only help performance-wise, but we still need
  2944. * code for partially-quoted strings.
  2945. *
  2946. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2947. * the logic can't be "shell-syntax argument is first transformed
  2948. * to a string, then globbed, and if globbing does not match anything,
  2949. * it is used verbatim". Here are two examples where it fails:
  2950. *
  2951. * echo 'b\*'?
  2952. *
  2953. * The globbing can't be avoided (because of '?' at the end).
  2954. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2955. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2956. * - IOW: they "unbackslash" the glob pattern.
  2957. * Now, look at this:
  2958. *
  2959. * v='\\\*'; echo b$v?
  2960. *
  2961. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2962. * should be used as glob pattern with no changes. However, if glob
  2963. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2964. *
  2965. * ash implements this by having an encoded representation of the word
  2966. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2967. * Glob pattern is derived from it. If glob fails, the decision what result
  2968. * should be is made using that encoded representation. Not glob pattern.
  2969. */
  2970. #if ENABLE_HUSH_BRACE_EXPANSION
  2971. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2972. * first, it processes even {a} (no commas), second,
  2973. * I didn't manage to make it return strings when they don't match
  2974. * existing files. Need to re-implement it.
  2975. */
  2976. /* Helper */
  2977. static int glob_needed(const char *s)
  2978. {
  2979. while (*s) {
  2980. if (*s == '\\') {
  2981. if (!s[1])
  2982. return 0;
  2983. s += 2;
  2984. continue;
  2985. }
  2986. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2987. return 1;
  2988. s++;
  2989. }
  2990. return 0;
  2991. }
  2992. /* Return pointer to next closing brace or to comma */
  2993. static const char *next_brace_sub(const char *cp)
  2994. {
  2995. unsigned depth = 0;
  2996. cp++;
  2997. while (*cp != '\0') {
  2998. if (*cp == '\\') {
  2999. if (*++cp == '\0')
  3000. break;
  3001. cp++;
  3002. continue;
  3003. }
  3004. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3005. break;
  3006. if (*cp++ == '{')
  3007. depth++;
  3008. }
  3009. return *cp != '\0' ? cp : NULL;
  3010. }
  3011. /* Recursive brace globber. Note: may garble pattern[]. */
  3012. static int glob_brace(char *pattern, o_string *o, int n)
  3013. {
  3014. char *new_pattern_buf;
  3015. const char *begin;
  3016. const char *next;
  3017. const char *rest;
  3018. const char *p;
  3019. size_t rest_len;
  3020. debug_printf_glob("glob_brace('%s')\n", pattern);
  3021. begin = pattern;
  3022. while (1) {
  3023. if (*begin == '\0')
  3024. goto simple_glob;
  3025. if (*begin == '{') {
  3026. /* Find the first sub-pattern and at the same time
  3027. * find the rest after the closing brace */
  3028. next = next_brace_sub(begin);
  3029. if (next == NULL) {
  3030. /* An illegal expression */
  3031. goto simple_glob;
  3032. }
  3033. if (*next == '}') {
  3034. /* "{abc}" with no commas - illegal
  3035. * brace expr, disregard and skip it */
  3036. begin = next + 1;
  3037. continue;
  3038. }
  3039. break;
  3040. }
  3041. if (*begin == '\\' && begin[1] != '\0')
  3042. begin++;
  3043. begin++;
  3044. }
  3045. debug_printf_glob("begin:%s\n", begin);
  3046. debug_printf_glob("next:%s\n", next);
  3047. /* Now find the end of the whole brace expression */
  3048. rest = next;
  3049. while (*rest != '}') {
  3050. rest = next_brace_sub(rest);
  3051. if (rest == NULL) {
  3052. /* An illegal expression */
  3053. goto simple_glob;
  3054. }
  3055. debug_printf_glob("rest:%s\n", rest);
  3056. }
  3057. rest_len = strlen(++rest) + 1;
  3058. /* We are sure the brace expression is well-formed */
  3059. /* Allocate working buffer large enough for our work */
  3060. new_pattern_buf = xmalloc(strlen(pattern));
  3061. /* We have a brace expression. BEGIN points to the opening {,
  3062. * NEXT points past the terminator of the first element, and REST
  3063. * points past the final }. We will accumulate result names from
  3064. * recursive runs for each brace alternative in the buffer using
  3065. * GLOB_APPEND. */
  3066. p = begin + 1;
  3067. while (1) {
  3068. /* Construct the new glob expression */
  3069. memcpy(
  3070. mempcpy(
  3071. mempcpy(new_pattern_buf,
  3072. /* We know the prefix for all sub-patterns */
  3073. pattern, begin - pattern),
  3074. p, next - p),
  3075. rest, rest_len);
  3076. /* Note: glob_brace() may garble new_pattern_buf[].
  3077. * That's why we re-copy prefix every time (1st memcpy above).
  3078. */
  3079. n = glob_brace(new_pattern_buf, o, n);
  3080. if (*next == '}') {
  3081. /* We saw the last entry */
  3082. break;
  3083. }
  3084. p = next + 1;
  3085. next = next_brace_sub(next);
  3086. }
  3087. free(new_pattern_buf);
  3088. return n;
  3089. simple_glob:
  3090. {
  3091. int gr;
  3092. glob_t globdata;
  3093. memset(&globdata, 0, sizeof(globdata));
  3094. gr = glob(pattern, 0, NULL, &globdata);
  3095. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3096. if (gr != 0) {
  3097. if (gr == GLOB_NOMATCH) {
  3098. globfree(&globdata);
  3099. /* NB: garbles parameter */
  3100. unbackslash(pattern);
  3101. o_addstr_with_NUL(o, pattern);
  3102. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3103. return o_save_ptr_helper(o, n);
  3104. }
  3105. if (gr == GLOB_NOSPACE)
  3106. bb_die_memory_exhausted();
  3107. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3108. * but we didn't specify it. Paranoia again. */
  3109. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3110. }
  3111. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3112. char **argv = globdata.gl_pathv;
  3113. while (1) {
  3114. o_addstr_with_NUL(o, *argv);
  3115. n = o_save_ptr_helper(o, n);
  3116. argv++;
  3117. if (!*argv)
  3118. break;
  3119. }
  3120. }
  3121. globfree(&globdata);
  3122. }
  3123. return n;
  3124. }
  3125. /* Performs globbing on last list[],
  3126. * saving each result as a new list[].
  3127. */
  3128. static int perform_glob(o_string *o, int n)
  3129. {
  3130. char *pattern, *copy;
  3131. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3132. if (!o->data)
  3133. return o_save_ptr_helper(o, n);
  3134. pattern = o->data + o_get_last_ptr(o, n);
  3135. debug_printf_glob("glob pattern '%s'\n", pattern);
  3136. if (!glob_needed(pattern)) {
  3137. /* unbackslash last string in o in place, fix length */
  3138. o->length = unbackslash(pattern) - o->data;
  3139. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3140. return o_save_ptr_helper(o, n);
  3141. }
  3142. copy = xstrdup(pattern);
  3143. /* "forget" pattern in o */
  3144. o->length = pattern - o->data;
  3145. n = glob_brace(copy, o, n);
  3146. free(copy);
  3147. if (DEBUG_GLOB)
  3148. debug_print_list("perform_glob returning", o, n);
  3149. return n;
  3150. }
  3151. #else /* !HUSH_BRACE_EXPANSION */
  3152. /* Helper */
  3153. static int glob_needed(const char *s)
  3154. {
  3155. while (*s) {
  3156. if (*s == '\\') {
  3157. if (!s[1])
  3158. return 0;
  3159. s += 2;
  3160. continue;
  3161. }
  3162. if (*s == '*' || *s == '[' || *s == '?')
  3163. return 1;
  3164. s++;
  3165. }
  3166. return 0;
  3167. }
  3168. /* Performs globbing on last list[],
  3169. * saving each result as a new list[].
  3170. */
  3171. static int perform_glob(o_string *o, int n)
  3172. {
  3173. glob_t globdata;
  3174. int gr;
  3175. char *pattern;
  3176. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3177. if (!o->data)
  3178. return o_save_ptr_helper(o, n);
  3179. pattern = o->data + o_get_last_ptr(o, n);
  3180. debug_printf_glob("glob pattern '%s'\n", pattern);
  3181. if (!glob_needed(pattern)) {
  3182. literal:
  3183. /* unbackslash last string in o in place, fix length */
  3184. o->length = unbackslash(pattern) - o->data;
  3185. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3186. return o_save_ptr_helper(o, n);
  3187. }
  3188. memset(&globdata, 0, sizeof(globdata));
  3189. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3190. * If we glob "*.\*" and don't find anything, we need
  3191. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3192. * will return "*.\*"!
  3193. */
  3194. gr = glob(pattern, 0, NULL, &globdata);
  3195. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3196. if (gr != 0) {
  3197. if (gr == GLOB_NOMATCH) {
  3198. globfree(&globdata);
  3199. goto literal;
  3200. }
  3201. if (gr == GLOB_NOSPACE)
  3202. bb_die_memory_exhausted();
  3203. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3204. * but we didn't specify it. Paranoia again. */
  3205. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3206. }
  3207. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3208. char **argv = globdata.gl_pathv;
  3209. /* "forget" pattern in o */
  3210. o->length = pattern - o->data;
  3211. while (1) {
  3212. o_addstr_with_NUL(o, *argv);
  3213. n = o_save_ptr_helper(o, n);
  3214. argv++;
  3215. if (!*argv)
  3216. break;
  3217. }
  3218. }
  3219. globfree(&globdata);
  3220. if (DEBUG_GLOB)
  3221. debug_print_list("perform_glob returning", o, n);
  3222. return n;
  3223. }
  3224. #endif /* !HUSH_BRACE_EXPANSION */
  3225. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3226. * Otherwise, just finish current list[] and start new */
  3227. static int o_save_ptr(o_string *o, int n)
  3228. {
  3229. if (o->o_expflags & EXP_FLAG_GLOB) {
  3230. /* If o->has_empty_slot, list[n] was already globbed
  3231. * (if it was requested back then when it was filled)
  3232. * so don't do that again! */
  3233. if (!o->has_empty_slot)
  3234. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3235. }
  3236. return o_save_ptr_helper(o, n);
  3237. }
  3238. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3239. static char **o_finalize_list(o_string *o, int n)
  3240. {
  3241. char **list;
  3242. int string_start;
  3243. if (DEBUG_EXPAND)
  3244. debug_print_list("finalized", o, n);
  3245. debug_printf_expand("finalized n:%d\n", n);
  3246. list = (char**)o->data;
  3247. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3248. list[--n] = NULL;
  3249. while (n) {
  3250. n--;
  3251. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3252. }
  3253. return list;
  3254. }
  3255. static void free_pipe_list(struct pipe *pi);
  3256. /* Returns pi->next - next pipe in the list */
  3257. static struct pipe *free_pipe(struct pipe *pi)
  3258. {
  3259. struct pipe *next;
  3260. int i;
  3261. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3262. for (i = 0; i < pi->num_cmds; i++) {
  3263. struct command *command;
  3264. struct redir_struct *r, *rnext;
  3265. command = &pi->cmds[i];
  3266. debug_printf_clean(" command %d:\n", i);
  3267. if (command->argv) {
  3268. if (DEBUG_CLEAN) {
  3269. int a;
  3270. char **p;
  3271. for (a = 0, p = command->argv; *p; a++, p++) {
  3272. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3273. }
  3274. }
  3275. free_strings(command->argv);
  3276. //command->argv = NULL;
  3277. }
  3278. /* not "else if": on syntax error, we may have both! */
  3279. if (command->group) {
  3280. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3281. command->cmd_type);
  3282. free_pipe_list(command->group);
  3283. debug_printf_clean(" end group\n");
  3284. //command->group = NULL;
  3285. }
  3286. /* else is crucial here.
  3287. * If group != NULL, child_func is meaningless */
  3288. #if ENABLE_HUSH_FUNCTIONS
  3289. else if (command->child_func) {
  3290. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3291. command->child_func->parent_cmd = NULL;
  3292. }
  3293. #endif
  3294. #if !BB_MMU
  3295. free(command->group_as_string);
  3296. //command->group_as_string = NULL;
  3297. #endif
  3298. for (r = command->redirects; r; r = rnext) {
  3299. debug_printf_clean(" redirect %d%s",
  3300. r->rd_fd, redir_table[r->rd_type].descrip);
  3301. /* guard against the case >$FOO, where foo is unset or blank */
  3302. if (r->rd_filename) {
  3303. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3304. free(r->rd_filename);
  3305. //r->rd_filename = NULL;
  3306. }
  3307. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3308. rnext = r->next;
  3309. free(r);
  3310. }
  3311. //command->redirects = NULL;
  3312. }
  3313. free(pi->cmds); /* children are an array, they get freed all at once */
  3314. //pi->cmds = NULL;
  3315. #if ENABLE_HUSH_JOB
  3316. free(pi->cmdtext);
  3317. //pi->cmdtext = NULL;
  3318. #endif
  3319. next = pi->next;
  3320. free(pi);
  3321. return next;
  3322. }
  3323. static void free_pipe_list(struct pipe *pi)
  3324. {
  3325. while (pi) {
  3326. #if HAS_KEYWORDS
  3327. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3328. #endif
  3329. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3330. pi = free_pipe(pi);
  3331. }
  3332. }
  3333. /*** Parsing routines ***/
  3334. #ifndef debug_print_tree
  3335. static void debug_print_tree(struct pipe *pi, int lvl)
  3336. {
  3337. static const char *const PIPE[] = {
  3338. [PIPE_SEQ] = "SEQ",
  3339. [PIPE_AND] = "AND",
  3340. [PIPE_OR ] = "OR" ,
  3341. [PIPE_BG ] = "BG" ,
  3342. };
  3343. static const char *RES[] = {
  3344. [RES_NONE ] = "NONE" ,
  3345. # if ENABLE_HUSH_IF
  3346. [RES_IF ] = "IF" ,
  3347. [RES_THEN ] = "THEN" ,
  3348. [RES_ELIF ] = "ELIF" ,
  3349. [RES_ELSE ] = "ELSE" ,
  3350. [RES_FI ] = "FI" ,
  3351. # endif
  3352. # if ENABLE_HUSH_LOOPS
  3353. [RES_FOR ] = "FOR" ,
  3354. [RES_WHILE] = "WHILE",
  3355. [RES_UNTIL] = "UNTIL",
  3356. [RES_DO ] = "DO" ,
  3357. [RES_DONE ] = "DONE" ,
  3358. # endif
  3359. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3360. [RES_IN ] = "IN" ,
  3361. # endif
  3362. # if ENABLE_HUSH_CASE
  3363. [RES_CASE ] = "CASE" ,
  3364. [RES_CASE_IN ] = "CASE_IN" ,
  3365. [RES_MATCH] = "MATCH",
  3366. [RES_CASE_BODY] = "CASE_BODY",
  3367. [RES_ESAC ] = "ESAC" ,
  3368. # endif
  3369. [RES_XXXX ] = "XXXX" ,
  3370. [RES_SNTX ] = "SNTX" ,
  3371. };
  3372. static const char *const CMDTYPE[] = {
  3373. "{}",
  3374. "()",
  3375. "[noglob]",
  3376. # if ENABLE_HUSH_FUNCTIONS
  3377. "func()",
  3378. # endif
  3379. };
  3380. int pin, prn;
  3381. pin = 0;
  3382. while (pi) {
  3383. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3384. lvl*2, "",
  3385. pin,
  3386. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3387. RES[pi->res_word],
  3388. pi->followup, PIPE[pi->followup]
  3389. );
  3390. prn = 0;
  3391. while (prn < pi->num_cmds) {
  3392. struct command *command = &pi->cmds[prn];
  3393. char **argv = command->argv;
  3394. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3395. lvl*2, "", prn,
  3396. command->assignment_cnt);
  3397. #if ENABLE_HUSH_LINENO_VAR
  3398. fdprintf(2, " LINENO:%u", command->lineno);
  3399. #endif
  3400. if (command->group) {
  3401. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3402. CMDTYPE[command->cmd_type],
  3403. argv
  3404. # if !BB_MMU
  3405. , " group_as_string:", command->group_as_string
  3406. # else
  3407. , "", ""
  3408. # endif
  3409. );
  3410. debug_print_tree(command->group, lvl+1);
  3411. prn++;
  3412. continue;
  3413. }
  3414. if (argv) while (*argv) {
  3415. fdprintf(2, " '%s'", *argv);
  3416. argv++;
  3417. }
  3418. if (command->redirects)
  3419. fdprintf(2, " {redir}");
  3420. fdprintf(2, "\n");
  3421. prn++;
  3422. }
  3423. pi = pi->next;
  3424. pin++;
  3425. }
  3426. }
  3427. #endif /* debug_print_tree */
  3428. static struct pipe *new_pipe(void)
  3429. {
  3430. struct pipe *pi;
  3431. pi = xzalloc(sizeof(struct pipe));
  3432. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3433. return pi;
  3434. }
  3435. /* Command (member of a pipe) is complete, or we start a new pipe
  3436. * if ctx->command is NULL.
  3437. * No errors possible here.
  3438. */
  3439. static int done_command(struct parse_context *ctx)
  3440. {
  3441. /* The command is really already in the pipe structure, so
  3442. * advance the pipe counter and make a new, null command. */
  3443. struct pipe *pi = ctx->pipe;
  3444. struct command *command = ctx->command;
  3445. #if 0 /* Instead we emit error message at run time */
  3446. if (ctx->pending_redirect) {
  3447. /* For example, "cmd >" (no filename to redirect to) */
  3448. syntax_error("invalid redirect");
  3449. ctx->pending_redirect = NULL;
  3450. }
  3451. #endif
  3452. if (command) {
  3453. if (IS_NULL_CMD(command)) {
  3454. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3455. goto clear_and_ret;
  3456. }
  3457. pi->num_cmds++;
  3458. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3459. //debug_print_tree(ctx->list_head, 20);
  3460. } else {
  3461. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3462. }
  3463. /* Only real trickiness here is that the uncommitted
  3464. * command structure is not counted in pi->num_cmds. */
  3465. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3466. ctx->command = command = &pi->cmds[pi->num_cmds];
  3467. clear_and_ret:
  3468. memset(command, 0, sizeof(*command));
  3469. #if ENABLE_HUSH_LINENO_VAR
  3470. command->lineno = G.lineno;
  3471. debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
  3472. #endif
  3473. return pi->num_cmds; /* used only for 0/nonzero check */
  3474. }
  3475. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3476. {
  3477. int not_null;
  3478. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3479. /* Close previous command */
  3480. not_null = done_command(ctx);
  3481. #if HAS_KEYWORDS
  3482. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3483. ctx->ctx_inverted = 0;
  3484. ctx->pipe->res_word = ctx->ctx_res_w;
  3485. #endif
  3486. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3487. /* Necessary since && and || have precedence over &:
  3488. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3489. * in a backgrounded subshell.
  3490. */
  3491. struct pipe *pi;
  3492. struct command *command;
  3493. /* Is this actually this construct, all pipes end with && or ||? */
  3494. pi = ctx->list_head;
  3495. while (pi != ctx->pipe) {
  3496. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3497. goto no_conv;
  3498. pi = pi->next;
  3499. }
  3500. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3501. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3502. pi = xzalloc(sizeof(*pi));
  3503. pi->followup = PIPE_BG;
  3504. pi->num_cmds = 1;
  3505. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3506. command = &pi->cmds[0];
  3507. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3508. command->cmd_type = CMD_NORMAL;
  3509. command->group = ctx->list_head;
  3510. #if !BB_MMU
  3511. command->group_as_string = xstrndup(
  3512. ctx->as_string.data,
  3513. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3514. );
  3515. #endif
  3516. /* Replace all pipes in ctx with one newly created */
  3517. ctx->list_head = ctx->pipe = pi;
  3518. } else {
  3519. no_conv:
  3520. ctx->pipe->followup = type;
  3521. }
  3522. /* Without this check, even just <enter> on command line generates
  3523. * tree of three NOPs (!). Which is harmless but annoying.
  3524. * IOW: it is safe to do it unconditionally. */
  3525. if (not_null
  3526. #if ENABLE_HUSH_IF
  3527. || ctx->ctx_res_w == RES_FI
  3528. #endif
  3529. #if ENABLE_HUSH_LOOPS
  3530. || ctx->ctx_res_w == RES_DONE
  3531. || ctx->ctx_res_w == RES_FOR
  3532. || ctx->ctx_res_w == RES_IN
  3533. #endif
  3534. #if ENABLE_HUSH_CASE
  3535. || ctx->ctx_res_w == RES_ESAC
  3536. #endif
  3537. ) {
  3538. struct pipe *new_p;
  3539. debug_printf_parse("done_pipe: adding new pipe: "
  3540. "not_null:%d ctx->ctx_res_w:%d\n",
  3541. not_null, ctx->ctx_res_w);
  3542. new_p = new_pipe();
  3543. ctx->pipe->next = new_p;
  3544. ctx->pipe = new_p;
  3545. /* RES_THEN, RES_DO etc are "sticky" -
  3546. * they remain set for pipes inside if/while.
  3547. * This is used to control execution.
  3548. * RES_FOR and RES_IN are NOT sticky (needed to support
  3549. * cases where variable or value happens to match a keyword):
  3550. */
  3551. #if ENABLE_HUSH_LOOPS
  3552. if (ctx->ctx_res_w == RES_FOR
  3553. || ctx->ctx_res_w == RES_IN)
  3554. ctx->ctx_res_w = RES_NONE;
  3555. #endif
  3556. #if ENABLE_HUSH_CASE
  3557. if (ctx->ctx_res_w == RES_MATCH)
  3558. ctx->ctx_res_w = RES_CASE_BODY;
  3559. if (ctx->ctx_res_w == RES_CASE)
  3560. ctx->ctx_res_w = RES_CASE_IN;
  3561. #endif
  3562. ctx->command = NULL; /* trick done_command below */
  3563. /* Create the memory for command, roughly:
  3564. * ctx->pipe->cmds = new struct command;
  3565. * ctx->command = &ctx->pipe->cmds[0];
  3566. */
  3567. done_command(ctx);
  3568. //debug_print_tree(ctx->list_head, 10);
  3569. }
  3570. debug_printf_parse("done_pipe return\n");
  3571. }
  3572. static void initialize_context(struct parse_context *ctx)
  3573. {
  3574. memset(ctx, 0, sizeof(*ctx));
  3575. if (MAYBE_ASSIGNMENT != 0)
  3576. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3577. ctx->pipe = ctx->list_head = new_pipe();
  3578. /* Create the memory for command, roughly:
  3579. * ctx->pipe->cmds = new struct command;
  3580. * ctx->command = &ctx->pipe->cmds[0];
  3581. */
  3582. done_command(ctx);
  3583. }
  3584. /* If a reserved word is found and processed, parse context is modified
  3585. * and 1 is returned.
  3586. */
  3587. #if HAS_KEYWORDS
  3588. struct reserved_combo {
  3589. char literal[6];
  3590. unsigned char res;
  3591. unsigned char assignment_flag;
  3592. int flag;
  3593. };
  3594. enum {
  3595. FLAG_END = (1 << RES_NONE ),
  3596. # if ENABLE_HUSH_IF
  3597. FLAG_IF = (1 << RES_IF ),
  3598. FLAG_THEN = (1 << RES_THEN ),
  3599. FLAG_ELIF = (1 << RES_ELIF ),
  3600. FLAG_ELSE = (1 << RES_ELSE ),
  3601. FLAG_FI = (1 << RES_FI ),
  3602. # endif
  3603. # if ENABLE_HUSH_LOOPS
  3604. FLAG_FOR = (1 << RES_FOR ),
  3605. FLAG_WHILE = (1 << RES_WHILE),
  3606. FLAG_UNTIL = (1 << RES_UNTIL),
  3607. FLAG_DO = (1 << RES_DO ),
  3608. FLAG_DONE = (1 << RES_DONE ),
  3609. FLAG_IN = (1 << RES_IN ),
  3610. # endif
  3611. # if ENABLE_HUSH_CASE
  3612. FLAG_MATCH = (1 << RES_MATCH),
  3613. FLAG_ESAC = (1 << RES_ESAC ),
  3614. # endif
  3615. FLAG_START = (1 << RES_XXXX ),
  3616. };
  3617. static const struct reserved_combo* match_reserved_word(o_string *word)
  3618. {
  3619. /* Mostly a list of accepted follow-up reserved words.
  3620. * FLAG_END means we are done with the sequence, and are ready
  3621. * to turn the compound list into a command.
  3622. * FLAG_START means the word must start a new compound list.
  3623. */
  3624. static const struct reserved_combo reserved_list[] = {
  3625. # if ENABLE_HUSH_IF
  3626. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3627. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3628. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3629. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3630. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3631. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3632. # endif
  3633. # if ENABLE_HUSH_LOOPS
  3634. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3635. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3636. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3637. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3638. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3639. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3640. # endif
  3641. # if ENABLE_HUSH_CASE
  3642. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3643. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3644. # endif
  3645. };
  3646. const struct reserved_combo *r;
  3647. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3648. if (strcmp(word->data, r->literal) == 0)
  3649. return r;
  3650. }
  3651. return NULL;
  3652. }
  3653. /* Return NULL: not a keyword, else: keyword
  3654. */
  3655. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3656. {
  3657. # if ENABLE_HUSH_CASE
  3658. static const struct reserved_combo reserved_match = {
  3659. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3660. };
  3661. # endif
  3662. const struct reserved_combo *r;
  3663. if (ctx->word.has_quoted_part)
  3664. return 0;
  3665. r = match_reserved_word(&ctx->word);
  3666. if (!r)
  3667. return r; /* NULL */
  3668. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3669. # if ENABLE_HUSH_CASE
  3670. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3671. /* "case word IN ..." - IN part starts first MATCH part */
  3672. r = &reserved_match;
  3673. } else
  3674. # endif
  3675. if (r->flag == 0) { /* '!' */
  3676. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3677. syntax_error("! ! command");
  3678. ctx->ctx_res_w = RES_SNTX;
  3679. }
  3680. ctx->ctx_inverted = 1;
  3681. return r;
  3682. }
  3683. if (r->flag & FLAG_START) {
  3684. struct parse_context *old;
  3685. old = xmemdup(ctx, sizeof(*ctx));
  3686. debug_printf_parse("push stack %p\n", old);
  3687. initialize_context(ctx);
  3688. ctx->stack = old;
  3689. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3690. syntax_error_at(ctx->word.data);
  3691. ctx->ctx_res_w = RES_SNTX;
  3692. return r;
  3693. } else {
  3694. /* "{...} fi" is ok. "{...} if" is not
  3695. * Example:
  3696. * if { echo foo; } then { echo bar; } fi */
  3697. if (ctx->command->group)
  3698. done_pipe(ctx, PIPE_SEQ);
  3699. }
  3700. ctx->ctx_res_w = r->res;
  3701. ctx->old_flag = r->flag;
  3702. ctx->is_assignment = r->assignment_flag;
  3703. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3704. if (ctx->old_flag & FLAG_END) {
  3705. struct parse_context *old;
  3706. done_pipe(ctx, PIPE_SEQ);
  3707. debug_printf_parse("pop stack %p\n", ctx->stack);
  3708. old = ctx->stack;
  3709. old->command->group = ctx->list_head;
  3710. old->command->cmd_type = CMD_NORMAL;
  3711. # if !BB_MMU
  3712. /* At this point, the compound command's string is in
  3713. * ctx->as_string... except for the leading keyword!
  3714. * Consider this example: "echo a | if true; then echo a; fi"
  3715. * ctx->as_string will contain "true; then echo a; fi",
  3716. * with "if " remaining in old->as_string!
  3717. */
  3718. {
  3719. char *str;
  3720. int len = old->as_string.length;
  3721. /* Concatenate halves */
  3722. o_addstr(&old->as_string, ctx->as_string.data);
  3723. o_free(&ctx->as_string);
  3724. /* Find where leading keyword starts in first half */
  3725. str = old->as_string.data + len;
  3726. if (str > old->as_string.data)
  3727. str--; /* skip whitespace after keyword */
  3728. while (str > old->as_string.data && isalpha(str[-1]))
  3729. str--;
  3730. /* Ugh, we're done with this horrid hack */
  3731. old->command->group_as_string = xstrdup(str);
  3732. debug_printf_parse("pop, remembering as:'%s'\n",
  3733. old->command->group_as_string);
  3734. }
  3735. # endif
  3736. *ctx = *old; /* physical copy */
  3737. free(old);
  3738. }
  3739. return r;
  3740. }
  3741. #endif /* HAS_KEYWORDS */
  3742. /* Word is complete, look at it and update parsing context.
  3743. * Normal return is 0. Syntax errors return 1.
  3744. * Note: on return, word is reset, but not o_free'd!
  3745. */
  3746. static int done_word(struct parse_context *ctx)
  3747. {
  3748. struct command *command = ctx->command;
  3749. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3750. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3751. debug_printf_parse("done_word return 0: true null, ignored\n");
  3752. return 0;
  3753. }
  3754. if (ctx->pending_redirect) {
  3755. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3756. * only if run as "bash", not "sh" */
  3757. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3758. * "2.7 Redirection
  3759. * If the redirection operator is "<<" or "<<-", the word
  3760. * that follows the redirection operator shall be
  3761. * subjected to quote removal; it is unspecified whether
  3762. * any of the other expansions occur. For the other
  3763. * redirection operators, the word that follows the
  3764. * redirection operator shall be subjected to tilde
  3765. * expansion, parameter expansion, command substitution,
  3766. * arithmetic expansion, and quote removal.
  3767. * Pathname expansion shall not be performed
  3768. * on the word by a non-interactive shell; an interactive
  3769. * shell may perform it, but shall do so only when
  3770. * the expansion would result in one word."
  3771. */
  3772. //bash does not do parameter/command substitution or arithmetic expansion
  3773. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3774. // as written:
  3775. // <<EOF$t
  3776. // <<EOF$((1))
  3777. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3778. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3779. /* Cater for >\file case:
  3780. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3781. * Same with heredocs:
  3782. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3783. */
  3784. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3785. unbackslash(ctx->pending_redirect->rd_filename);
  3786. /* Is it <<"HEREDOC"? */
  3787. if (ctx->word.has_quoted_part) {
  3788. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3789. }
  3790. }
  3791. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3792. ctx->pending_redirect = NULL;
  3793. } else {
  3794. #if HAS_KEYWORDS
  3795. # if ENABLE_HUSH_CASE
  3796. if (ctx->ctx_dsemicolon
  3797. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3798. ) {
  3799. /* already done when ctx_dsemicolon was set to 1: */
  3800. /* ctx->ctx_res_w = RES_MATCH; */
  3801. ctx->ctx_dsemicolon = 0;
  3802. } else
  3803. # endif
  3804. if (!command->argv /* if it's the first word... */
  3805. # if ENABLE_HUSH_LOOPS
  3806. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3807. && ctx->ctx_res_w != RES_IN
  3808. # endif
  3809. # if ENABLE_HUSH_CASE
  3810. && ctx->ctx_res_w != RES_CASE
  3811. # endif
  3812. ) {
  3813. const struct reserved_combo *reserved;
  3814. reserved = reserved_word(ctx);
  3815. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3816. if (reserved) {
  3817. # if ENABLE_HUSH_LINENO_VAR
  3818. /* Case:
  3819. * "while ...; do
  3820. * cmd ..."
  3821. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3822. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3823. */
  3824. if (0
  3825. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3826. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3827. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3828. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3829. ) {
  3830. done_pipe(ctx, PIPE_SEQ);
  3831. }
  3832. # endif
  3833. o_reset_to_empty_unquoted(&ctx->word);
  3834. debug_printf_parse("done_word return %d\n",
  3835. (ctx->ctx_res_w == RES_SNTX));
  3836. return (ctx->ctx_res_w == RES_SNTX);
  3837. }
  3838. # if defined(CMD_SINGLEWORD_NOGLOB)
  3839. if (0
  3840. # if BASH_TEST2
  3841. || strcmp(ctx->word.data, "[[") == 0
  3842. # endif
  3843. /* In bash, local/export/readonly are special, args
  3844. * are assignments and therefore expansion of them
  3845. * should be "one-word" expansion:
  3846. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3847. * compare with:
  3848. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3849. * ls: cannot access i=a: No such file or directory
  3850. * ls: cannot access b: No such file or directory
  3851. * Note: bash 3.2.33(1) does this only if export word
  3852. * itself is not quoted:
  3853. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3854. * aaa bbb
  3855. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3856. * aaa
  3857. */
  3858. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3859. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3860. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3861. ) {
  3862. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3863. }
  3864. /* fall through */
  3865. # endif
  3866. }
  3867. #endif /* HAS_KEYWORDS */
  3868. if (command->group) {
  3869. /* "{ echo foo; } echo bar" - bad */
  3870. syntax_error_at(ctx->word.data);
  3871. debug_printf_parse("done_word return 1: syntax error, "
  3872. "groups and arglists don't mix\n");
  3873. return 1;
  3874. }
  3875. /* If this word wasn't an assignment, next ones definitely
  3876. * can't be assignments. Even if they look like ones. */
  3877. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3878. && ctx->is_assignment != WORD_IS_KEYWORD
  3879. ) {
  3880. ctx->is_assignment = NOT_ASSIGNMENT;
  3881. } else {
  3882. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3883. command->assignment_cnt++;
  3884. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3885. }
  3886. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3887. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3888. }
  3889. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3890. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3891. debug_print_strings("word appended to argv", command->argv);
  3892. }
  3893. #if ENABLE_HUSH_LOOPS
  3894. if (ctx->ctx_res_w == RES_FOR) {
  3895. if (ctx->word.has_quoted_part
  3896. || !is_well_formed_var_name(command->argv[0], '\0')
  3897. ) {
  3898. /* bash says just "not a valid identifier" */
  3899. syntax_error("not a valid identifier in for");
  3900. return 1;
  3901. }
  3902. /* Force FOR to have just one word (variable name) */
  3903. /* NB: basically, this makes hush see "for v in ..."
  3904. * syntax as if it is "for v; in ...". FOR and IN become
  3905. * two pipe structs in parse tree. */
  3906. done_pipe(ctx, PIPE_SEQ);
  3907. }
  3908. #endif
  3909. #if ENABLE_HUSH_CASE
  3910. /* Force CASE to have just one word */
  3911. if (ctx->ctx_res_w == RES_CASE) {
  3912. done_pipe(ctx, PIPE_SEQ);
  3913. }
  3914. #endif
  3915. o_reset_to_empty_unquoted(&ctx->word);
  3916. debug_printf_parse("done_word return 0\n");
  3917. return 0;
  3918. }
  3919. /* Peek ahead in the input to find out if we have a "&n" construct,
  3920. * as in "2>&1", that represents duplicating a file descriptor.
  3921. * Return:
  3922. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3923. * REDIRFD_SYNTAX_ERR if syntax error,
  3924. * REDIRFD_TO_FILE if no & was seen,
  3925. * or the number found.
  3926. */
  3927. #if BB_MMU
  3928. #define parse_redir_right_fd(as_string, input) \
  3929. parse_redir_right_fd(input)
  3930. #endif
  3931. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3932. {
  3933. int ch, d, ok;
  3934. ch = i_peek(input);
  3935. if (ch != '&')
  3936. return REDIRFD_TO_FILE;
  3937. ch = i_getch(input); /* get the & */
  3938. nommu_addchr(as_string, ch);
  3939. ch = i_peek(input);
  3940. if (ch == '-') {
  3941. ch = i_getch(input);
  3942. nommu_addchr(as_string, ch);
  3943. return REDIRFD_CLOSE;
  3944. }
  3945. d = 0;
  3946. ok = 0;
  3947. while (ch != EOF && isdigit(ch)) {
  3948. d = d*10 + (ch-'0');
  3949. ok = 1;
  3950. ch = i_getch(input);
  3951. nommu_addchr(as_string, ch);
  3952. ch = i_peek(input);
  3953. }
  3954. if (ok) return d;
  3955. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3956. bb_error_msg("ambiguous redirect");
  3957. return REDIRFD_SYNTAX_ERR;
  3958. }
  3959. /* Return code is 0 normal, 1 if a syntax error is detected
  3960. */
  3961. static int parse_redirect(struct parse_context *ctx,
  3962. int fd,
  3963. redir_type style,
  3964. struct in_str *input)
  3965. {
  3966. struct command *command = ctx->command;
  3967. struct redir_struct *redir;
  3968. struct redir_struct **redirp;
  3969. int dup_num;
  3970. dup_num = REDIRFD_TO_FILE;
  3971. if (style != REDIRECT_HEREDOC) {
  3972. /* Check for a '>&1' type redirect */
  3973. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3974. if (dup_num == REDIRFD_SYNTAX_ERR)
  3975. return 1;
  3976. } else {
  3977. int ch = i_peek_and_eat_bkslash_nl(input);
  3978. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3979. if (dup_num) { /* <<-... */
  3980. ch = i_getch(input);
  3981. nommu_addchr(&ctx->as_string, ch);
  3982. ch = i_peek(input);
  3983. }
  3984. }
  3985. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3986. int ch = i_peek_and_eat_bkslash_nl(input);
  3987. if (ch == '|') {
  3988. /* >|FILE redirect ("clobbering" >).
  3989. * Since we do not support "set -o noclobber" yet,
  3990. * >| and > are the same for now. Just eat |.
  3991. */
  3992. ch = i_getch(input);
  3993. nommu_addchr(&ctx->as_string, ch);
  3994. }
  3995. }
  3996. /* Create a new redir_struct and append it to the linked list */
  3997. redirp = &command->redirects;
  3998. while ((redir = *redirp) != NULL) {
  3999. redirp = &(redir->next);
  4000. }
  4001. *redirp = redir = xzalloc(sizeof(*redir));
  4002. /* redir->next = NULL; */
  4003. /* redir->rd_filename = NULL; */
  4004. redir->rd_type = style;
  4005. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4006. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4007. redir_table[style].descrip);
  4008. redir->rd_dup = dup_num;
  4009. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4010. /* Erik had a check here that the file descriptor in question
  4011. * is legit; I postpone that to "run time"
  4012. * A "-" representation of "close me" shows up as a -3 here */
  4013. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4014. redir->rd_fd, redir->rd_dup);
  4015. } else {
  4016. #if 0 /* Instead we emit error message at run time */
  4017. if (ctx->pending_redirect) {
  4018. /* For example, "cmd > <file" */
  4019. syntax_error("invalid redirect");
  4020. }
  4021. #endif
  4022. /* Set ctx->pending_redirect, so we know what to do at the
  4023. * end of the next parsed word. */
  4024. ctx->pending_redirect = redir;
  4025. }
  4026. return 0;
  4027. }
  4028. /* If a redirect is immediately preceded by a number, that number is
  4029. * supposed to tell which file descriptor to redirect. This routine
  4030. * looks for such preceding numbers. In an ideal world this routine
  4031. * needs to handle all the following classes of redirects...
  4032. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4033. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4034. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4035. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4036. *
  4037. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4038. * "2.7 Redirection
  4039. * ... If n is quoted, the number shall not be recognized as part of
  4040. * the redirection expression. For example:
  4041. * echo \2>a
  4042. * writes the character 2 into file a"
  4043. * We are getting it right by setting ->has_quoted_part on any \<char>
  4044. *
  4045. * A -1 return means no valid number was found,
  4046. * the caller should use the appropriate default for this redirection.
  4047. */
  4048. static int redirect_opt_num(o_string *o)
  4049. {
  4050. int num;
  4051. if (o->data == NULL)
  4052. return -1;
  4053. num = bb_strtou(o->data, NULL, 10);
  4054. if (errno || num < 0)
  4055. return -1;
  4056. o_reset_to_empty_unquoted(o);
  4057. return num;
  4058. }
  4059. #if BB_MMU
  4060. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4061. fetch_till_str(input, word, skip_tabs)
  4062. #endif
  4063. static char *fetch_till_str(o_string *as_string,
  4064. struct in_str *input,
  4065. const char *word,
  4066. int heredoc_flags)
  4067. {
  4068. o_string heredoc = NULL_O_STRING;
  4069. unsigned past_EOL;
  4070. int prev = 0; /* not \ */
  4071. int ch;
  4072. /* Starting with "" is necessary for this case:
  4073. * cat <<EOF
  4074. *
  4075. * xxx
  4076. * EOF
  4077. */
  4078. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4079. goto jump_in;
  4080. while (1) {
  4081. ch = i_getch(input);
  4082. if (ch != EOF)
  4083. nommu_addchr(as_string, ch);
  4084. if (ch == '\n' || ch == EOF) {
  4085. check_heredoc_end:
  4086. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4087. /* End-of-line, and not a line continuation */
  4088. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4089. heredoc.data[past_EOL] = '\0';
  4090. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4091. return heredoc.data;
  4092. }
  4093. if (ch == '\n') {
  4094. /* This is a new line.
  4095. * Remember position and backslash-escaping status.
  4096. */
  4097. o_addchr(&heredoc, ch);
  4098. prev = ch;
  4099. jump_in:
  4100. past_EOL = heredoc.length;
  4101. /* Get 1st char of next line, possibly skipping leading tabs */
  4102. do {
  4103. ch = i_getch(input);
  4104. if (ch != EOF)
  4105. nommu_addchr(as_string, ch);
  4106. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4107. /* If this immediately ended the line,
  4108. * go back to end-of-line checks.
  4109. */
  4110. if (ch == '\n')
  4111. goto check_heredoc_end;
  4112. }
  4113. } else {
  4114. /* Backslash-line continuation in an unquoted
  4115. * heredoc. This does not need special handling
  4116. * for heredoc body (unquoted heredocs are
  4117. * expanded on "execution" and that would take
  4118. * care of this case too), but not the case
  4119. * of line continuation *in terminator*:
  4120. * cat <<EOF
  4121. * Ok1
  4122. * EO\
  4123. * F
  4124. */
  4125. heredoc.data[--heredoc.length] = '\0';
  4126. prev = 0; /* not '\' */
  4127. continue;
  4128. }
  4129. }
  4130. if (ch == EOF) {
  4131. o_free(&heredoc);
  4132. return NULL; /* error */
  4133. }
  4134. o_addchr(&heredoc, ch);
  4135. nommu_addchr(as_string, ch);
  4136. if (prev == '\\' && ch == '\\')
  4137. /* Correctly handle foo\\<eol> (not a line cont.) */
  4138. prev = 0; /* not '\' */
  4139. else
  4140. prev = ch;
  4141. }
  4142. }
  4143. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4144. * and load them all. There should be exactly heredoc_cnt of them.
  4145. */
  4146. #if BB_MMU
  4147. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4148. fetch_heredocs(pi, heredoc_cnt, input)
  4149. #endif
  4150. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4151. {
  4152. while (pi && heredoc_cnt) {
  4153. int i;
  4154. struct command *cmd = pi->cmds;
  4155. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4156. pi->num_cmds,
  4157. cmd->argv ? cmd->argv[0] : "NONE"
  4158. );
  4159. for (i = 0; i < pi->num_cmds; i++) {
  4160. struct redir_struct *redir = cmd->redirects;
  4161. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4162. i, cmd->argv ? cmd->argv[0] : "NONE");
  4163. while (redir) {
  4164. if (redir->rd_type == REDIRECT_HEREDOC) {
  4165. char *p;
  4166. redir->rd_type = REDIRECT_HEREDOC2;
  4167. /* redir->rd_dup is (ab)used to indicate <<- */
  4168. p = fetch_till_str(as_string, input,
  4169. redir->rd_filename, redir->rd_dup);
  4170. if (!p) {
  4171. syntax_error("unexpected EOF in here document");
  4172. return -1;
  4173. }
  4174. free(redir->rd_filename);
  4175. redir->rd_filename = p;
  4176. heredoc_cnt--;
  4177. }
  4178. redir = redir->next;
  4179. }
  4180. if (cmd->group) {
  4181. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4182. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4183. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4184. if (heredoc_cnt < 0)
  4185. return heredoc_cnt; /* error */
  4186. }
  4187. cmd++;
  4188. }
  4189. pi = pi->next;
  4190. }
  4191. return heredoc_cnt;
  4192. }
  4193. static int run_list(struct pipe *pi);
  4194. #if BB_MMU
  4195. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4196. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4197. #endif
  4198. static struct pipe *parse_stream(char **pstring,
  4199. int *heredoc_cnt_ptr,
  4200. struct in_str *input,
  4201. int end_trigger);
  4202. /* Returns number of heredocs not yet consumed,
  4203. * or -1 on error.
  4204. */
  4205. static int parse_group(struct parse_context *ctx,
  4206. struct in_str *input, int ch)
  4207. {
  4208. /* ctx->word contains characters seen prior to ( or {.
  4209. * Typically it's empty, but for function defs,
  4210. * it contains function name (without '()'). */
  4211. #if BB_MMU
  4212. # define as_string NULL
  4213. #else
  4214. char *as_string = NULL;
  4215. #endif
  4216. struct pipe *pipe_list;
  4217. int heredoc_cnt = 0;
  4218. int endch;
  4219. struct command *command = ctx->command;
  4220. debug_printf_parse("parse_group entered\n");
  4221. #if ENABLE_HUSH_FUNCTIONS
  4222. if (ch == '(' && !ctx->word.has_quoted_part) {
  4223. if (ctx->word.length)
  4224. if (done_word(ctx))
  4225. return -1;
  4226. if (!command->argv)
  4227. goto skip; /* (... */
  4228. if (command->argv[1]) { /* word word ... (... */
  4229. syntax_error_unexpected_ch('(');
  4230. return -1;
  4231. }
  4232. /* it is "word(..." or "word (..." */
  4233. do
  4234. ch = i_getch(input);
  4235. while (ch == ' ' || ch == '\t');
  4236. if (ch != ')') {
  4237. syntax_error_unexpected_ch(ch);
  4238. return -1;
  4239. }
  4240. nommu_addchr(&ctx->as_string, ch);
  4241. do
  4242. ch = i_getch(input);
  4243. while (ch == ' ' || ch == '\t' || ch == '\n');
  4244. if (ch != '{' && ch != '(') {
  4245. syntax_error_unexpected_ch(ch);
  4246. return -1;
  4247. }
  4248. nommu_addchr(&ctx->as_string, ch);
  4249. command->cmd_type = CMD_FUNCDEF;
  4250. goto skip;
  4251. }
  4252. #endif
  4253. #if 0 /* Prevented by caller */
  4254. if (command->argv /* word [word]{... */
  4255. || ctx->word.length /* word{... */
  4256. || ctx->word.has_quoted_part /* ""{... */
  4257. ) {
  4258. syntax_error(NULL);
  4259. debug_printf_parse("parse_group return -1: "
  4260. "syntax error, groups and arglists don't mix\n");
  4261. return -1;
  4262. }
  4263. #endif
  4264. IF_HUSH_FUNCTIONS(skip:)
  4265. endch = '}';
  4266. if (ch == '(') {
  4267. endch = ')';
  4268. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4269. command->cmd_type = CMD_SUBSHELL;
  4270. } else {
  4271. /* bash does not allow "{echo...", requires whitespace */
  4272. ch = i_peek(input);
  4273. if (ch != ' ' && ch != '\t' && ch != '\n'
  4274. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4275. ) {
  4276. syntax_error_unexpected_ch(ch);
  4277. return -1;
  4278. }
  4279. if (ch != '(') {
  4280. ch = i_getch(input);
  4281. nommu_addchr(&ctx->as_string, ch);
  4282. }
  4283. }
  4284. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4285. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4286. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4287. #if !BB_MMU
  4288. if (as_string)
  4289. o_addstr(&ctx->as_string, as_string);
  4290. #endif
  4291. /* empty ()/{} or parse error? */
  4292. if (!pipe_list || pipe_list == ERR_PTR) {
  4293. /* parse_stream already emitted error msg */
  4294. if (!BB_MMU)
  4295. free(as_string);
  4296. debug_printf_parse("parse_group return -1: "
  4297. "parse_stream returned %p\n", pipe_list);
  4298. return -1;
  4299. }
  4300. #if !BB_MMU
  4301. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4302. command->group_as_string = as_string;
  4303. debug_printf_parse("end of group, remembering as:'%s'\n",
  4304. command->group_as_string);
  4305. #endif
  4306. #if ENABLE_HUSH_FUNCTIONS
  4307. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4308. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4309. struct command *cmd2;
  4310. cmd2 = xzalloc(sizeof(*cmd2));
  4311. cmd2->cmd_type = CMD_SUBSHELL;
  4312. cmd2->group = pipe_list;
  4313. # if !BB_MMU
  4314. //UNTESTED!
  4315. cmd2->group_as_string = command->group_as_string;
  4316. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4317. # endif
  4318. pipe_list = new_pipe();
  4319. pipe_list->cmds = cmd2;
  4320. pipe_list->num_cmds = 1;
  4321. }
  4322. #endif
  4323. command->group = pipe_list;
  4324. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4325. return heredoc_cnt;
  4326. /* command remains "open", available for possible redirects */
  4327. #undef as_string
  4328. }
  4329. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4330. /* Subroutines for copying $(...) and `...` things */
  4331. /* '...' */
  4332. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4333. {
  4334. while (1) {
  4335. int ch = i_getch(input);
  4336. if (ch == EOF) {
  4337. syntax_error_unterm_ch('\'');
  4338. return 0;
  4339. }
  4340. if (ch == '\'')
  4341. return 1;
  4342. o_addchr(dest, ch);
  4343. }
  4344. }
  4345. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4346. {
  4347. while (1) {
  4348. int ch = i_getch(input);
  4349. if (ch == EOF) {
  4350. syntax_error_unterm_ch('\'');
  4351. return 0;
  4352. }
  4353. if (ch == '\'')
  4354. return 1;
  4355. o_addqchr(dest, ch);
  4356. }
  4357. }
  4358. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4359. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4360. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4361. {
  4362. while (1) {
  4363. int ch = i_getch(input);
  4364. if (ch == EOF) {
  4365. syntax_error_unterm_ch('"');
  4366. return 0;
  4367. }
  4368. if (ch == '"')
  4369. return 1;
  4370. if (ch == '\\') { /* \x. Copy both chars. */
  4371. o_addchr(dest, ch);
  4372. ch = i_getch(input);
  4373. }
  4374. o_addchr(dest, ch);
  4375. if (ch == '`') {
  4376. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4377. return 0;
  4378. o_addchr(dest, ch);
  4379. continue;
  4380. }
  4381. //if (ch == '$') ...
  4382. }
  4383. }
  4384. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4385. * \` quoting.
  4386. * "Within the backquoted style of command substitution, backslash
  4387. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4388. * The search for the matching backquote shall be satisfied by the first
  4389. * backquote found without a preceding backslash; during this search,
  4390. * if a non-escaped backquote is encountered within a shell comment,
  4391. * a here-document, an embedded command substitution of the $(command)
  4392. * form, or a quoted string, undefined results occur. A single-quoted
  4393. * or double-quoted string that begins, but does not end, within the
  4394. * "`...`" sequence produces undefined results."
  4395. * Example Output
  4396. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4397. */
  4398. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4399. {
  4400. while (1) {
  4401. int ch = i_getch(input);
  4402. if (ch == '`')
  4403. return 1;
  4404. if (ch == '\\') {
  4405. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4406. ch = i_getch(input);
  4407. if (ch != '`'
  4408. && ch != '$'
  4409. && ch != '\\'
  4410. && (!in_dquote || ch != '"')
  4411. ) {
  4412. o_addchr(dest, '\\');
  4413. }
  4414. }
  4415. if (ch == EOF) {
  4416. syntax_error_unterm_ch('`');
  4417. return 0;
  4418. }
  4419. o_addchr(dest, ch);
  4420. }
  4421. }
  4422. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4423. * quoting and nested ()s.
  4424. * "With the $(command) style of command substitution, all characters
  4425. * following the open parenthesis to the matching closing parenthesis
  4426. * constitute the command. Any valid shell script can be used for command,
  4427. * except a script consisting solely of redirections which produces
  4428. * unspecified results."
  4429. * Example Output
  4430. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4431. * echo $(echo 'TEST)' BEST) TEST) BEST
  4432. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4433. *
  4434. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4435. * can contain arbitrary constructs, just like $(cmd).
  4436. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4437. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4438. */
  4439. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4440. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4441. {
  4442. int ch;
  4443. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4444. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4445. char end_char2 = end_ch >> 8;
  4446. # endif
  4447. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4448. #if ENABLE_HUSH_INTERACTIVE
  4449. G.promptmode = 1; /* PS2 */
  4450. #endif
  4451. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4452. while (1) {
  4453. ch = i_getch(input);
  4454. if (ch == EOF) {
  4455. syntax_error_unterm_ch(end_ch);
  4456. return 0;
  4457. }
  4458. if (ch == end_ch
  4459. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4460. || ch == end_char2
  4461. # endif
  4462. ) {
  4463. if (!dbl)
  4464. break;
  4465. /* we look for closing )) of $((EXPR)) */
  4466. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4467. i_getch(input); /* eat second ')' */
  4468. break;
  4469. }
  4470. }
  4471. o_addchr(dest, ch);
  4472. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4473. if (ch == '(' || ch == '{') {
  4474. ch = (ch == '(' ? ')' : '}');
  4475. if (!add_till_closing_bracket(dest, input, ch))
  4476. return 0;
  4477. o_addchr(dest, ch);
  4478. continue;
  4479. }
  4480. if (ch == '\'') {
  4481. if (!add_till_single_quote(dest, input))
  4482. return 0;
  4483. o_addchr(dest, ch);
  4484. continue;
  4485. }
  4486. if (ch == '"') {
  4487. if (!add_till_double_quote(dest, input))
  4488. return 0;
  4489. o_addchr(dest, ch);
  4490. continue;
  4491. }
  4492. if (ch == '`') {
  4493. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4494. return 0;
  4495. o_addchr(dest, ch);
  4496. continue;
  4497. }
  4498. if (ch == '\\') {
  4499. /* \x. Copy verbatim. Important for \(, \) */
  4500. ch = i_getch(input);
  4501. if (ch == EOF) {
  4502. syntax_error_unterm_ch(end_ch);
  4503. return 0;
  4504. }
  4505. #if 0
  4506. if (ch == '\n') {
  4507. /* "backslash+newline", ignore both */
  4508. o_delchr(dest); /* undo insertion of '\' */
  4509. continue;
  4510. }
  4511. #endif
  4512. o_addchr(dest, ch);
  4513. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4514. continue;
  4515. }
  4516. }
  4517. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4518. return ch;
  4519. }
  4520. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4521. /* Return code: 0 for OK, 1 for syntax error */
  4522. #if BB_MMU
  4523. #define parse_dollar(as_string, dest, input, quote_mask) \
  4524. parse_dollar(dest, input, quote_mask)
  4525. #define as_string NULL
  4526. #endif
  4527. static int parse_dollar(o_string *as_string,
  4528. o_string *dest,
  4529. struct in_str *input, unsigned char quote_mask)
  4530. {
  4531. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4532. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4533. if (isalpha(ch)) {
  4534. make_var:
  4535. ch = i_getch(input);
  4536. nommu_addchr(as_string, ch);
  4537. /*make_var1:*/
  4538. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4539. while (1) {
  4540. debug_printf_parse(": '%c'\n", ch);
  4541. o_addchr(dest, ch | quote_mask);
  4542. quote_mask = 0;
  4543. ch = i_peek_and_eat_bkslash_nl(input);
  4544. if (!isalnum(ch) && ch != '_') {
  4545. /* End of variable name reached */
  4546. break;
  4547. }
  4548. ch = i_getch(input);
  4549. nommu_addchr(as_string, ch);
  4550. }
  4551. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4552. } else if (isdigit(ch)) {
  4553. make_one_char_var:
  4554. ch = i_getch(input);
  4555. nommu_addchr(as_string, ch);
  4556. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4557. debug_printf_parse(": '%c'\n", ch);
  4558. o_addchr(dest, ch | quote_mask);
  4559. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4560. } else switch (ch) {
  4561. case '$': /* pid */
  4562. case '!': /* last bg pid */
  4563. case '?': /* last exit code */
  4564. case '#': /* number of args */
  4565. case '*': /* args */
  4566. case '@': /* args */
  4567. goto make_one_char_var;
  4568. case '{': {
  4569. char len_single_ch;
  4570. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4571. ch = i_getch(input); /* eat '{' */
  4572. nommu_addchr(as_string, ch);
  4573. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4574. /* It should be ${?}, or ${#var},
  4575. * or even ${?+subst} - operator acting on a special variable,
  4576. * or the beginning of variable name.
  4577. */
  4578. if (ch == EOF
  4579. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4580. ) {
  4581. bad_dollar_syntax:
  4582. syntax_error_unterm_str("${name}");
  4583. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4584. return 0;
  4585. }
  4586. nommu_addchr(as_string, ch);
  4587. len_single_ch = ch;
  4588. ch |= quote_mask;
  4589. /* It's possible to just call add_till_closing_bracket() at this point.
  4590. * However, this regresses some of our testsuite cases
  4591. * which check invalid constructs like ${%}.
  4592. * Oh well... let's check that the var name part is fine... */
  4593. while (1) {
  4594. unsigned pos;
  4595. o_addchr(dest, ch);
  4596. debug_printf_parse(": '%c'\n", ch);
  4597. ch = i_getch(input);
  4598. nommu_addchr(as_string, ch);
  4599. if (ch == '}')
  4600. break;
  4601. if (!isalnum(ch) && ch != '_') {
  4602. unsigned end_ch;
  4603. unsigned char last_ch;
  4604. /* handle parameter expansions
  4605. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4606. */
  4607. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4608. if (len_single_ch != '#'
  4609. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4610. || i_peek(input) != '}'
  4611. ) {
  4612. goto bad_dollar_syntax;
  4613. }
  4614. /* else: it's "length of C" ${#C} op,
  4615. * where C is a single char
  4616. * special var name, e.g. ${#!}.
  4617. */
  4618. }
  4619. /* Eat everything until closing '}' (or ':') */
  4620. end_ch = '}';
  4621. if (BASH_SUBSTR
  4622. && ch == ':'
  4623. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4624. ) {
  4625. /* It's ${var:N[:M]} thing */
  4626. end_ch = '}' * 0x100 + ':';
  4627. }
  4628. if (BASH_PATTERN_SUBST
  4629. && ch == '/'
  4630. ) {
  4631. /* It's ${var/[/]pattern[/repl]} thing */
  4632. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4633. i_getch(input);
  4634. nommu_addchr(as_string, '/');
  4635. ch = '\\';
  4636. }
  4637. end_ch = '}' * 0x100 + '/';
  4638. }
  4639. o_addchr(dest, ch);
  4640. /* The pattern can't be empty.
  4641. * IOW: if the first char after "${v//" is a slash,
  4642. * it does not terminate the pattern - it's the first char of the pattern:
  4643. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4644. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4645. */
  4646. if (i_peek(input) == '/') {
  4647. o_addchr(dest, i_getch(input));
  4648. }
  4649. again:
  4650. if (!BB_MMU)
  4651. pos = dest->length;
  4652. #if ENABLE_HUSH_DOLLAR_OPS
  4653. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4654. if (last_ch == 0) /* error? */
  4655. return 0;
  4656. #else
  4657. #error Simple code to only allow ${var} is not implemented
  4658. #endif
  4659. if (as_string) {
  4660. o_addstr(as_string, dest->data + pos);
  4661. o_addchr(as_string, last_ch);
  4662. }
  4663. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4664. && (end_ch & 0xff00)
  4665. ) {
  4666. /* close the first block: */
  4667. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4668. /* while parsing N from ${var:N[:M]}
  4669. * or pattern from ${var/[/]pattern[/repl]} */
  4670. if ((end_ch & 0xff) == last_ch) {
  4671. /* got ':' or '/'- parse the rest */
  4672. end_ch = '}';
  4673. goto again;
  4674. }
  4675. /* got '}' */
  4676. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4677. /* it's ${var:N} - emulate :999999999 */
  4678. o_addstr(dest, "999999999");
  4679. } /* else: it's ${var/[/]pattern} */
  4680. }
  4681. break;
  4682. }
  4683. len_single_ch = 0; /* it can't be ${#C} op */
  4684. }
  4685. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4686. break;
  4687. }
  4688. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4689. case '(': {
  4690. unsigned pos;
  4691. ch = i_getch(input);
  4692. nommu_addchr(as_string, ch);
  4693. # if ENABLE_FEATURE_SH_MATH
  4694. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4695. ch = i_getch(input);
  4696. nommu_addchr(as_string, ch);
  4697. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4698. o_addchr(dest, /*quote_mask |*/ '+');
  4699. if (!BB_MMU)
  4700. pos = dest->length;
  4701. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4702. return 0; /* error */
  4703. if (as_string) {
  4704. o_addstr(as_string, dest->data + pos);
  4705. o_addchr(as_string, ')');
  4706. o_addchr(as_string, ')');
  4707. }
  4708. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4709. break;
  4710. }
  4711. # endif
  4712. # if ENABLE_HUSH_TICK
  4713. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4714. o_addchr(dest, quote_mask | '`');
  4715. if (!BB_MMU)
  4716. pos = dest->length;
  4717. if (!add_till_closing_bracket(dest, input, ')'))
  4718. return 0; /* error */
  4719. if (as_string) {
  4720. o_addstr(as_string, dest->data + pos);
  4721. o_addchr(as_string, ')');
  4722. }
  4723. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4724. # endif
  4725. break;
  4726. }
  4727. #endif
  4728. case '_':
  4729. goto make_var;
  4730. #if 0
  4731. /* TODO: $_ and $-: */
  4732. /* $_ Shell or shell script name; or last argument of last command
  4733. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4734. * but in command's env, set to full pathname used to invoke it */
  4735. /* $- Option flags set by set builtin or shell options (-i etc) */
  4736. ch = i_getch(input);
  4737. nommu_addchr(as_string, ch);
  4738. ch = i_peek_and_eat_bkslash_nl(input);
  4739. if (isalnum(ch)) { /* it's $_name or $_123 */
  4740. ch = '_';
  4741. goto make_var1;
  4742. }
  4743. /* else: it's $_ */
  4744. #endif
  4745. default:
  4746. o_addQchr(dest, '$');
  4747. }
  4748. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4749. return 1;
  4750. #undef as_string
  4751. }
  4752. #if BB_MMU
  4753. #define encode_string(as_string, dest, input, dquote_end) \
  4754. encode_string(dest, input, dquote_end)
  4755. #define as_string NULL
  4756. #endif
  4757. static int encode_string(o_string *as_string,
  4758. o_string *dest,
  4759. struct in_str *input,
  4760. int dquote_end)
  4761. {
  4762. int ch;
  4763. int next;
  4764. again:
  4765. ch = i_getch(input);
  4766. if (ch != EOF)
  4767. nommu_addchr(as_string, ch);
  4768. if (ch == dquote_end) { /* may be only '"' or EOF */
  4769. debug_printf_parse("encode_string return 1 (ok)\n");
  4770. return 1;
  4771. }
  4772. /* note: can't move it above ch == dquote_end check! */
  4773. if (ch == EOF) {
  4774. syntax_error_unterm_ch('"');
  4775. return 0; /* error */
  4776. }
  4777. next = '\0';
  4778. if (ch != '\n') {
  4779. next = i_peek(input);
  4780. }
  4781. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4782. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4783. if (ch == '\\') {
  4784. if (next == EOF) {
  4785. /* Testcase: in interactive shell a file with
  4786. * echo "unterminated string\<eof>
  4787. * is sourced.
  4788. */
  4789. syntax_error_unterm_ch('"');
  4790. return 0; /* error */
  4791. }
  4792. /* bash:
  4793. * "The backslash retains its special meaning [in "..."]
  4794. * only when followed by one of the following characters:
  4795. * $, `, ", \, or <newline>. A double quote may be quoted
  4796. * within double quotes by preceding it with a backslash."
  4797. * NB: in (unquoted) heredoc, above does not apply to ",
  4798. * therefore we check for it by "next == dquote_end" cond.
  4799. */
  4800. if (next == dquote_end || strchr("$`\\\n", next)) {
  4801. ch = i_getch(input); /* eat next */
  4802. if (ch == '\n')
  4803. goto again; /* skip \<newline> */
  4804. } /* else: ch remains == '\\', and we double it below: */
  4805. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4806. nommu_addchr(as_string, ch);
  4807. goto again;
  4808. }
  4809. if (ch == '$') {
  4810. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4811. debug_printf_parse("encode_string return 0: "
  4812. "parse_dollar returned 0 (error)\n");
  4813. return 0;
  4814. }
  4815. goto again;
  4816. }
  4817. #if ENABLE_HUSH_TICK
  4818. if (ch == '`') {
  4819. //unsigned pos = dest->length;
  4820. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4821. o_addchr(dest, 0x80 | '`');
  4822. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4823. return 0; /* error */
  4824. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4825. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4826. goto again;
  4827. }
  4828. #endif
  4829. o_addQchr(dest, ch);
  4830. goto again;
  4831. #undef as_string
  4832. }
  4833. /*
  4834. * Scan input until EOF or end_trigger char.
  4835. * Return a list of pipes to execute, or NULL on EOF
  4836. * or if end_trigger character is met.
  4837. * On syntax error, exit if shell is not interactive,
  4838. * reset parsing machinery and start parsing anew,
  4839. * or return ERR_PTR.
  4840. */
  4841. static struct pipe *parse_stream(char **pstring,
  4842. int *heredoc_cnt_ptr,
  4843. struct in_str *input,
  4844. int end_trigger)
  4845. {
  4846. struct parse_context ctx;
  4847. int heredoc_cnt;
  4848. /* Single-quote triggers a bypass of the main loop until its mate is
  4849. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4850. */
  4851. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4852. end_trigger ? end_trigger : 'X');
  4853. debug_enter();
  4854. initialize_context(&ctx);
  4855. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4856. * Preventing this:
  4857. */
  4858. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4859. /* We used to separate words on $IFS here. This was wrong.
  4860. * $IFS is used only for word splitting when $var is expanded,
  4861. * here we should use blank chars as separators, not $IFS
  4862. */
  4863. heredoc_cnt = 0;
  4864. while (1) {
  4865. const char *is_blank;
  4866. const char *is_special;
  4867. int ch;
  4868. int next;
  4869. int redir_fd;
  4870. redir_type redir_style;
  4871. ch = i_getch(input);
  4872. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4873. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4874. if (ch == EOF) {
  4875. struct pipe *pi;
  4876. if (heredoc_cnt) {
  4877. syntax_error_unterm_str("here document");
  4878. goto parse_error;
  4879. }
  4880. if (end_trigger == ')') {
  4881. syntax_error_unterm_ch('(');
  4882. goto parse_error;
  4883. }
  4884. if (end_trigger == '}') {
  4885. syntax_error_unterm_ch('{');
  4886. goto parse_error;
  4887. }
  4888. if (done_word(&ctx)) {
  4889. goto parse_error;
  4890. }
  4891. o_free_and_set_NULL(&ctx.word);
  4892. done_pipe(&ctx, PIPE_SEQ);
  4893. pi = ctx.list_head;
  4894. /* If we got nothing... */
  4895. /* (this makes bare "&" cmd a no-op.
  4896. * bash says: "syntax error near unexpected token '&'") */
  4897. if (pi->num_cmds == 0
  4898. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4899. ) {
  4900. free_pipe_list(pi);
  4901. pi = NULL;
  4902. }
  4903. #if !BB_MMU
  4904. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4905. if (pstring)
  4906. *pstring = ctx.as_string.data;
  4907. else
  4908. o_free(&ctx.as_string);
  4909. #endif
  4910. // heredoc_cnt must be 0 here anyway
  4911. //if (heredoc_cnt_ptr)
  4912. // *heredoc_cnt_ptr = heredoc_cnt;
  4913. debug_leave();
  4914. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4915. debug_printf_parse("parse_stream return %p\n", pi);
  4916. return pi;
  4917. }
  4918. /* Handle "'" and "\" first, as they won't play nice with
  4919. * i_peek_and_eat_bkslash_nl() anyway:
  4920. * echo z\\
  4921. * and
  4922. * echo '\
  4923. * '
  4924. * would break.
  4925. */
  4926. if (ch == '\\') {
  4927. ch = i_getch(input);
  4928. if (ch == '\n')
  4929. continue; /* drop \<newline>, get next char */
  4930. nommu_addchr(&ctx.as_string, '\\');
  4931. o_addchr(&ctx.word, '\\');
  4932. if (ch == EOF) {
  4933. /* Testcase: eval 'echo Ok\' */
  4934. /* bash-4.3.43 was removing backslash,
  4935. * but 4.4.19 retains it, most other shells too
  4936. */
  4937. continue; /* get next char */
  4938. }
  4939. /* Example: echo Hello \2>file
  4940. * we need to know that word 2 is quoted
  4941. */
  4942. ctx.word.has_quoted_part = 1;
  4943. nommu_addchr(&ctx.as_string, ch);
  4944. o_addchr(&ctx.word, ch);
  4945. continue; /* get next char */
  4946. }
  4947. nommu_addchr(&ctx.as_string, ch);
  4948. if (ch == '\'') {
  4949. ctx.word.has_quoted_part = 1;
  4950. next = i_getch(input);
  4951. if (next == '\'' && !ctx.pending_redirect)
  4952. goto insert_empty_quoted_str_marker;
  4953. ch = next;
  4954. while (1) {
  4955. if (ch == EOF) {
  4956. syntax_error_unterm_ch('\'');
  4957. goto parse_error;
  4958. }
  4959. nommu_addchr(&ctx.as_string, ch);
  4960. if (ch == '\'')
  4961. break;
  4962. if (ch == SPECIAL_VAR_SYMBOL) {
  4963. /* Convert raw ^C to corresponding special variable reference */
  4964. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4965. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4966. }
  4967. o_addqchr(&ctx.word, ch);
  4968. ch = i_getch(input);
  4969. }
  4970. continue; /* get next char */
  4971. }
  4972. next = '\0';
  4973. if (ch != '\n')
  4974. next = i_peek_and_eat_bkslash_nl(input);
  4975. is_special = "{}<>;&|()#" /* special outside of "str" */
  4976. "$\"" IF_HUSH_TICK("`") /* always special */
  4977. SPECIAL_VAR_SYMBOL_STR;
  4978. /* Are { and } special here? */
  4979. if (ctx.command->argv /* word [word]{... - non-special */
  4980. || ctx.word.length /* word{... - non-special */
  4981. || ctx.word.has_quoted_part /* ""{... - non-special */
  4982. || (next != ';' /* }; - special */
  4983. && next != ')' /* }) - special */
  4984. && next != '(' /* {( - special */
  4985. && next != '&' /* }& and }&& ... - special */
  4986. && next != '|' /* }|| ... - special */
  4987. && !strchr(defifs, next) /* {word - non-special */
  4988. )
  4989. ) {
  4990. /* They are not special, skip "{}" */
  4991. is_special += 2;
  4992. }
  4993. is_special = strchr(is_special, ch);
  4994. is_blank = strchr(defifs, ch);
  4995. if (!is_special && !is_blank) { /* ordinary char */
  4996. ordinary_char:
  4997. o_addQchr(&ctx.word, ch);
  4998. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  4999. || ctx.is_assignment == WORD_IS_KEYWORD)
  5000. && ch == '='
  5001. && is_well_formed_var_name(ctx.word.data, '=')
  5002. ) {
  5003. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5004. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5005. }
  5006. continue;
  5007. }
  5008. if (is_blank) {
  5009. #if ENABLE_HUSH_LINENO_VAR
  5010. /* Case:
  5011. * "while ...; do<whitespace><newline>
  5012. * cmd ..."
  5013. * would think that "cmd" starts in <whitespace> -
  5014. * i.e., at the previous line.
  5015. * We need to skip all whitespace before newlines.
  5016. */
  5017. while (ch != '\n') {
  5018. next = i_peek(input);
  5019. if (next != ' ' && next != '\t' && next != '\n')
  5020. break; /* next char is not ws */
  5021. ch = i_getch(input);
  5022. }
  5023. /* ch == last eaten whitespace char */
  5024. #endif
  5025. if (done_word(&ctx)) {
  5026. goto parse_error;
  5027. }
  5028. if (ch == '\n') {
  5029. /* Is this a case when newline is simply ignored?
  5030. * Some examples:
  5031. * "cmd | <newline> cmd ..."
  5032. * "case ... in <newline> word) ..."
  5033. */
  5034. if (IS_NULL_CMD(ctx.command)
  5035. && ctx.word.length == 0
  5036. && !ctx.word.has_quoted_part
  5037. && heredoc_cnt == 0
  5038. ) {
  5039. /* This newline can be ignored. But...
  5040. * Without check #1, interactive shell
  5041. * ignores even bare <newline>,
  5042. * and shows the continuation prompt:
  5043. * ps1_prompt$ <enter>
  5044. * ps2> _ <=== wrong, should be ps1
  5045. * Without check #2, "cmd & <newline>"
  5046. * is similarly mistreated.
  5047. * (BTW, this makes "cmd & cmd"
  5048. * and "cmd && cmd" non-orthogonal.
  5049. * Really, ask yourself, why
  5050. * "cmd && <newline>" doesn't start
  5051. * cmd but waits for more input?
  5052. * The only reason is that it might be
  5053. * a "cmd1 && <nl> cmd2 &" construct,
  5054. * cmd1 may need to run in BG).
  5055. */
  5056. struct pipe *pi = ctx.list_head;
  5057. if (pi->num_cmds != 0 /* check #1 */
  5058. && pi->followup != PIPE_BG /* check #2 */
  5059. ) {
  5060. continue;
  5061. }
  5062. }
  5063. /* Treat newline as a command separator. */
  5064. done_pipe(&ctx, PIPE_SEQ);
  5065. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5066. if (heredoc_cnt) {
  5067. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5068. if (heredoc_cnt != 0)
  5069. goto parse_error;
  5070. }
  5071. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5072. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5073. ch = ';';
  5074. /* note: if (is_blank) continue;
  5075. * will still trigger for us */
  5076. }
  5077. }
  5078. /* "cmd}" or "cmd }..." without semicolon or &:
  5079. * } is an ordinary char in this case, even inside { cmd; }
  5080. * Pathological example: { ""}; } should exec "}" cmd
  5081. */
  5082. if (ch == '}') {
  5083. if (ctx.word.length != 0 /* word} */
  5084. || ctx.word.has_quoted_part /* ""} */
  5085. ) {
  5086. goto ordinary_char;
  5087. }
  5088. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5089. /* Generally, there should be semicolon: "cmd; }"
  5090. * However, bash allows to omit it if "cmd" is
  5091. * a group. Examples:
  5092. * { { echo 1; } }
  5093. * {(echo 1)}
  5094. * { echo 0 >&2 | { echo 1; } }
  5095. * { while false; do :; done }
  5096. * { case a in b) ;; esac }
  5097. */
  5098. if (ctx.command->group)
  5099. goto term_group;
  5100. goto ordinary_char;
  5101. }
  5102. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5103. /* Can't be an end of {cmd}, skip the check */
  5104. goto skip_end_trigger;
  5105. /* else: } does terminate a group */
  5106. }
  5107. term_group:
  5108. if (end_trigger && end_trigger == ch
  5109. && (ch != ';' || heredoc_cnt == 0)
  5110. #if ENABLE_HUSH_CASE
  5111. && (ch != ')'
  5112. || ctx.ctx_res_w != RES_MATCH
  5113. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5114. )
  5115. #endif
  5116. ) {
  5117. if (done_word(&ctx)) {
  5118. goto parse_error;
  5119. }
  5120. done_pipe(&ctx, PIPE_SEQ);
  5121. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5122. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5123. /* Do we sit outside of any if's, loops or case's? */
  5124. if (!HAS_KEYWORDS
  5125. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5126. ) {
  5127. o_free_and_set_NULL(&ctx.word);
  5128. #if !BB_MMU
  5129. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5130. if (pstring)
  5131. *pstring = ctx.as_string.data;
  5132. else
  5133. o_free(&ctx.as_string);
  5134. #endif
  5135. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5136. /* Example: bare "{ }", "()" */
  5137. G.last_exitcode = 2; /* bash compat */
  5138. syntax_error_unexpected_ch(ch);
  5139. goto parse_error2;
  5140. }
  5141. if (heredoc_cnt_ptr)
  5142. *heredoc_cnt_ptr = heredoc_cnt;
  5143. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5144. debug_printf_parse("parse_stream return %p: "
  5145. "end_trigger char found\n",
  5146. ctx.list_head);
  5147. debug_leave();
  5148. return ctx.list_head;
  5149. }
  5150. }
  5151. if (is_blank)
  5152. continue;
  5153. /* Catch <, > before deciding whether this word is
  5154. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5155. switch (ch) {
  5156. case '>':
  5157. redir_fd = redirect_opt_num(&ctx.word);
  5158. if (done_word(&ctx)) {
  5159. goto parse_error;
  5160. }
  5161. redir_style = REDIRECT_OVERWRITE;
  5162. if (next == '>') {
  5163. redir_style = REDIRECT_APPEND;
  5164. ch = i_getch(input);
  5165. nommu_addchr(&ctx.as_string, ch);
  5166. }
  5167. #if 0
  5168. else if (next == '(') {
  5169. syntax_error(">(process) not supported");
  5170. goto parse_error;
  5171. }
  5172. #endif
  5173. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5174. goto parse_error;
  5175. continue; /* get next char */
  5176. case '<':
  5177. redir_fd = redirect_opt_num(&ctx.word);
  5178. if (done_word(&ctx)) {
  5179. goto parse_error;
  5180. }
  5181. redir_style = REDIRECT_INPUT;
  5182. if (next == '<') {
  5183. redir_style = REDIRECT_HEREDOC;
  5184. heredoc_cnt++;
  5185. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5186. ch = i_getch(input);
  5187. nommu_addchr(&ctx.as_string, ch);
  5188. } else if (next == '>') {
  5189. redir_style = REDIRECT_IO;
  5190. ch = i_getch(input);
  5191. nommu_addchr(&ctx.as_string, ch);
  5192. }
  5193. #if 0
  5194. else if (next == '(') {
  5195. syntax_error("<(process) not supported");
  5196. goto parse_error;
  5197. }
  5198. #endif
  5199. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5200. goto parse_error;
  5201. continue; /* get next char */
  5202. case '#':
  5203. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5204. /* skip "#comment" */
  5205. /* note: we do not add it to &ctx.as_string */
  5206. /* TODO: in bash:
  5207. * comment inside $() goes to the next \n, even inside quoted string (!):
  5208. * cmd "$(cmd2 #comment)" - syntax error
  5209. * cmd "`cmd2 #comment`" - ok
  5210. * We accept both (comment ends where command subst ends, in both cases).
  5211. */
  5212. while (1) {
  5213. ch = i_peek(input);
  5214. if (ch == '\n') {
  5215. nommu_addchr(&ctx.as_string, '\n');
  5216. break;
  5217. }
  5218. ch = i_getch(input);
  5219. if (ch == EOF)
  5220. break;
  5221. }
  5222. continue; /* get next char */
  5223. }
  5224. break;
  5225. }
  5226. skip_end_trigger:
  5227. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5228. /* check that we are not in word in "a=1 2>word b=1": */
  5229. && !ctx.pending_redirect
  5230. ) {
  5231. /* ch is a special char and thus this word
  5232. * cannot be an assignment */
  5233. ctx.is_assignment = NOT_ASSIGNMENT;
  5234. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5235. }
  5236. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5237. switch (ch) {
  5238. case SPECIAL_VAR_SYMBOL:
  5239. /* Convert raw ^C to corresponding special variable reference */
  5240. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5241. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5242. /* fall through */
  5243. case '#':
  5244. /* non-comment #: "echo a#b" etc */
  5245. o_addchr(&ctx.word, ch);
  5246. continue; /* get next char */
  5247. case '$':
  5248. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5249. debug_printf_parse("parse_stream parse error: "
  5250. "parse_dollar returned 0 (error)\n");
  5251. goto parse_error;
  5252. }
  5253. continue; /* get next char */
  5254. case '"':
  5255. ctx.word.has_quoted_part = 1;
  5256. if (next == '"' && !ctx.pending_redirect) {
  5257. i_getch(input); /* eat second " */
  5258. insert_empty_quoted_str_marker:
  5259. nommu_addchr(&ctx.as_string, next);
  5260. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5261. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5262. continue; /* get next char */
  5263. }
  5264. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5265. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5266. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5267. goto parse_error;
  5268. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5269. continue; /* get next char */
  5270. #if ENABLE_HUSH_TICK
  5271. case '`': {
  5272. USE_FOR_NOMMU(unsigned pos;)
  5273. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5274. o_addchr(&ctx.word, '`');
  5275. USE_FOR_NOMMU(pos = ctx.word.length;)
  5276. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5277. goto parse_error;
  5278. # if !BB_MMU
  5279. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5280. o_addchr(&ctx.as_string, '`');
  5281. # endif
  5282. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5283. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5284. continue; /* get next char */
  5285. }
  5286. #endif
  5287. case ';':
  5288. #if ENABLE_HUSH_CASE
  5289. case_semi:
  5290. #endif
  5291. if (done_word(&ctx)) {
  5292. goto parse_error;
  5293. }
  5294. done_pipe(&ctx, PIPE_SEQ);
  5295. #if ENABLE_HUSH_CASE
  5296. /* Eat multiple semicolons, detect
  5297. * whether it means something special */
  5298. while (1) {
  5299. ch = i_peek_and_eat_bkslash_nl(input);
  5300. if (ch != ';')
  5301. break;
  5302. ch = i_getch(input);
  5303. nommu_addchr(&ctx.as_string, ch);
  5304. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5305. ctx.ctx_dsemicolon = 1;
  5306. ctx.ctx_res_w = RES_MATCH;
  5307. break;
  5308. }
  5309. }
  5310. #endif
  5311. new_cmd:
  5312. /* We just finished a cmd. New one may start
  5313. * with an assignment */
  5314. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5315. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5316. continue; /* get next char */
  5317. case '&':
  5318. if (done_word(&ctx)) {
  5319. goto parse_error;
  5320. }
  5321. if (next == '&') {
  5322. ch = i_getch(input);
  5323. nommu_addchr(&ctx.as_string, ch);
  5324. done_pipe(&ctx, PIPE_AND);
  5325. } else {
  5326. done_pipe(&ctx, PIPE_BG);
  5327. }
  5328. goto new_cmd;
  5329. case '|':
  5330. if (done_word(&ctx)) {
  5331. goto parse_error;
  5332. }
  5333. #if ENABLE_HUSH_CASE
  5334. if (ctx.ctx_res_w == RES_MATCH)
  5335. break; /* we are in case's "word | word)" */
  5336. #endif
  5337. if (next == '|') { /* || */
  5338. ch = i_getch(input);
  5339. nommu_addchr(&ctx.as_string, ch);
  5340. done_pipe(&ctx, PIPE_OR);
  5341. } else {
  5342. /* we could pick up a file descriptor choice here
  5343. * with redirect_opt_num(), but bash doesn't do it.
  5344. * "echo foo 2| cat" yields "foo 2". */
  5345. done_command(&ctx);
  5346. }
  5347. goto new_cmd;
  5348. case '(':
  5349. #if ENABLE_HUSH_CASE
  5350. /* "case... in [(]word)..." - skip '(' */
  5351. if (ctx.ctx_res_w == RES_MATCH
  5352. && ctx.command->argv == NULL /* not (word|(... */
  5353. && ctx.word.length == 0 /* not word(... */
  5354. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5355. ) {
  5356. continue; /* get next char */
  5357. }
  5358. #endif
  5359. /* fall through */
  5360. case '{': {
  5361. int n = parse_group(&ctx, input, ch);
  5362. if (n < 0) {
  5363. goto parse_error;
  5364. }
  5365. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5366. heredoc_cnt += n;
  5367. goto new_cmd;
  5368. }
  5369. case ')':
  5370. #if ENABLE_HUSH_CASE
  5371. if (ctx.ctx_res_w == RES_MATCH)
  5372. goto case_semi;
  5373. #endif
  5374. case '}':
  5375. /* proper use of this character is caught by end_trigger:
  5376. * if we see {, we call parse_group(..., end_trigger='}')
  5377. * and it will match } earlier (not here). */
  5378. G.last_exitcode = 2;
  5379. syntax_error_unexpected_ch(ch);
  5380. goto parse_error2;
  5381. default:
  5382. if (HUSH_DEBUG)
  5383. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5384. }
  5385. } /* while (1) */
  5386. parse_error:
  5387. G.last_exitcode = 1;
  5388. parse_error2:
  5389. {
  5390. struct parse_context *pctx;
  5391. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5392. /* Clean up allocated tree.
  5393. * Sample for finding leaks on syntax error recovery path.
  5394. * Run it from interactive shell, watch pmap `pidof hush`.
  5395. * while if false; then false; fi; do break; fi
  5396. * Samples to catch leaks at execution:
  5397. * while if (true | { true;}); then echo ok; fi; do break; done
  5398. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5399. */
  5400. pctx = &ctx;
  5401. do {
  5402. /* Update pipe/command counts,
  5403. * otherwise freeing may miss some */
  5404. done_pipe(pctx, PIPE_SEQ);
  5405. debug_printf_clean("freeing list %p from ctx %p\n",
  5406. pctx->list_head, pctx);
  5407. debug_print_tree(pctx->list_head, 0);
  5408. free_pipe_list(pctx->list_head);
  5409. debug_printf_clean("freed list %p\n", pctx->list_head);
  5410. #if !BB_MMU
  5411. o_free(&pctx->as_string);
  5412. #endif
  5413. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5414. if (pctx != &ctx) {
  5415. free(pctx);
  5416. }
  5417. IF_HAS_KEYWORDS(pctx = p2;)
  5418. } while (HAS_KEYWORDS && pctx);
  5419. o_free(&ctx.word);
  5420. #if !BB_MMU
  5421. if (pstring)
  5422. *pstring = NULL;
  5423. #endif
  5424. debug_leave();
  5425. return ERR_PTR;
  5426. }
  5427. }
  5428. /*** Execution routines ***/
  5429. /* Expansion can recurse, need forward decls: */
  5430. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5431. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5432. expand_string_to_string(str)
  5433. #endif
  5434. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5435. #if ENABLE_HUSH_TICK
  5436. static int process_command_subs(o_string *dest, const char *s);
  5437. #endif
  5438. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5439. /* expand_strvec_to_strvec() takes a list of strings, expands
  5440. * all variable references within and returns a pointer to
  5441. * a list of expanded strings, possibly with larger number
  5442. * of strings. (Think VAR="a b"; echo $VAR).
  5443. * This new list is allocated as a single malloc block.
  5444. * NULL-terminated list of char* pointers is at the beginning of it,
  5445. * followed by strings themselves.
  5446. * Caller can deallocate entire list by single free(list). */
  5447. /* A horde of its helpers come first: */
  5448. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5449. {
  5450. while (--len >= 0) {
  5451. char c = *str++;
  5452. #if ENABLE_HUSH_BRACE_EXPANSION
  5453. if (c == '{' || c == '}') {
  5454. /* { -> \{, } -> \} */
  5455. o_addchr(o, '\\');
  5456. /* And now we want to add { or } and continue:
  5457. * o_addchr(o, c);
  5458. * continue;
  5459. * luckily, just falling through achieves this.
  5460. */
  5461. }
  5462. #endif
  5463. o_addchr(o, c);
  5464. if (c == '\\') {
  5465. /* \z -> \\\z; \<eol> -> \\<eol> */
  5466. o_addchr(o, '\\');
  5467. if (len) {
  5468. len--;
  5469. o_addchr(o, '\\');
  5470. o_addchr(o, *str++);
  5471. }
  5472. }
  5473. }
  5474. }
  5475. /* Store given string, finalizing the word and starting new one whenever
  5476. * we encounter IFS char(s). This is used for expanding variable values.
  5477. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5478. * Return in output->ended_in_ifs:
  5479. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5480. */
  5481. static int expand_on_ifs(o_string *output, int n, const char *str)
  5482. {
  5483. int last_is_ifs = 0;
  5484. while (1) {
  5485. int word_len;
  5486. if (!*str) /* EOL - do not finalize word */
  5487. break;
  5488. word_len = strcspn(str, G.ifs);
  5489. if (word_len) {
  5490. /* We have WORD_LEN leading non-IFS chars */
  5491. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5492. o_addblock(output, str, word_len);
  5493. } else {
  5494. /* Protect backslashes against globbing up :)
  5495. * Example: "v='\*'; echo b$v" prints "b\*"
  5496. * (and does not try to glob on "*")
  5497. */
  5498. o_addblock_duplicate_backslash(output, str, word_len);
  5499. /*/ Why can't we do it easier? */
  5500. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5501. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5502. }
  5503. last_is_ifs = 0;
  5504. str += word_len;
  5505. if (!*str) /* EOL - do not finalize word */
  5506. break;
  5507. }
  5508. /* We know str here points to at least one IFS char */
  5509. last_is_ifs = 1;
  5510. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5511. if (!*str) /* EOL - do not finalize word */
  5512. break;
  5513. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5514. && strchr(G.ifs, *str) /* the second check would fail */
  5515. ) {
  5516. /* This is a non-whitespace $IFS char */
  5517. /* Skip it and IFS whitespace chars, start new word */
  5518. str++;
  5519. str += strspn(str, G.ifs_whitespace);
  5520. goto new_word;
  5521. }
  5522. /* Start new word... but not always! */
  5523. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5524. if (output->has_quoted_part
  5525. /*
  5526. * Case "v=' a'; echo $v":
  5527. * here nothing precedes the space in $v expansion,
  5528. * therefore we should not finish the word
  5529. * (IOW: if there *is* word to finalize, only then do it):
  5530. * It's okay if this accesses the byte before first argv[]:
  5531. * past call to o_save_ptr() cleared it to zero byte
  5532. * (grep for -prev-ifs-check-).
  5533. */
  5534. || output->data[output->length - 1]
  5535. ) {
  5536. new_word:
  5537. o_addchr(output, '\0');
  5538. debug_print_list("expand_on_ifs", output, n);
  5539. n = o_save_ptr(output, n);
  5540. }
  5541. }
  5542. output->ended_in_ifs = last_is_ifs;
  5543. debug_print_list("expand_on_ifs[1]", output, n);
  5544. return n;
  5545. }
  5546. /* Helper to expand $((...)) and heredoc body. These act as if
  5547. * they are in double quotes, with the exception that they are not :).
  5548. * Just the rules are similar: "expand only $var and `cmd`"
  5549. *
  5550. * Returns malloced string.
  5551. * As an optimization, we return NULL if expansion is not needed.
  5552. */
  5553. static char *encode_then_expand_string(const char *str)
  5554. {
  5555. char *exp_str;
  5556. struct in_str input;
  5557. o_string dest = NULL_O_STRING;
  5558. const char *cp;
  5559. cp = str;
  5560. for (;;) {
  5561. if (!*cp) return NULL; /* string has no special chars */
  5562. if (*cp == '$') break;
  5563. if (*cp == '\\') break;
  5564. #if ENABLE_HUSH_TICK
  5565. if (*cp == '`') break;
  5566. #endif
  5567. cp++;
  5568. }
  5569. /* We need to expand. Example:
  5570. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5571. */
  5572. setup_string_in_str(&input, str);
  5573. encode_string(NULL, &dest, &input, EOF);
  5574. //TODO: error check (encode_string returns 0 on error)?
  5575. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5576. exp_str = expand_string_to_string(dest.data,
  5577. EXP_FLAG_ESC_GLOB_CHARS,
  5578. /*unbackslash:*/ 1
  5579. );
  5580. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5581. o_free(&dest);
  5582. return exp_str;
  5583. }
  5584. static const char *first_special_char_in_vararg(const char *cp)
  5585. {
  5586. for (;;) {
  5587. if (!*cp) return NULL; /* string has no special chars */
  5588. if (*cp == '$') return cp;
  5589. if (*cp == '\\') return cp;
  5590. if (*cp == '\'') return cp;
  5591. if (*cp == '"') return cp;
  5592. #if ENABLE_HUSH_TICK
  5593. if (*cp == '`') return cp;
  5594. #endif
  5595. /* dquoted "${x:+ARG}" should not glob, therefore
  5596. * '*' et al require some non-literal processing: */
  5597. if (*cp == '*') return cp;
  5598. if (*cp == '?') return cp;
  5599. if (*cp == '[') return cp;
  5600. cp++;
  5601. }
  5602. }
  5603. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5604. * These can contain single- and double-quoted strings,
  5605. * and treated as if the ARG string is initially unquoted. IOW:
  5606. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5607. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5608. * (word splitting and globbing of the ${var...} result).
  5609. */
  5610. #if !BASH_PATTERN_SUBST
  5611. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5612. encode_then_expand_vararg(str, handle_squotes)
  5613. #endif
  5614. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5615. {
  5616. #if !BASH_PATTERN_SUBST
  5617. const int do_unbackslash = 0;
  5618. #endif
  5619. char *exp_str;
  5620. struct in_str input;
  5621. o_string dest = NULL_O_STRING;
  5622. if (!first_special_char_in_vararg(str)) {
  5623. /* string has no special chars */
  5624. return NULL;
  5625. }
  5626. setup_string_in_str(&input, str);
  5627. dest.data = xzalloc(1); /* start as "", not as NULL */
  5628. exp_str = NULL;
  5629. for (;;) {
  5630. int ch;
  5631. ch = i_getch(&input);
  5632. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5633. __func__, ch, ch, !!dest.o_expflags);
  5634. if (!dest.o_expflags) {
  5635. if (ch == EOF)
  5636. break;
  5637. if (handle_squotes && ch == '\'') {
  5638. if (!add_till_single_quote_dquoted(&dest, &input))
  5639. goto ret; /* error */
  5640. continue;
  5641. }
  5642. }
  5643. if (ch == EOF) {
  5644. syntax_error_unterm_ch('"');
  5645. goto ret; /* error */
  5646. }
  5647. if (ch == '"') {
  5648. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5649. continue;
  5650. }
  5651. if (ch == '\\') {
  5652. ch = i_getch(&input);
  5653. if (ch == EOF) {
  5654. //example? error message? syntax_error_unterm_ch('"');
  5655. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5656. goto ret;
  5657. }
  5658. o_addqchr(&dest, ch);
  5659. continue;
  5660. }
  5661. if (ch == '$') {
  5662. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5663. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5664. goto ret;
  5665. }
  5666. continue;
  5667. }
  5668. #if ENABLE_HUSH_TICK
  5669. if (ch == '`') {
  5670. //unsigned pos = dest->length;
  5671. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5672. o_addchr(&dest, 0x80 | '`');
  5673. if (!add_till_backquote(&dest, &input,
  5674. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5675. )
  5676. ) {
  5677. goto ret; /* error */
  5678. }
  5679. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5680. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5681. continue;
  5682. }
  5683. #endif
  5684. o_addQchr(&dest, ch);
  5685. } /* for (;;) */
  5686. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5687. exp_str = expand_string_to_string(dest.data,
  5688. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5689. do_unbackslash
  5690. );
  5691. ret:
  5692. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5693. o_free(&dest);
  5694. return exp_str;
  5695. }
  5696. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5697. */
  5698. static int encode_then_append_var_plusminus(o_string *output, int n,
  5699. char *str, int dquoted)
  5700. {
  5701. struct in_str input;
  5702. o_string dest = NULL_O_STRING;
  5703. if (!first_special_char_in_vararg(str)
  5704. && '\0' == str[strcspn(str, G.ifs)]
  5705. ) {
  5706. /* string has no special chars
  5707. * && string has no $IFS chars
  5708. */
  5709. return expand_vars_to_list(output, n, str);
  5710. }
  5711. setup_string_in_str(&input, str);
  5712. for (;;) {
  5713. int ch;
  5714. ch = i_getch(&input);
  5715. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5716. __func__, ch, ch, dest.o_expflags);
  5717. if (!dest.o_expflags) {
  5718. if (ch == EOF)
  5719. break;
  5720. if (!dquoted && strchr(G.ifs, ch)) {
  5721. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5722. * do not assume we are at the start of the word (PREFIX above).
  5723. */
  5724. if (dest.data) {
  5725. n = expand_vars_to_list(output, n, dest.data);
  5726. o_free_and_set_NULL(&dest);
  5727. o_addchr(output, '\0');
  5728. n = o_save_ptr(output, n); /* create next word */
  5729. } else
  5730. if (output->length != o_get_last_ptr(output, n)
  5731. || output->has_quoted_part
  5732. ) {
  5733. /* For these cases:
  5734. * f() { for i; do echo "|$i|"; done; }; x=x
  5735. * f a${x:+ }b # 1st condition
  5736. * |a|
  5737. * |b|
  5738. * f ""${x:+ }b # 2nd condition
  5739. * ||
  5740. * |b|
  5741. */
  5742. o_addchr(output, '\0');
  5743. n = o_save_ptr(output, n); /* create next word */
  5744. }
  5745. continue;
  5746. }
  5747. if (!dquoted && ch == '\'') {
  5748. if (!add_till_single_quote_dquoted(&dest, &input))
  5749. goto ret; /* error */
  5750. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5751. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5752. continue;
  5753. }
  5754. }
  5755. if (ch == EOF) {
  5756. syntax_error_unterm_ch('"');
  5757. goto ret; /* error */
  5758. }
  5759. if (ch == '"') {
  5760. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5761. if (dest.o_expflags) {
  5762. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5763. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5764. }
  5765. continue;
  5766. }
  5767. if (ch == '\\') {
  5768. ch = i_getch(&input);
  5769. if (ch == EOF) {
  5770. //example? error message? syntax_error_unterm_ch('"');
  5771. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5772. goto ret;
  5773. }
  5774. o_addqchr(&dest, ch);
  5775. continue;
  5776. }
  5777. if (ch == '$') {
  5778. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5779. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5780. goto ret;
  5781. }
  5782. continue;
  5783. }
  5784. #if ENABLE_HUSH_TICK
  5785. if (ch == '`') {
  5786. //unsigned pos = dest->length;
  5787. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5788. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5789. if (!add_till_backquote(&dest, &input,
  5790. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5791. )
  5792. ) {
  5793. goto ret; /* error */
  5794. }
  5795. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5796. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5797. continue;
  5798. }
  5799. #endif
  5800. if (dquoted) {
  5801. /* Always glob-protect if in dquotes:
  5802. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5803. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5804. */
  5805. o_addqchr(&dest, ch);
  5806. } else {
  5807. /* Glob-protect only if char is quoted:
  5808. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5809. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5810. */
  5811. o_addQchr(&dest, ch);
  5812. }
  5813. } /* for (;;) */
  5814. if (dest.data) {
  5815. n = expand_vars_to_list(output, n, dest.data);
  5816. }
  5817. ret:
  5818. o_free(&dest);
  5819. return n;
  5820. }
  5821. #if ENABLE_FEATURE_SH_MATH
  5822. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5823. {
  5824. arith_state_t math_state;
  5825. arith_t res;
  5826. char *exp_str;
  5827. math_state.lookupvar = get_local_var_value;
  5828. math_state.setvar = set_local_var_from_halves;
  5829. //math_state.endofname = endofname;
  5830. exp_str = encode_then_expand_string(arg);
  5831. res = arith(&math_state, exp_str ? exp_str : arg);
  5832. free(exp_str);
  5833. if (errmsg_p)
  5834. *errmsg_p = math_state.errmsg;
  5835. if (math_state.errmsg)
  5836. msg_and_die_if_script(math_state.errmsg);
  5837. return res;
  5838. }
  5839. #endif
  5840. #if BASH_PATTERN_SUBST
  5841. /* ${var/[/]pattern[/repl]} helpers */
  5842. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5843. {
  5844. while (1) {
  5845. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5846. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5847. if (end) {
  5848. *size = end - val;
  5849. return val;
  5850. }
  5851. if (*val == '\0')
  5852. return NULL;
  5853. /* Optimization: if "*pat" did not match the start of "string",
  5854. * we know that "tring", "ring" etc will not match too:
  5855. */
  5856. if (pattern[0] == '*')
  5857. return NULL;
  5858. val++;
  5859. }
  5860. }
  5861. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5862. {
  5863. char *result = NULL;
  5864. unsigned res_len = 0;
  5865. unsigned repl_len = strlen(repl);
  5866. /* Null pattern never matches, including if "var" is empty */
  5867. if (!pattern[0])
  5868. return result; /* NULL, no replaces happened */
  5869. while (1) {
  5870. int size;
  5871. char *s = strstr_pattern(val, pattern, &size);
  5872. if (!s)
  5873. break;
  5874. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5875. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5876. res_len += (s - val) + repl_len;
  5877. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5878. val = s + size;
  5879. if (exp_op == '/')
  5880. break;
  5881. }
  5882. if (*val && result) {
  5883. result = xrealloc(result, res_len + strlen(val) + 1);
  5884. strcpy(result + res_len, val);
  5885. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5886. }
  5887. debug_printf_varexp("result:'%s'\n", result);
  5888. return result;
  5889. }
  5890. #endif /* BASH_PATTERN_SUBST */
  5891. static int append_str_maybe_ifs_split(o_string *output, int n,
  5892. int first_ch, const char *val)
  5893. {
  5894. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5895. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5896. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5897. if (val && val[0])
  5898. n = expand_on_ifs(output, n, val);
  5899. } else { /* quoted "$VAR" */
  5900. output->has_quoted_part = 1;
  5901. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5902. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5903. if (val && val[0])
  5904. o_addQstr(output, val);
  5905. }
  5906. return n;
  5907. }
  5908. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5909. */
  5910. static NOINLINE int expand_one_var(o_string *output, int n,
  5911. int first_ch, char *arg, char **pp)
  5912. {
  5913. const char *val;
  5914. char *to_be_freed;
  5915. char *p;
  5916. char *var;
  5917. char exp_op;
  5918. char exp_save = exp_save; /* for compiler */
  5919. char *exp_saveptr; /* points to expansion operator */
  5920. char *exp_word = exp_word; /* for compiler */
  5921. char arg0;
  5922. val = NULL;
  5923. to_be_freed = NULL;
  5924. p = *pp;
  5925. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5926. var = arg;
  5927. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5928. arg0 = arg[0];
  5929. arg[0] = (arg0 & 0x7f);
  5930. exp_op = 0;
  5931. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5932. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5933. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5934. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5935. ) {
  5936. /* It must be length operator: ${#var} */
  5937. var++;
  5938. exp_op = 'L';
  5939. } else {
  5940. /* Maybe handle parameter expansion */
  5941. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5942. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5943. ) {
  5944. /* ${?:0}, ${#[:]%0} etc */
  5945. exp_saveptr = var + 1;
  5946. } else {
  5947. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5948. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5949. }
  5950. exp_op = exp_save = *exp_saveptr;
  5951. if (exp_op) {
  5952. exp_word = exp_saveptr + 1;
  5953. if (exp_op == ':') {
  5954. exp_op = *exp_word++;
  5955. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5956. if (BASH_SUBSTR
  5957. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5958. ) {
  5959. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5960. exp_op = ':';
  5961. exp_word--;
  5962. }
  5963. }
  5964. *exp_saveptr = '\0';
  5965. } /* else: it's not an expansion op, but bare ${var} */
  5966. }
  5967. /* Look up the variable in question */
  5968. if (isdigit(var[0])) {
  5969. /* parse_dollar should have vetted var for us */
  5970. int nn = xatoi_positive(var);
  5971. if (nn < G.global_argc)
  5972. val = G.global_argv[nn];
  5973. /* else val remains NULL: $N with too big N */
  5974. } else {
  5975. switch (var[0]) {
  5976. case '$': /* pid */
  5977. val = utoa(G.root_pid);
  5978. break;
  5979. case '!': /* bg pid */
  5980. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  5981. break;
  5982. case '?': /* exitcode */
  5983. val = utoa(G.last_exitcode);
  5984. break;
  5985. case '#': /* argc */
  5986. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  5987. break;
  5988. default:
  5989. val = get_local_var_value(var);
  5990. }
  5991. }
  5992. /* Handle any expansions */
  5993. if (exp_op == 'L') {
  5994. reinit_unicode_for_hush();
  5995. debug_printf_expand("expand: length(%s)=", val);
  5996. val = utoa(val ? unicode_strlen(val) : 0);
  5997. debug_printf_expand("%s\n", val);
  5998. } else if (exp_op) {
  5999. if (exp_op == '%' || exp_op == '#') {
  6000. /* Standard-mandated substring removal ops:
  6001. * ${parameter%word} - remove smallest suffix pattern
  6002. * ${parameter%%word} - remove largest suffix pattern
  6003. * ${parameter#word} - remove smallest prefix pattern
  6004. * ${parameter##word} - remove largest prefix pattern
  6005. *
  6006. * Word is expanded to produce a glob pattern.
  6007. * Then var's value is matched to it and matching part removed.
  6008. */
  6009. //FIXME: ${x#...${...}...}
  6010. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6011. //inner ${...} may have side effects!
  6012. if (val && val[0]) {
  6013. char *t;
  6014. char *exp_exp_word;
  6015. char *loc;
  6016. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6017. if (exp_op == *exp_word) /* ## or %% */
  6018. exp_word++;
  6019. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6020. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6021. if (exp_exp_word)
  6022. exp_word = exp_exp_word;
  6023. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6024. /*
  6025. * HACK ALERT. We depend here on the fact that
  6026. * G.global_argv and results of utoa and get_local_var_value
  6027. * are actually in writable memory:
  6028. * scan_and_match momentarily stores NULs there.
  6029. */
  6030. t = (char*)val;
  6031. loc = scan_and_match(t, exp_word, scan_flags);
  6032. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6033. free(exp_exp_word);
  6034. if (loc) { /* match was found */
  6035. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6036. val = loc; /* take right part */
  6037. else /* %[%] */
  6038. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6039. }
  6040. }
  6041. }
  6042. #if BASH_PATTERN_SUBST
  6043. else if (exp_op == '/' || exp_op == '\\') {
  6044. /* It's ${var/[/]pattern[/repl]} thing.
  6045. * Note that in encoded form it has TWO parts:
  6046. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6047. * and if // is used, it is encoded as \:
  6048. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6049. */
  6050. if (val && val[0]) {
  6051. /* pattern uses non-standard expansion.
  6052. * repl should be unbackslashed and globbed
  6053. * by the usual expansion rules:
  6054. * >az >bz
  6055. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6056. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6057. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6058. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6059. * (note that a*z _pattern_ is never globbed!)
  6060. */
  6061. char *pattern, *repl, *t;
  6062. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6063. if (!pattern)
  6064. pattern = xstrdup(exp_word);
  6065. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6066. *p++ = SPECIAL_VAR_SYMBOL;
  6067. exp_word = p;
  6068. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6069. *p = '\0';
  6070. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6071. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6072. /* HACK ALERT. We depend here on the fact that
  6073. * G.global_argv and results of utoa and get_local_var_value
  6074. * are actually in writable memory:
  6075. * replace_pattern momentarily stores NULs there. */
  6076. t = (char*)val;
  6077. to_be_freed = replace_pattern(t,
  6078. pattern,
  6079. (repl ? repl : exp_word),
  6080. exp_op);
  6081. if (to_be_freed) /* at least one replace happened */
  6082. val = to_be_freed;
  6083. free(pattern);
  6084. free(repl);
  6085. } else {
  6086. /* Empty variable always gives nothing */
  6087. // "v=''; echo ${v/*/w}" prints "", not "w"
  6088. /* Just skip "replace" part */
  6089. *p++ = SPECIAL_VAR_SYMBOL;
  6090. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6091. *p = '\0';
  6092. }
  6093. }
  6094. #endif /* BASH_PATTERN_SUBST */
  6095. else if (exp_op == ':') {
  6096. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6097. /* It's ${var:N[:M]} bashism.
  6098. * Note that in encoded form it has TWO parts:
  6099. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6100. */
  6101. arith_t beg, len;
  6102. const char *errmsg;
  6103. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6104. if (errmsg)
  6105. goto arith_err;
  6106. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6107. *p++ = SPECIAL_VAR_SYMBOL;
  6108. exp_word = p;
  6109. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6110. *p = '\0';
  6111. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6112. if (errmsg)
  6113. goto arith_err;
  6114. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6115. if (beg < 0) {
  6116. /* negative beg counts from the end */
  6117. beg = (arith_t)strlen(val) + beg;
  6118. if (beg < 0) /* ${v: -999999} is "" */
  6119. beg = len = 0;
  6120. }
  6121. debug_printf_varexp("from val:'%s'\n", val);
  6122. if (len < 0) {
  6123. /* in bash, len=-n means strlen()-n */
  6124. len = (arith_t)strlen(val) - beg + len;
  6125. if (len < 0) /* bash compat */
  6126. msg_and_die_if_script("%s: substring expression < 0", var);
  6127. }
  6128. if (len <= 0 || !val || beg >= strlen(val)) {
  6129. arith_err:
  6130. val = NULL;
  6131. } else {
  6132. /* Paranoia. What if user entered 9999999999999
  6133. * which fits in arith_t but not int? */
  6134. if (len >= INT_MAX)
  6135. len = INT_MAX;
  6136. val = to_be_freed = xstrndup(val + beg, len);
  6137. }
  6138. debug_printf_varexp("val:'%s'\n", val);
  6139. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6140. msg_and_die_if_script("malformed ${%s:...}", var);
  6141. val = NULL;
  6142. #endif
  6143. } else { /* one of "-=+?" */
  6144. /* Standard-mandated substitution ops:
  6145. * ${var?word} - indicate error if unset
  6146. * If var is unset, word (or a message indicating it is unset
  6147. * if word is null) is written to standard error
  6148. * and the shell exits with a non-zero exit status.
  6149. * Otherwise, the value of var is substituted.
  6150. * ${var-word} - use default value
  6151. * If var is unset, word is substituted.
  6152. * ${var=word} - assign and use default value
  6153. * If var is unset, word is assigned to var.
  6154. * In all cases, final value of var is substituted.
  6155. * ${var+word} - use alternative value
  6156. * If var is unset, null is substituted.
  6157. * Otherwise, word is substituted.
  6158. *
  6159. * Word is subjected to tilde expansion, parameter expansion,
  6160. * command substitution, and arithmetic expansion.
  6161. * If word is not needed, it is not expanded.
  6162. *
  6163. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6164. * but also treat null var as if it is unset.
  6165. *
  6166. * Word-splitting and single quote behavior:
  6167. *
  6168. * $ f() { for i; do echo "|$i|"; done; };
  6169. *
  6170. * $ x=; f ${x:?'x y' z}
  6171. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6172. * $ x=; f "${x:?'x y' z}"
  6173. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6174. *
  6175. * $ x=; f ${x:='x y' z}
  6176. * |x|
  6177. * |y|
  6178. * |z|
  6179. * $ x=; f "${x:='x y' z}"
  6180. * |'x y' z|
  6181. *
  6182. * $ x=x; f ${x:+'x y' z}
  6183. * |x y|
  6184. * |z|
  6185. * $ x=x; f "${x:+'x y' z}"
  6186. * |'x y' z|
  6187. *
  6188. * $ x=; f ${x:-'x y' z}
  6189. * |x y|
  6190. * |z|
  6191. * $ x=; f "${x:-'x y' z}"
  6192. * |'x y' z|
  6193. */
  6194. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6195. if (exp_op == '+')
  6196. use_word = !use_word;
  6197. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6198. (exp_save == ':') ? "true" : "false", use_word);
  6199. if (use_word) {
  6200. if (exp_op == '+' || exp_op == '-') {
  6201. /* ${var+word} - use alternative value */
  6202. /* ${var-word} - use default value */
  6203. n = encode_then_append_var_plusminus(output, n, exp_word,
  6204. /*dquoted:*/ (arg0 & 0x80)
  6205. );
  6206. val = NULL;
  6207. } else {
  6208. /* ${var?word} - indicate error if unset */
  6209. /* ${var=word} - assign and use default value */
  6210. to_be_freed = encode_then_expand_vararg(exp_word,
  6211. /*handle_squotes:*/ !(arg0 & 0x80),
  6212. /*unbackslash:*/ 0
  6213. );
  6214. if (to_be_freed)
  6215. exp_word = to_be_freed;
  6216. if (exp_op == '?') {
  6217. /* mimic bash message */
  6218. msg_and_die_if_script("%s: %s",
  6219. var,
  6220. exp_word[0]
  6221. ? exp_word
  6222. : "parameter null or not set"
  6223. /* ash has more specific messages, a-la: */
  6224. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6225. );
  6226. //TODO: how interactive bash aborts expansion mid-command?
  6227. //It aborts the entire line, returns to prompt:
  6228. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6229. // bash: x: x y z
  6230. // $
  6231. // ("echo YO" is not executed, neither the f function call)
  6232. } else {
  6233. val = exp_word;
  6234. }
  6235. if (exp_op == '=') {
  6236. /* ${var=[word]} or ${var:=[word]} */
  6237. if (isdigit(var[0]) || var[0] == '#') {
  6238. /* mimic bash message */
  6239. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6240. val = NULL;
  6241. } else {
  6242. char *new_var = xasprintf("%s=%s", var, val);
  6243. set_local_var(new_var, /*flag:*/ 0);
  6244. }
  6245. }
  6246. }
  6247. }
  6248. } /* one of "-=+?" */
  6249. *exp_saveptr = exp_save;
  6250. } /* if (exp_op) */
  6251. arg[0] = arg0;
  6252. *pp = p;
  6253. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6254. free(to_be_freed);
  6255. return n;
  6256. }
  6257. /* Expand all variable references in given string, adding words to list[]
  6258. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6259. * to be filled). This routine is extremely tricky: has to deal with
  6260. * variables/parameters with whitespace, $* and $@, and constructs like
  6261. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6262. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6263. {
  6264. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6265. * expansion of right-hand side of assignment == 1-element expand.
  6266. */
  6267. char cant_be_null = 0; /* only bit 0x80 matters */
  6268. char *p;
  6269. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6270. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6271. debug_print_list("expand_vars_to_list[0]", output, n);
  6272. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6273. char first_ch;
  6274. #if ENABLE_FEATURE_SH_MATH
  6275. char arith_buf[sizeof(arith_t)*3 + 2];
  6276. #endif
  6277. if (output->ended_in_ifs) {
  6278. o_addchr(output, '\0');
  6279. n = o_save_ptr(output, n);
  6280. output->ended_in_ifs = 0;
  6281. }
  6282. o_addblock(output, arg, p - arg);
  6283. debug_print_list("expand_vars_to_list[1]", output, n);
  6284. arg = ++p;
  6285. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6286. /* Fetch special var name (if it is indeed one of them)
  6287. * and quote bit, force the bit on if singleword expansion -
  6288. * important for not getting v=$@ expand to many words. */
  6289. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6290. /* Is this variable quoted and thus expansion can't be null?
  6291. * "$@" is special. Even if quoted, it can still
  6292. * expand to nothing (not even an empty string),
  6293. * thus it is excluded. */
  6294. if ((first_ch & 0x7f) != '@')
  6295. cant_be_null |= first_ch;
  6296. switch (first_ch & 0x7f) {
  6297. /* Highest bit in first_ch indicates that var is double-quoted */
  6298. case '*':
  6299. case '@': {
  6300. int i;
  6301. if (!G.global_argv[1])
  6302. break;
  6303. i = 1;
  6304. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6305. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6306. while (G.global_argv[i]) {
  6307. n = expand_on_ifs(output, n, G.global_argv[i]);
  6308. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6309. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6310. /* this argv[] is not empty and not last:
  6311. * put terminating NUL, start new word */
  6312. o_addchr(output, '\0');
  6313. debug_print_list("expand_vars_to_list[2]", output, n);
  6314. n = o_save_ptr(output, n);
  6315. debug_print_list("expand_vars_to_list[3]", output, n);
  6316. }
  6317. }
  6318. } else
  6319. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6320. * and in this case should treat it like '$*' - see 'else...' below */
  6321. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6322. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6323. ) {
  6324. while (1) {
  6325. o_addQstr(output, G.global_argv[i]);
  6326. if (++i >= G.global_argc)
  6327. break;
  6328. o_addchr(output, '\0');
  6329. debug_print_list("expand_vars_to_list[4]", output, n);
  6330. n = o_save_ptr(output, n);
  6331. }
  6332. } else { /* quoted $* (or v="$@" case): add as one word */
  6333. while (1) {
  6334. o_addQstr(output, G.global_argv[i]);
  6335. if (!G.global_argv[++i])
  6336. break;
  6337. if (G.ifs[0])
  6338. o_addchr(output, G.ifs[0]);
  6339. }
  6340. output->has_quoted_part = 1;
  6341. }
  6342. break;
  6343. }
  6344. case SPECIAL_VAR_SYMBOL: {
  6345. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6346. /* "Empty variable", used to make "" etc to not disappear */
  6347. output->has_quoted_part = 1;
  6348. cant_be_null = 0x80;
  6349. arg++;
  6350. break;
  6351. }
  6352. case SPECIAL_VAR_QUOTED_SVS:
  6353. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6354. /* "^C variable", represents literal ^C char (possible in scripts) */
  6355. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6356. arg++;
  6357. break;
  6358. #if ENABLE_HUSH_TICK
  6359. case '`': {
  6360. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6361. o_string subst_result = NULL_O_STRING;
  6362. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6363. arg++;
  6364. /* Can't just stuff it into output o_string,
  6365. * expanded result may need to be globbed
  6366. * and $IFS-split */
  6367. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6368. G.last_exitcode = process_command_subs(&subst_result, arg);
  6369. G.expand_exitcode = G.last_exitcode;
  6370. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6371. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6372. o_free(&subst_result);
  6373. break;
  6374. }
  6375. #endif
  6376. #if ENABLE_FEATURE_SH_MATH
  6377. case '+': {
  6378. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6379. arith_t res;
  6380. arg++; /* skip '+' */
  6381. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6382. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6383. res = expand_and_evaluate_arith(arg, NULL);
  6384. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6385. sprintf(arith_buf, ARITH_FMT, res);
  6386. o_addstr(output, arith_buf);
  6387. break;
  6388. }
  6389. #endif
  6390. default:
  6391. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6392. n = expand_one_var(output, n, first_ch, arg, &p);
  6393. break;
  6394. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6395. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6396. * Do the check to avoid writing to a const string. */
  6397. if (*p != SPECIAL_VAR_SYMBOL)
  6398. *p = SPECIAL_VAR_SYMBOL;
  6399. arg = ++p;
  6400. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6401. if (*arg) {
  6402. /* handle trailing string */
  6403. if (output->ended_in_ifs) {
  6404. o_addchr(output, '\0');
  6405. n = o_save_ptr(output, n);
  6406. }
  6407. debug_print_list("expand_vars_to_list[a]", output, n);
  6408. /* this part is literal, and it was already pre-quoted
  6409. * if needed (much earlier), do not use o_addQstr here!
  6410. */
  6411. o_addstr(output, arg);
  6412. debug_print_list("expand_vars_to_list[b]", output, n);
  6413. } else
  6414. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6415. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6416. && !output->has_quoted_part
  6417. ) {
  6418. n--;
  6419. /* allow to reuse list[n] later without re-growth */
  6420. output->has_empty_slot = 1;
  6421. }
  6422. return n;
  6423. }
  6424. static char **expand_variables(char **argv, unsigned expflags)
  6425. {
  6426. int n;
  6427. char **list;
  6428. o_string output = NULL_O_STRING;
  6429. output.o_expflags = expflags;
  6430. n = 0;
  6431. for (;;) {
  6432. /* go to next list[n] */
  6433. output.ended_in_ifs = 0;
  6434. n = o_save_ptr(&output, n);
  6435. if (!*argv)
  6436. break;
  6437. /* expand argv[i] */
  6438. n = expand_vars_to_list(&output, n, *argv++);
  6439. /* if (!output->has_empty_slot) -- need this?? */
  6440. o_addchr(&output, '\0');
  6441. }
  6442. debug_print_list("expand_variables", &output, n);
  6443. /* output.data (malloced in one block) gets returned in "list" */
  6444. list = o_finalize_list(&output, n);
  6445. debug_print_strings("expand_variables[1]", list);
  6446. return list;
  6447. }
  6448. static char **expand_strvec_to_strvec(char **argv)
  6449. {
  6450. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6451. }
  6452. #if defined(CMD_SINGLEWORD_NOGLOB)
  6453. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6454. {
  6455. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6456. }
  6457. #endif
  6458. /* Used for expansion of right hand of assignments,
  6459. * $((...)), heredocs, variable expansion parts.
  6460. *
  6461. * NB: should NOT do globbing!
  6462. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6463. */
  6464. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6465. {
  6466. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6467. const int do_unbackslash = 1;
  6468. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6469. #endif
  6470. char *argv[2], **list;
  6471. debug_printf_expand("string_to_string<='%s'\n", str);
  6472. /* This is generally an optimization, but it also
  6473. * handles "", which otherwise trips over !list[0] check below.
  6474. * (is this ever happens that we actually get str="" here?)
  6475. */
  6476. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6477. //TODO: Can use on strings with \ too, just unbackslash() them?
  6478. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6479. return xstrdup(str);
  6480. }
  6481. argv[0] = (char*)str;
  6482. argv[1] = NULL;
  6483. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6484. if (!list[0]) {
  6485. /* Example where it happens:
  6486. * x=; echo ${x:-"$@"}
  6487. */
  6488. ((char*)list)[0] = '\0';
  6489. } else {
  6490. if (HUSH_DEBUG)
  6491. if (list[1])
  6492. bb_error_msg_and_die("BUG in varexp2");
  6493. /* actually, just move string 2*sizeof(char*) bytes back */
  6494. overlapping_strcpy((char*)list, list[0]);
  6495. if (do_unbackslash)
  6496. unbackslash((char*)list);
  6497. }
  6498. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6499. return (char*)list;
  6500. }
  6501. #if 0
  6502. static char* expand_strvec_to_string(char **argv)
  6503. {
  6504. char **list;
  6505. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6506. /* Convert all NULs to spaces */
  6507. if (list[0]) {
  6508. int n = 1;
  6509. while (list[n]) {
  6510. if (HUSH_DEBUG)
  6511. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6512. bb_error_msg_and_die("BUG in varexp3");
  6513. /* bash uses ' ' regardless of $IFS contents */
  6514. list[n][-1] = ' ';
  6515. n++;
  6516. }
  6517. }
  6518. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6519. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6520. return (char*)list;
  6521. }
  6522. #endif
  6523. static char **expand_assignments(char **argv, int count)
  6524. {
  6525. int i;
  6526. char **p;
  6527. G.expanded_assignments = p = NULL;
  6528. /* Expand assignments into one string each */
  6529. for (i = 0; i < count; i++) {
  6530. p = add_string_to_strings(p,
  6531. expand_string_to_string(argv[i],
  6532. EXP_FLAG_ESC_GLOB_CHARS,
  6533. /*unbackslash:*/ 1
  6534. )
  6535. );
  6536. G.expanded_assignments = p;
  6537. }
  6538. G.expanded_assignments = NULL;
  6539. return p;
  6540. }
  6541. static void switch_off_special_sigs(unsigned mask)
  6542. {
  6543. unsigned sig = 0;
  6544. while ((mask >>= 1) != 0) {
  6545. sig++;
  6546. if (!(mask & 1))
  6547. continue;
  6548. #if ENABLE_HUSH_TRAP
  6549. if (G_traps) {
  6550. if (G_traps[sig] && !G_traps[sig][0])
  6551. /* trap is '', has to remain SIG_IGN */
  6552. continue;
  6553. free(G_traps[sig]);
  6554. G_traps[sig] = NULL;
  6555. }
  6556. #endif
  6557. /* We are here only if no trap or trap was not '' */
  6558. install_sighandler(sig, SIG_DFL);
  6559. }
  6560. }
  6561. #if BB_MMU
  6562. /* never called */
  6563. void re_execute_shell(char ***to_free, const char *s,
  6564. char *g_argv0, char **g_argv,
  6565. char **builtin_argv) NORETURN;
  6566. static void reset_traps_to_defaults(void)
  6567. {
  6568. /* This function is always called in a child shell
  6569. * after fork (not vfork, NOMMU doesn't use this function).
  6570. */
  6571. IF_HUSH_TRAP(unsigned sig;)
  6572. unsigned mask;
  6573. /* Child shells are not interactive.
  6574. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6575. * Testcase: (while :; do :; done) + ^Z should background.
  6576. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6577. */
  6578. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6579. if (!G_traps && !mask)
  6580. return; /* already no traps and no special sigs */
  6581. /* Switch off special sigs */
  6582. switch_off_special_sigs(mask);
  6583. # if ENABLE_HUSH_JOB
  6584. G_fatal_sig_mask = 0;
  6585. # endif
  6586. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6587. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6588. * remain set in G.special_sig_mask */
  6589. # if ENABLE_HUSH_TRAP
  6590. if (!G_traps)
  6591. return;
  6592. /* Reset all sigs to default except ones with empty traps */
  6593. for (sig = 0; sig < NSIG; sig++) {
  6594. if (!G_traps[sig])
  6595. continue; /* no trap: nothing to do */
  6596. if (!G_traps[sig][0])
  6597. continue; /* empty trap: has to remain SIG_IGN */
  6598. /* sig has non-empty trap, reset it: */
  6599. free(G_traps[sig]);
  6600. G_traps[sig] = NULL;
  6601. /* There is no signal for trap 0 (EXIT) */
  6602. if (sig == 0)
  6603. continue;
  6604. install_sighandler(sig, pick_sighandler(sig));
  6605. }
  6606. # endif
  6607. }
  6608. #else /* !BB_MMU */
  6609. static void re_execute_shell(char ***to_free, const char *s,
  6610. char *g_argv0, char **g_argv,
  6611. char **builtin_argv) NORETURN;
  6612. static void re_execute_shell(char ***to_free, const char *s,
  6613. char *g_argv0, char **g_argv,
  6614. char **builtin_argv)
  6615. {
  6616. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6617. /* delims + 2 * (number of bytes in printed hex numbers) */
  6618. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6619. char *heredoc_argv[4];
  6620. struct variable *cur;
  6621. # if ENABLE_HUSH_FUNCTIONS
  6622. struct function *funcp;
  6623. # endif
  6624. char **argv, **pp;
  6625. unsigned cnt;
  6626. unsigned long long empty_trap_mask;
  6627. if (!g_argv0) { /* heredoc */
  6628. argv = heredoc_argv;
  6629. argv[0] = (char *) G.argv0_for_re_execing;
  6630. argv[1] = (char *) "-<";
  6631. argv[2] = (char *) s;
  6632. argv[3] = NULL;
  6633. pp = &argv[3]; /* used as pointer to empty environment */
  6634. goto do_exec;
  6635. }
  6636. cnt = 0;
  6637. pp = builtin_argv;
  6638. if (pp) while (*pp++)
  6639. cnt++;
  6640. empty_trap_mask = 0;
  6641. if (G_traps) {
  6642. int sig;
  6643. for (sig = 1; sig < NSIG; sig++) {
  6644. if (G_traps[sig] && !G_traps[sig][0])
  6645. empty_trap_mask |= 1LL << sig;
  6646. }
  6647. }
  6648. sprintf(param_buf, NOMMU_HACK_FMT
  6649. , (unsigned) G.root_pid
  6650. , (unsigned) G.root_ppid
  6651. , (unsigned) G.last_bg_pid
  6652. , (unsigned) G.last_exitcode
  6653. , cnt
  6654. , empty_trap_mask
  6655. IF_HUSH_LOOPS(, G.depth_of_loop)
  6656. );
  6657. # undef NOMMU_HACK_FMT
  6658. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6659. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6660. */
  6661. cnt += 6;
  6662. for (cur = G.top_var; cur; cur = cur->next) {
  6663. if (!cur->flg_export || cur->flg_read_only)
  6664. cnt += 2;
  6665. }
  6666. # if ENABLE_HUSH_FUNCTIONS
  6667. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6668. cnt += 3;
  6669. # endif
  6670. pp = g_argv;
  6671. while (*pp++)
  6672. cnt++;
  6673. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6674. *pp++ = (char *) G.argv0_for_re_execing;
  6675. *pp++ = param_buf;
  6676. for (cur = G.top_var; cur; cur = cur->next) {
  6677. if (strcmp(cur->varstr, hush_version_str) == 0)
  6678. continue;
  6679. if (cur->flg_read_only) {
  6680. *pp++ = (char *) "-R";
  6681. *pp++ = cur->varstr;
  6682. } else if (!cur->flg_export) {
  6683. *pp++ = (char *) "-V";
  6684. *pp++ = cur->varstr;
  6685. }
  6686. }
  6687. # if ENABLE_HUSH_FUNCTIONS
  6688. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6689. *pp++ = (char *) "-F";
  6690. *pp++ = funcp->name;
  6691. *pp++ = funcp->body_as_string;
  6692. }
  6693. # endif
  6694. /* We can pass activated traps here. Say, -Tnn:trap_string
  6695. *
  6696. * However, POSIX says that subshells reset signals with traps
  6697. * to SIG_DFL.
  6698. * I tested bash-3.2 and it not only does that with true subshells
  6699. * of the form ( list ), but with any forked children shells.
  6700. * I set trap "echo W" WINCH; and then tried:
  6701. *
  6702. * { echo 1; sleep 20; echo 2; } &
  6703. * while true; do echo 1; sleep 20; echo 2; break; done &
  6704. * true | { echo 1; sleep 20; echo 2; } | cat
  6705. *
  6706. * In all these cases sending SIGWINCH to the child shell
  6707. * did not run the trap. If I add trap "echo V" WINCH;
  6708. * _inside_ group (just before echo 1), it works.
  6709. *
  6710. * I conclude it means we don't need to pass active traps here.
  6711. */
  6712. *pp++ = (char *) "-c";
  6713. *pp++ = (char *) s;
  6714. if (builtin_argv) {
  6715. while (*++builtin_argv)
  6716. *pp++ = *builtin_argv;
  6717. *pp++ = (char *) "";
  6718. }
  6719. *pp++ = g_argv0;
  6720. while (*g_argv)
  6721. *pp++ = *g_argv++;
  6722. /* *pp = NULL; - is already there */
  6723. pp = environ;
  6724. do_exec:
  6725. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6726. /* Don't propagate SIG_IGN to the child */
  6727. if (SPECIAL_JOBSTOP_SIGS != 0)
  6728. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6729. execve(bb_busybox_exec_path, argv, pp);
  6730. /* Fallback. Useful for init=/bin/hush usage etc */
  6731. if (argv[0][0] == '/')
  6732. execve(argv[0], argv, pp);
  6733. xfunc_error_retval = 127;
  6734. bb_error_msg_and_die("can't re-execute the shell");
  6735. }
  6736. #endif /* !BB_MMU */
  6737. static int run_and_free_list(struct pipe *pi);
  6738. /* Executing from string: eval, sh -c '...'
  6739. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6740. * end_trigger controls how often we stop parsing
  6741. * NUL: parse all, execute, return
  6742. * ';': parse till ';' or newline, execute, repeat till EOF
  6743. */
  6744. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6745. {
  6746. /* Why we need empty flag?
  6747. * An obscure corner case "false; ``; echo $?":
  6748. * empty command in `` should still set $? to 0.
  6749. * But we can't just set $? to 0 at the start,
  6750. * this breaks "false; echo `echo $?`" case.
  6751. */
  6752. bool empty = 1;
  6753. while (1) {
  6754. struct pipe *pipe_list;
  6755. #if ENABLE_HUSH_INTERACTIVE
  6756. if (end_trigger == ';') {
  6757. G.promptmode = 0; /* PS1 */
  6758. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6759. }
  6760. #endif
  6761. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6762. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6763. /* If we are in "big" script
  6764. * (not in `cmd` or something similar)...
  6765. */
  6766. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6767. /* Discard cached input (rest of line) */
  6768. int ch = inp->last_char;
  6769. while (ch != EOF && ch != '\n') {
  6770. //bb_error_msg("Discarded:'%c'", ch);
  6771. ch = i_getch(inp);
  6772. }
  6773. /* Force prompt */
  6774. inp->p = NULL;
  6775. /* This stream isn't empty */
  6776. empty = 0;
  6777. continue;
  6778. }
  6779. if (!pipe_list && empty)
  6780. G.last_exitcode = 0;
  6781. break;
  6782. }
  6783. debug_print_tree(pipe_list, 0);
  6784. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6785. run_and_free_list(pipe_list);
  6786. empty = 0;
  6787. if (G_flag_return_in_progress == 1)
  6788. break;
  6789. }
  6790. }
  6791. static void parse_and_run_string(const char *s)
  6792. {
  6793. struct in_str input;
  6794. //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6795. setup_string_in_str(&input, s);
  6796. parse_and_run_stream(&input, '\0');
  6797. //IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6798. }
  6799. static void parse_and_run_file(HFILE *fp)
  6800. {
  6801. struct in_str input;
  6802. IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
  6803. IF_HUSH_LINENO_VAR(G.lineno = 1;)
  6804. setup_file_in_str(&input, fp);
  6805. parse_and_run_stream(&input, ';');
  6806. IF_HUSH_LINENO_VAR(G.lineno = sv;)
  6807. }
  6808. #if ENABLE_HUSH_TICK
  6809. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6810. {
  6811. pid_t pid;
  6812. int channel[2];
  6813. # if !BB_MMU
  6814. char **to_free = NULL;
  6815. # endif
  6816. xpipe(channel);
  6817. pid = BB_MMU ? xfork() : xvfork();
  6818. if (pid == 0) { /* child */
  6819. disable_restore_tty_pgrp_on_exit();
  6820. /* Process substitution is not considered to be usual
  6821. * 'command execution'.
  6822. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6823. */
  6824. bb_signals(0
  6825. + (1 << SIGTSTP)
  6826. + (1 << SIGTTIN)
  6827. + (1 << SIGTTOU)
  6828. , SIG_IGN);
  6829. close(channel[0]); /* NB: close _first_, then move fd! */
  6830. xmove_fd(channel[1], 1);
  6831. # if ENABLE_HUSH_TRAP
  6832. /* Awful hack for `trap` or $(trap).
  6833. *
  6834. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6835. * contains an example where "trap" is executed in a subshell:
  6836. *
  6837. * save_traps=$(trap)
  6838. * ...
  6839. * eval "$save_traps"
  6840. *
  6841. * Standard does not say that "trap" in subshell shall print
  6842. * parent shell's traps. It only says that its output
  6843. * must have suitable form, but then, in the above example
  6844. * (which is not supposed to be normative), it implies that.
  6845. *
  6846. * bash (and probably other shell) does implement it
  6847. * (traps are reset to defaults, but "trap" still shows them),
  6848. * but as a result, "trap" logic is hopelessly messed up:
  6849. *
  6850. * # trap
  6851. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6852. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6853. * # true | trap <--- trap is in subshell - no output (ditto)
  6854. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6855. * trap -- 'echo Ho' SIGWINCH
  6856. * # echo `(trap)` <--- in subshell in subshell - output
  6857. * trap -- 'echo Ho' SIGWINCH
  6858. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6859. * trap -- 'echo Ho' SIGWINCH
  6860. *
  6861. * The rules when to forget and when to not forget traps
  6862. * get really complex and nonsensical.
  6863. *
  6864. * Our solution: ONLY bare $(trap) or `trap` is special.
  6865. */
  6866. s = skip_whitespace(s);
  6867. if (is_prefixed_with(s, "trap")
  6868. && skip_whitespace(s + 4)[0] == '\0'
  6869. ) {
  6870. static const char *const argv[] = { NULL, NULL };
  6871. builtin_trap((char**)argv);
  6872. fflush_all(); /* important */
  6873. _exit(0);
  6874. }
  6875. # endif
  6876. # if BB_MMU
  6877. /* Prevent it from trying to handle ctrl-z etc */
  6878. IF_HUSH_JOB(G.run_list_level = 1;)
  6879. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6880. reset_traps_to_defaults();
  6881. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6882. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6883. parse_and_run_string(s);
  6884. _exit(G.last_exitcode);
  6885. # else
  6886. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6887. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6888. * huge=`cat BIG` # was blocking here forever
  6889. * echo OK
  6890. */
  6891. re_execute_shell(&to_free,
  6892. s,
  6893. G.global_argv[0],
  6894. G.global_argv + 1,
  6895. NULL);
  6896. # endif
  6897. }
  6898. /* parent */
  6899. *pid_p = pid;
  6900. # if ENABLE_HUSH_FAST
  6901. G.count_SIGCHLD++;
  6902. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6903. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6904. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6905. # endif
  6906. enable_restore_tty_pgrp_on_exit();
  6907. # if !BB_MMU
  6908. free(to_free);
  6909. # endif
  6910. close(channel[1]);
  6911. return channel[0];
  6912. }
  6913. /* Return code is exit status of the process that is run. */
  6914. static int process_command_subs(o_string *dest, const char *s)
  6915. {
  6916. FILE *fp;
  6917. pid_t pid;
  6918. int status, ch, eol_cnt;
  6919. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6920. /* Now send results of command back into original context */
  6921. eol_cnt = 0;
  6922. while ((ch = getc(fp)) != EOF) {
  6923. if (ch == '\0')
  6924. continue;
  6925. if (ch == '\n') {
  6926. eol_cnt++;
  6927. continue;
  6928. }
  6929. while (eol_cnt) {
  6930. o_addchr(dest, '\n');
  6931. eol_cnt--;
  6932. }
  6933. o_addQchr(dest, ch);
  6934. }
  6935. debug_printf("done reading from `cmd` pipe, closing it\n");
  6936. fclose(fp);
  6937. /* We need to extract exitcode. Test case
  6938. * "true; echo `sleep 1; false` $?"
  6939. * should print 1 */
  6940. safe_waitpid(pid, &status, 0);
  6941. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6942. return WEXITSTATUS(status);
  6943. }
  6944. #endif /* ENABLE_HUSH_TICK */
  6945. static void setup_heredoc(struct redir_struct *redir)
  6946. {
  6947. struct fd_pair pair;
  6948. pid_t pid;
  6949. int len, written;
  6950. /* the _body_ of heredoc (misleading field name) */
  6951. const char *heredoc = redir->rd_filename;
  6952. char *expanded;
  6953. #if !BB_MMU
  6954. char **to_free;
  6955. #endif
  6956. expanded = NULL;
  6957. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6958. expanded = encode_then_expand_string(heredoc);
  6959. if (expanded)
  6960. heredoc = expanded;
  6961. }
  6962. len = strlen(heredoc);
  6963. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  6964. xpiped_pair(pair);
  6965. xmove_fd(pair.rd, redir->rd_fd);
  6966. /* Try writing without forking. Newer kernels have
  6967. * dynamically growing pipes. Must use non-blocking write! */
  6968. ndelay_on(pair.wr);
  6969. while (1) {
  6970. written = write(pair.wr, heredoc, len);
  6971. if (written <= 0)
  6972. break;
  6973. len -= written;
  6974. if (len == 0) {
  6975. close(pair.wr);
  6976. free(expanded);
  6977. return;
  6978. }
  6979. heredoc += written;
  6980. }
  6981. ndelay_off(pair.wr);
  6982. /* Okay, pipe buffer was not big enough */
  6983. /* Note: we must not create a stray child (bastard? :)
  6984. * for the unsuspecting parent process. Child creates a grandchild
  6985. * and exits before parent execs the process which consumes heredoc
  6986. * (that exec happens after we return from this function) */
  6987. #if !BB_MMU
  6988. to_free = NULL;
  6989. #endif
  6990. pid = xvfork();
  6991. if (pid == 0) {
  6992. /* child */
  6993. disable_restore_tty_pgrp_on_exit();
  6994. pid = BB_MMU ? xfork() : xvfork();
  6995. if (pid != 0)
  6996. _exit(0);
  6997. /* grandchild */
  6998. close(redir->rd_fd); /* read side of the pipe */
  6999. #if BB_MMU
  7000. full_write(pair.wr, heredoc, len); /* may loop or block */
  7001. _exit(0);
  7002. #else
  7003. /* Delegate blocking writes to another process */
  7004. xmove_fd(pair.wr, STDOUT_FILENO);
  7005. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7006. #endif
  7007. }
  7008. /* parent */
  7009. #if ENABLE_HUSH_FAST
  7010. G.count_SIGCHLD++;
  7011. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7012. #endif
  7013. enable_restore_tty_pgrp_on_exit();
  7014. #if !BB_MMU
  7015. free(to_free);
  7016. #endif
  7017. close(pair.wr);
  7018. free(expanded);
  7019. wait(NULL); /* wait till child has died */
  7020. }
  7021. struct squirrel {
  7022. int orig_fd;
  7023. int moved_to;
  7024. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7025. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7026. };
  7027. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7028. {
  7029. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7030. sq[i].orig_fd = orig;
  7031. sq[i].moved_to = moved;
  7032. sq[i+1].orig_fd = -1; /* end marker */
  7033. return sq;
  7034. }
  7035. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7036. {
  7037. int moved_to;
  7038. int i;
  7039. i = 0;
  7040. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7041. /* If we collide with an already moved fd... */
  7042. if (fd == sq[i].moved_to) {
  7043. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7044. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7045. if (sq[i].moved_to < 0) /* what? */
  7046. xfunc_die();
  7047. return sq;
  7048. }
  7049. if (fd == sq[i].orig_fd) {
  7050. /* Example: echo Hello >/dev/null 1>&2 */
  7051. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7052. return sq;
  7053. }
  7054. }
  7055. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7056. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7057. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7058. if (moved_to < 0 && errno != EBADF)
  7059. xfunc_die();
  7060. return append_squirrel(sq, i, fd, moved_to);
  7061. }
  7062. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7063. {
  7064. int i;
  7065. i = 0;
  7066. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7067. /* If we collide with an already moved fd... */
  7068. if (fd == sq[i].orig_fd) {
  7069. /* Examples:
  7070. * "echo 3>FILE 3>&- 3>FILE"
  7071. * "echo 3>&- 3>FILE"
  7072. * No need for last redirect to insert
  7073. * another "need to close 3" indicator.
  7074. */
  7075. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7076. return sq;
  7077. }
  7078. }
  7079. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7080. return append_squirrel(sq, i, fd, -1);
  7081. }
  7082. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7083. * Move all conflicting internally used fds,
  7084. * and remember them so that we can restore them later.
  7085. */
  7086. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7087. {
  7088. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7089. avoid_fd = 9;
  7090. #if ENABLE_HUSH_INTERACTIVE
  7091. if (fd == G.interactive_fd) {
  7092. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7093. G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
  7094. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
  7095. return 1; /* "we closed fd" */
  7096. }
  7097. #endif
  7098. /* Are we called from setup_redirects(squirrel==NULL)
  7099. * in redirect in a [v]forked child?
  7100. */
  7101. if (sqp == NULL) {
  7102. /* No need to move script fds.
  7103. * For NOMMU case, it's actively wrong: we'd change ->fd
  7104. * fields in memory for the parent, but parent's fds
  7105. * aren't be moved, it would use wrong fd!
  7106. * Reproducer: "cmd 3>FILE" in script.
  7107. * If we would call move_HFILEs_on_redirect(), child would:
  7108. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7109. * close(3) = 0
  7110. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7111. */
  7112. //bb_error_msg("sqp == NULL: [v]forked child");
  7113. return 0;
  7114. }
  7115. /* If this one of script's fds? */
  7116. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7117. return 1; /* yes. "we closed fd" (actually moved it) */
  7118. /* Are we called for "exec 3>FILE"? Came through
  7119. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7120. * This case used to fail for this script:
  7121. * exec 3>FILE
  7122. * echo Ok
  7123. * ...100000 more lines...
  7124. * echo Ok
  7125. * as follows:
  7126. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7127. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7128. * dup2(4, 3) = 3
  7129. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7130. * close(4) = 0
  7131. * write(1, "Ok\n", 3) = 3
  7132. * ... = 3
  7133. * write(1, "Ok\n", 3) = 3
  7134. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7135. * ^^^^^^^^ oops, wrong fd!!!
  7136. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7137. * it now works:
  7138. */
  7139. if (sqp == ERR_PTR) {
  7140. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7141. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7142. return 0;
  7143. }
  7144. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7145. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7146. return 0; /* "we did not close fd" */
  7147. }
  7148. static void restore_redirects(struct squirrel *sq)
  7149. {
  7150. if (sq) {
  7151. int i;
  7152. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7153. if (sq[i].moved_to >= 0) {
  7154. /* We simply die on error */
  7155. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7156. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7157. } else {
  7158. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7159. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7160. close(sq[i].orig_fd);
  7161. }
  7162. }
  7163. free(sq);
  7164. }
  7165. /* If moved, G.interactive_fd stays on new fd, not restoring it */
  7166. }
  7167. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7168. static void close_saved_fds_and_FILE_fds(void)
  7169. {
  7170. if (G_interactive_fd)
  7171. close(G_interactive_fd);
  7172. close_all_HFILE_list();
  7173. }
  7174. #endif
  7175. static int internally_opened_fd(int fd, struct squirrel *sq)
  7176. {
  7177. int i;
  7178. #if ENABLE_HUSH_INTERACTIVE
  7179. if (fd == G.interactive_fd)
  7180. return 1;
  7181. #endif
  7182. /* If this one of script's fds? */
  7183. if (fd_in_HFILEs(fd))
  7184. return 1;
  7185. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7186. if (fd == sq[i].moved_to)
  7187. return 1;
  7188. }
  7189. return 0;
  7190. }
  7191. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7192. * and stderr if they are redirected. */
  7193. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7194. {
  7195. struct redir_struct *redir;
  7196. for (redir = prog->redirects; redir; redir = redir->next) {
  7197. int newfd;
  7198. int closed;
  7199. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7200. /* "rd_fd<<HERE" case */
  7201. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7202. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7203. * of the heredoc */
  7204. debug_printf_redir("set heredoc '%s'\n",
  7205. redir->rd_filename);
  7206. setup_heredoc(redir);
  7207. continue;
  7208. }
  7209. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7210. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7211. char *p;
  7212. int mode;
  7213. if (redir->rd_filename == NULL) {
  7214. /* Examples:
  7215. * "cmd >" (no filename)
  7216. * "cmd > <file" (2nd redirect starts too early)
  7217. */
  7218. syntax_error("invalid redirect");
  7219. continue;
  7220. }
  7221. mode = redir_table[redir->rd_type].mode;
  7222. p = expand_string_to_string(redir->rd_filename,
  7223. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7224. newfd = open_or_warn(p, mode);
  7225. free(p);
  7226. if (newfd < 0) {
  7227. /* Error message from open_or_warn can be lost
  7228. * if stderr has been redirected, but bash
  7229. * and ash both lose it as well
  7230. * (though zsh doesn't!)
  7231. */
  7232. return 1;
  7233. }
  7234. if (newfd == redir->rd_fd && sqp) {
  7235. /* open() gave us precisely the fd we wanted.
  7236. * This means that this fd was not busy
  7237. * (not opened to anywhere).
  7238. * Remember to close it on restore:
  7239. */
  7240. *sqp = add_squirrel_closed(*sqp, newfd);
  7241. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7242. }
  7243. } else {
  7244. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7245. newfd = redir->rd_dup;
  7246. }
  7247. if (newfd == redir->rd_fd)
  7248. continue;
  7249. /* if "N>FILE": move newfd to redir->rd_fd */
  7250. /* if "N>&M": dup newfd to redir->rd_fd */
  7251. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7252. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7253. if (newfd == REDIRFD_CLOSE) {
  7254. /* "N>&-" means "close me" */
  7255. if (!closed) {
  7256. /* ^^^ optimization: saving may already
  7257. * have closed it. If not... */
  7258. close(redir->rd_fd);
  7259. }
  7260. /* Sometimes we do another close on restore, getting EBADF.
  7261. * Consider "echo 3>FILE 3>&-"
  7262. * first redirect remembers "need to close 3",
  7263. * and second redirect closes 3! Restore code then closes 3 again.
  7264. */
  7265. } else {
  7266. /* if newfd is a script fd or saved fd, simulate EBADF */
  7267. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7268. //errno = EBADF;
  7269. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7270. newfd = -1; /* same effect as code above */
  7271. }
  7272. xdup2(newfd, redir->rd_fd);
  7273. if (redir->rd_dup == REDIRFD_TO_FILE)
  7274. /* "rd_fd > FILE" */
  7275. close(newfd);
  7276. /* else: "rd_fd > rd_dup" */
  7277. }
  7278. }
  7279. return 0;
  7280. }
  7281. static char *find_in_path(const char *arg)
  7282. {
  7283. char *ret = NULL;
  7284. const char *PATH = get_local_var_value("PATH");
  7285. if (!PATH)
  7286. return NULL;
  7287. while (1) {
  7288. const char *end = strchrnul(PATH, ':');
  7289. int sz = end - PATH; /* must be int! */
  7290. free(ret);
  7291. if (sz != 0) {
  7292. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7293. } else {
  7294. /* We have xxx::yyyy in $PATH,
  7295. * it means "use current dir" */
  7296. ret = xstrdup(arg);
  7297. }
  7298. if (access(ret, F_OK) == 0)
  7299. break;
  7300. if (*end == '\0') {
  7301. free(ret);
  7302. return NULL;
  7303. }
  7304. PATH = end + 1;
  7305. }
  7306. return ret;
  7307. }
  7308. static const struct built_in_command *find_builtin_helper(const char *name,
  7309. const struct built_in_command *x,
  7310. const struct built_in_command *end)
  7311. {
  7312. while (x != end) {
  7313. if (strcmp(name, x->b_cmd) != 0) {
  7314. x++;
  7315. continue;
  7316. }
  7317. debug_printf_exec("found builtin '%s'\n", name);
  7318. return x;
  7319. }
  7320. return NULL;
  7321. }
  7322. static const struct built_in_command *find_builtin1(const char *name)
  7323. {
  7324. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7325. }
  7326. static const struct built_in_command *find_builtin(const char *name)
  7327. {
  7328. const struct built_in_command *x = find_builtin1(name);
  7329. if (x)
  7330. return x;
  7331. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7332. }
  7333. static void remove_nested_vars(void)
  7334. {
  7335. struct variable *cur;
  7336. struct variable **cur_pp;
  7337. cur_pp = &G.top_var;
  7338. while ((cur = *cur_pp) != NULL) {
  7339. if (cur->var_nest_level <= G.var_nest_level) {
  7340. cur_pp = &cur->next;
  7341. continue;
  7342. }
  7343. /* Unexport */
  7344. if (cur->flg_export) {
  7345. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7346. bb_unsetenv(cur->varstr);
  7347. }
  7348. /* Remove from global list */
  7349. *cur_pp = cur->next;
  7350. /* Free */
  7351. if (!cur->max_len) {
  7352. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7353. free(cur->varstr);
  7354. }
  7355. free(cur);
  7356. }
  7357. }
  7358. static void enter_var_nest_level(void)
  7359. {
  7360. G.var_nest_level++;
  7361. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7362. /* Try: f() { echo -n .; f; }; f
  7363. * struct variable::var_nest_level is uint16_t,
  7364. * thus limiting recursion to < 2^16.
  7365. * In any case, with 8 Mbyte stack SEGV happens
  7366. * not too long after 2^16 recursions anyway.
  7367. */
  7368. if (G.var_nest_level > 0xff00)
  7369. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7370. }
  7371. static void leave_var_nest_level(void)
  7372. {
  7373. G.var_nest_level--;
  7374. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7375. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7376. bb_error_msg_and_die("BUG: nesting underflow");
  7377. remove_nested_vars();
  7378. }
  7379. #if ENABLE_HUSH_FUNCTIONS
  7380. static struct function **find_function_slot(const char *name)
  7381. {
  7382. struct function *funcp;
  7383. struct function **funcpp = &G.top_func;
  7384. while ((funcp = *funcpp) != NULL) {
  7385. if (strcmp(name, funcp->name) == 0) {
  7386. debug_printf_exec("found function '%s'\n", name);
  7387. break;
  7388. }
  7389. funcpp = &funcp->next;
  7390. }
  7391. return funcpp;
  7392. }
  7393. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7394. {
  7395. const struct function *funcp = *find_function_slot(name);
  7396. return funcp;
  7397. }
  7398. /* Note: takes ownership on name ptr */
  7399. static struct function *new_function(char *name)
  7400. {
  7401. struct function **funcpp = find_function_slot(name);
  7402. struct function *funcp = *funcpp;
  7403. if (funcp != NULL) {
  7404. struct command *cmd = funcp->parent_cmd;
  7405. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7406. if (!cmd) {
  7407. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7408. free(funcp->name);
  7409. /* Note: if !funcp->body, do not free body_as_string!
  7410. * This is a special case of "-F name body" function:
  7411. * body_as_string was not malloced! */
  7412. if (funcp->body) {
  7413. free_pipe_list(funcp->body);
  7414. # if !BB_MMU
  7415. free(funcp->body_as_string);
  7416. # endif
  7417. }
  7418. } else {
  7419. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7420. cmd->argv[0] = funcp->name;
  7421. cmd->group = funcp->body;
  7422. # if !BB_MMU
  7423. cmd->group_as_string = funcp->body_as_string;
  7424. # endif
  7425. }
  7426. } else {
  7427. debug_printf_exec("remembering new function '%s'\n", name);
  7428. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7429. /*funcp->next = NULL;*/
  7430. }
  7431. funcp->name = name;
  7432. return funcp;
  7433. }
  7434. # if ENABLE_HUSH_UNSET
  7435. static void unset_func(const char *name)
  7436. {
  7437. struct function **funcpp = find_function_slot(name);
  7438. struct function *funcp = *funcpp;
  7439. if (funcp != NULL) {
  7440. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7441. *funcpp = funcp->next;
  7442. /* funcp is unlinked now, deleting it.
  7443. * Note: if !funcp->body, the function was created by
  7444. * "-F name body", do not free ->body_as_string
  7445. * and ->name as they were not malloced. */
  7446. if (funcp->body) {
  7447. free_pipe_list(funcp->body);
  7448. free(funcp->name);
  7449. # if !BB_MMU
  7450. free(funcp->body_as_string);
  7451. # endif
  7452. }
  7453. free(funcp);
  7454. }
  7455. }
  7456. # endif
  7457. # if BB_MMU
  7458. #define exec_function(to_free, funcp, argv) \
  7459. exec_function(funcp, argv)
  7460. # endif
  7461. static void exec_function(char ***to_free,
  7462. const struct function *funcp,
  7463. char **argv) NORETURN;
  7464. static void exec_function(char ***to_free,
  7465. const struct function *funcp,
  7466. char **argv)
  7467. {
  7468. # if BB_MMU
  7469. int n;
  7470. argv[0] = G.global_argv[0];
  7471. G.global_argv = argv;
  7472. G.global_argc = n = 1 + string_array_len(argv + 1);
  7473. // Example when we are here: "cmd | func"
  7474. // func will run with saved-redirect fds open.
  7475. // $ f() { echo /proc/self/fd/*; }
  7476. // $ true | f
  7477. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7478. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7479. // Same in script:
  7480. // $ . ./SCRIPT
  7481. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7482. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7483. // They are CLOEXEC so external programs won't see them, but
  7484. // for "more correctness" we might want to close those extra fds here:
  7485. //? close_saved_fds_and_FILE_fds();
  7486. /* "we are in a function, ok to use return" */
  7487. G_flag_return_in_progress = -1;
  7488. enter_var_nest_level();
  7489. IF_HUSH_LOCAL(G.func_nest_level++;)
  7490. /* On MMU, funcp->body is always non-NULL */
  7491. n = run_list(funcp->body);
  7492. fflush_all();
  7493. _exit(n);
  7494. # else
  7495. //? close_saved_fds_and_FILE_fds();
  7496. //TODO: check whether "true | func_with_return" works
  7497. re_execute_shell(to_free,
  7498. funcp->body_as_string,
  7499. G.global_argv[0],
  7500. argv + 1,
  7501. NULL);
  7502. # endif
  7503. }
  7504. static int run_function(const struct function *funcp, char **argv)
  7505. {
  7506. int rc;
  7507. save_arg_t sv;
  7508. smallint sv_flg;
  7509. save_and_replace_G_args(&sv, argv);
  7510. /* "We are in function, ok to use return" */
  7511. sv_flg = G_flag_return_in_progress;
  7512. G_flag_return_in_progress = -1;
  7513. /* Make "local" variables properly shadow previous ones */
  7514. IF_HUSH_LOCAL(enter_var_nest_level();)
  7515. IF_HUSH_LOCAL(G.func_nest_level++;)
  7516. /* On MMU, funcp->body is always non-NULL */
  7517. # if !BB_MMU
  7518. if (!funcp->body) {
  7519. /* Function defined by -F */
  7520. parse_and_run_string(funcp->body_as_string);
  7521. rc = G.last_exitcode;
  7522. } else
  7523. # endif
  7524. {
  7525. rc = run_list(funcp->body);
  7526. }
  7527. IF_HUSH_LOCAL(G.func_nest_level--;)
  7528. IF_HUSH_LOCAL(leave_var_nest_level();)
  7529. G_flag_return_in_progress = sv_flg;
  7530. restore_G_args(&sv, argv);
  7531. return rc;
  7532. }
  7533. #endif /* ENABLE_HUSH_FUNCTIONS */
  7534. #if BB_MMU
  7535. #define exec_builtin(to_free, x, argv) \
  7536. exec_builtin(x, argv)
  7537. #else
  7538. #define exec_builtin(to_free, x, argv) \
  7539. exec_builtin(to_free, argv)
  7540. #endif
  7541. static void exec_builtin(char ***to_free,
  7542. const struct built_in_command *x,
  7543. char **argv) NORETURN;
  7544. static void exec_builtin(char ***to_free,
  7545. const struct built_in_command *x,
  7546. char **argv)
  7547. {
  7548. #if BB_MMU
  7549. int rcode;
  7550. fflush_all();
  7551. //? close_saved_fds_and_FILE_fds();
  7552. rcode = x->b_function(argv);
  7553. fflush_all();
  7554. _exit(rcode);
  7555. #else
  7556. fflush_all();
  7557. /* On NOMMU, we must never block!
  7558. * Example: { sleep 99 | read line; } & echo Ok
  7559. */
  7560. re_execute_shell(to_free,
  7561. argv[0],
  7562. G.global_argv[0],
  7563. G.global_argv + 1,
  7564. argv);
  7565. #endif
  7566. }
  7567. static void execvp_or_die(char **argv) NORETURN;
  7568. static void execvp_or_die(char **argv)
  7569. {
  7570. int e;
  7571. debug_printf_exec("execing '%s'\n", argv[0]);
  7572. /* Don't propagate SIG_IGN to the child */
  7573. if (SPECIAL_JOBSTOP_SIGS != 0)
  7574. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7575. execvp(argv[0], argv);
  7576. e = 2;
  7577. if (errno == EACCES) e = 126;
  7578. if (errno == ENOENT) e = 127;
  7579. bb_perror_msg("can't execute '%s'", argv[0]);
  7580. _exit(e);
  7581. }
  7582. #if ENABLE_HUSH_MODE_X
  7583. static void x_mode_print_optionally_squoted(const char *str)
  7584. {
  7585. unsigned len;
  7586. const char *cp;
  7587. cp = str;
  7588. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7589. /* test a char with: bash -c 'set -x; echo "CH"' */
  7590. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7591. " " "\001\002\003\004\005\006\007"
  7592. "\010\011\012\013\014\015\016\017"
  7593. "\020\021\022\023\024\025\026\027"
  7594. "\030\031\032\033\034\035\036\037"
  7595. )
  7596. ] == '\0'
  7597. ) {
  7598. /* string has no special chars */
  7599. x_mode_addstr(str);
  7600. return;
  7601. }
  7602. cp = str;
  7603. for (;;) {
  7604. /* print '....' up to EOL or first squote */
  7605. len = (int)(strchrnul(cp, '\'') - cp);
  7606. if (len != 0) {
  7607. x_mode_addchr('\'');
  7608. x_mode_addblock(cp, len);
  7609. x_mode_addchr('\'');
  7610. cp += len;
  7611. }
  7612. if (*cp == '\0')
  7613. break;
  7614. /* string contains squote(s), print them as \' */
  7615. x_mode_addchr('\\');
  7616. x_mode_addchr('\'');
  7617. cp++;
  7618. }
  7619. }
  7620. static void dump_cmd_in_x_mode(char **argv)
  7621. {
  7622. if (G_x_mode && argv) {
  7623. unsigned n;
  7624. /* "+[+++...][ cmd...]\n\0" */
  7625. x_mode_prefix();
  7626. n = 0;
  7627. while (argv[n]) {
  7628. x_mode_addchr(' ');
  7629. if (argv[n][0] == '\0') {
  7630. x_mode_addchr('\'');
  7631. x_mode_addchr('\'');
  7632. } else {
  7633. x_mode_print_optionally_squoted(argv[n]);
  7634. }
  7635. n++;
  7636. }
  7637. x_mode_flush();
  7638. }
  7639. }
  7640. #else
  7641. # define dump_cmd_in_x_mode(argv) ((void)0)
  7642. #endif
  7643. #if ENABLE_HUSH_COMMAND
  7644. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7645. {
  7646. char *to_free;
  7647. if (!opt_vV)
  7648. return;
  7649. to_free = NULL;
  7650. if (!explanation) {
  7651. char *path = getenv("PATH");
  7652. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7653. if (!explanation)
  7654. _exit(1); /* PROG was not found */
  7655. if (opt_vV != 'V')
  7656. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7657. }
  7658. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7659. free(to_free);
  7660. fflush_all();
  7661. _exit(0);
  7662. }
  7663. #else
  7664. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7665. #endif
  7666. #if BB_MMU
  7667. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7668. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7669. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7670. pseudo_exec(command, argv_expanded)
  7671. #endif
  7672. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7673. * Never returns.
  7674. * Don't exit() here. If you don't exec, use _exit instead.
  7675. * The at_exit handlers apparently confuse the calling process,
  7676. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7677. */
  7678. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7679. char **argv, int assignment_cnt,
  7680. char **argv_expanded) NORETURN;
  7681. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7682. char **argv, int assignment_cnt,
  7683. char **argv_expanded)
  7684. {
  7685. const struct built_in_command *x;
  7686. struct variable **sv_shadowed;
  7687. char **new_env;
  7688. IF_HUSH_COMMAND(char opt_vV = 0;)
  7689. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7690. new_env = expand_assignments(argv, assignment_cnt);
  7691. dump_cmd_in_x_mode(new_env);
  7692. if (!argv[assignment_cnt]) {
  7693. /* Case when we are here: ... | var=val | ...
  7694. * (note that we do not exit early, i.e., do not optimize out
  7695. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7696. */
  7697. free_strings(new_env);
  7698. _exit(EXIT_SUCCESS);
  7699. }
  7700. sv_shadowed = G.shadowed_vars_pp;
  7701. #if BB_MMU
  7702. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7703. #else
  7704. G.shadowed_vars_pp = &nommu_save->old_vars;
  7705. G.var_nest_level++;
  7706. #endif
  7707. set_vars_and_save_old(new_env);
  7708. G.shadowed_vars_pp = sv_shadowed;
  7709. if (argv_expanded) {
  7710. argv = argv_expanded;
  7711. } else {
  7712. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7713. #if !BB_MMU
  7714. nommu_save->argv = argv;
  7715. #endif
  7716. }
  7717. dump_cmd_in_x_mode(argv);
  7718. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7719. if (strchr(argv[0], '/') != NULL)
  7720. goto skip;
  7721. #endif
  7722. #if ENABLE_HUSH_FUNCTIONS
  7723. /* Check if the command matches any functions (this goes before bltins) */
  7724. funcp = find_function(argv[0]);
  7725. if (funcp)
  7726. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7727. #endif
  7728. #if ENABLE_HUSH_COMMAND
  7729. /* "command BAR": run BAR without looking it up among functions
  7730. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7731. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7732. */
  7733. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7734. char *p;
  7735. argv++;
  7736. p = *argv;
  7737. if (p[0] != '-' || !p[1])
  7738. continue; /* bash allows "command command command [-OPT] BAR" */
  7739. for (;;) {
  7740. p++;
  7741. switch (*p) {
  7742. case '\0':
  7743. argv++;
  7744. p = *argv;
  7745. if (p[0] != '-' || !p[1])
  7746. goto after_opts;
  7747. continue; /* next arg is also -opts, process it too */
  7748. case 'v':
  7749. case 'V':
  7750. opt_vV = *p;
  7751. continue;
  7752. default:
  7753. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7754. }
  7755. }
  7756. }
  7757. after_opts:
  7758. # if ENABLE_HUSH_FUNCTIONS
  7759. if (opt_vV && find_function(argv[0]))
  7760. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7761. # endif
  7762. #endif
  7763. /* Check if the command matches any of the builtins.
  7764. * Depending on context, this might be redundant. But it's
  7765. * easier to waste a few CPU cycles than it is to figure out
  7766. * if this is one of those cases.
  7767. */
  7768. /* Why "BB_MMU ? :" difference in logic? -
  7769. * On NOMMU, it is more expensive to re-execute shell
  7770. * just in order to run echo or test builtin.
  7771. * It's better to skip it here and run corresponding
  7772. * non-builtin later. */
  7773. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7774. if (x) {
  7775. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7776. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7777. }
  7778. #if ENABLE_FEATURE_SH_STANDALONE
  7779. /* Check if the command matches any busybox applets */
  7780. {
  7781. int a = find_applet_by_name(argv[0]);
  7782. if (a >= 0) {
  7783. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7784. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7785. if (APPLET_IS_NOEXEC(a)) {
  7786. /* Do not leak open fds from opened script files etc.
  7787. * Testcase: interactive "ls -l /proc/self/fd"
  7788. * should not show tty fd open.
  7789. */
  7790. close_saved_fds_and_FILE_fds();
  7791. //FIXME: should also close saved redir fds
  7792. //This casuses test failures in
  7793. //redir_children_should_not_see_saved_fd_2.tests
  7794. //redir_children_should_not_see_saved_fd_3.tests
  7795. //if you replace "busybox find" with just "find" in them
  7796. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7797. switch_off_special_sigs(G.special_sig_mask);
  7798. debug_printf_exec("running applet '%s'\n", argv[0]);
  7799. run_noexec_applet_and_exit(a, argv[0], argv);
  7800. }
  7801. # endif
  7802. /* Re-exec ourselves */
  7803. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7804. /* Don't propagate SIG_IGN to the child */
  7805. if (SPECIAL_JOBSTOP_SIGS != 0)
  7806. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7807. execv(bb_busybox_exec_path, argv);
  7808. /* If they called chroot or otherwise made the binary no longer
  7809. * executable, fall through */
  7810. }
  7811. }
  7812. #endif
  7813. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7814. skip:
  7815. #endif
  7816. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7817. execvp_or_die(argv);
  7818. }
  7819. /* Called after [v]fork() in run_pipe
  7820. */
  7821. static void pseudo_exec(nommu_save_t *nommu_save,
  7822. struct command *command,
  7823. char **argv_expanded) NORETURN;
  7824. static void pseudo_exec(nommu_save_t *nommu_save,
  7825. struct command *command,
  7826. char **argv_expanded)
  7827. {
  7828. #if ENABLE_HUSH_FUNCTIONS
  7829. if (command->cmd_type == CMD_FUNCDEF) {
  7830. /* Ignore funcdefs in pipes:
  7831. * true | f() { cmd }
  7832. */
  7833. _exit(0);
  7834. }
  7835. #endif
  7836. if (command->argv) {
  7837. pseudo_exec_argv(nommu_save, command->argv,
  7838. command->assignment_cnt, argv_expanded);
  7839. }
  7840. if (command->group) {
  7841. /* Cases when we are here:
  7842. * ( list )
  7843. * { list } &
  7844. * ... | ( list ) | ...
  7845. * ... | { list } | ...
  7846. */
  7847. #if BB_MMU
  7848. int rcode;
  7849. debug_printf_exec("pseudo_exec: run_list\n");
  7850. reset_traps_to_defaults();
  7851. rcode = run_list(command->group);
  7852. /* OK to leak memory by not calling free_pipe_list,
  7853. * since this process is about to exit */
  7854. _exit(rcode);
  7855. #else
  7856. re_execute_shell(&nommu_save->argv_from_re_execing,
  7857. command->group_as_string,
  7858. G.global_argv[0],
  7859. G.global_argv + 1,
  7860. NULL);
  7861. #endif
  7862. }
  7863. /* Case when we are here: ... | >file */
  7864. debug_printf_exec("pseudo_exec'ed null command\n");
  7865. _exit(EXIT_SUCCESS);
  7866. }
  7867. #if ENABLE_HUSH_JOB
  7868. static const char *get_cmdtext(struct pipe *pi)
  7869. {
  7870. char **argv;
  7871. char *p;
  7872. int len;
  7873. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7874. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7875. * On subsequent bg argv is trashed, but we won't use it */
  7876. if (pi->cmdtext)
  7877. return pi->cmdtext;
  7878. argv = pi->cmds[0].argv;
  7879. if (!argv) {
  7880. pi->cmdtext = xzalloc(1);
  7881. return pi->cmdtext;
  7882. }
  7883. len = 0;
  7884. do {
  7885. len += strlen(*argv) + 1;
  7886. } while (*++argv);
  7887. p = xmalloc(len);
  7888. pi->cmdtext = p;
  7889. argv = pi->cmds[0].argv;
  7890. do {
  7891. p = stpcpy(p, *argv);
  7892. *p++ = ' ';
  7893. } while (*++argv);
  7894. p[-1] = '\0';
  7895. return pi->cmdtext;
  7896. }
  7897. static void remove_job_from_table(struct pipe *pi)
  7898. {
  7899. struct pipe *prev_pipe;
  7900. if (pi == G.job_list) {
  7901. G.job_list = pi->next;
  7902. } else {
  7903. prev_pipe = G.job_list;
  7904. while (prev_pipe->next != pi)
  7905. prev_pipe = prev_pipe->next;
  7906. prev_pipe->next = pi->next;
  7907. }
  7908. G.last_jobid = 0;
  7909. if (G.job_list)
  7910. G.last_jobid = G.job_list->jobid;
  7911. }
  7912. static void delete_finished_job(struct pipe *pi)
  7913. {
  7914. remove_job_from_table(pi);
  7915. free_pipe(pi);
  7916. }
  7917. static void clean_up_last_dead_job(void)
  7918. {
  7919. if (G.job_list && !G.job_list->alive_cmds)
  7920. delete_finished_job(G.job_list);
  7921. }
  7922. static void insert_job_into_table(struct pipe *pi)
  7923. {
  7924. struct pipe *job, **jobp;
  7925. int i;
  7926. clean_up_last_dead_job();
  7927. /* Find the end of the list, and find next job ID to use */
  7928. i = 0;
  7929. jobp = &G.job_list;
  7930. while ((job = *jobp) != NULL) {
  7931. if (job->jobid > i)
  7932. i = job->jobid;
  7933. jobp = &job->next;
  7934. }
  7935. pi->jobid = i + 1;
  7936. /* Create a new job struct at the end */
  7937. job = *jobp = xmemdup(pi, sizeof(*pi));
  7938. job->next = NULL;
  7939. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7940. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7941. for (i = 0; i < pi->num_cmds; i++) {
  7942. job->cmds[i].pid = pi->cmds[i].pid;
  7943. /* all other fields are not used and stay zero */
  7944. }
  7945. job->cmdtext = xstrdup(get_cmdtext(pi));
  7946. if (G_interactive_fd)
  7947. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  7948. G.last_jobid = job->jobid;
  7949. }
  7950. #endif /* JOB */
  7951. static int job_exited_or_stopped(struct pipe *pi)
  7952. {
  7953. int rcode, i;
  7954. if (pi->alive_cmds != pi->stopped_cmds)
  7955. return -1;
  7956. /* All processes in fg pipe have exited or stopped */
  7957. rcode = 0;
  7958. i = pi->num_cmds;
  7959. while (--i >= 0) {
  7960. rcode = pi->cmds[i].cmd_exitcode;
  7961. /* usually last process gives overall exitstatus,
  7962. * but with "set -o pipefail", last *failed* process does */
  7963. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  7964. break;
  7965. }
  7966. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  7967. return rcode;
  7968. }
  7969. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  7970. {
  7971. #if ENABLE_HUSH_JOB
  7972. struct pipe *pi;
  7973. #endif
  7974. int i, dead;
  7975. dead = WIFEXITED(status) || WIFSIGNALED(status);
  7976. #if DEBUG_JOBS
  7977. if (WIFSTOPPED(status))
  7978. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  7979. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  7980. if (WIFSIGNALED(status))
  7981. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  7982. childpid, WTERMSIG(status), WEXITSTATUS(status));
  7983. if (WIFEXITED(status))
  7984. debug_printf_jobs("pid %d exited, exitcode %d\n",
  7985. childpid, WEXITSTATUS(status));
  7986. #endif
  7987. /* Were we asked to wait for a fg pipe? */
  7988. if (fg_pipe) {
  7989. i = fg_pipe->num_cmds;
  7990. while (--i >= 0) {
  7991. int rcode;
  7992. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  7993. if (fg_pipe->cmds[i].pid != childpid)
  7994. continue;
  7995. if (dead) {
  7996. int ex;
  7997. fg_pipe->cmds[i].pid = 0;
  7998. fg_pipe->alive_cmds--;
  7999. ex = WEXITSTATUS(status);
  8000. /* bash prints killer signal's name for *last*
  8001. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8002. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8003. */
  8004. if (WIFSIGNALED(status)) {
  8005. int sig = WTERMSIG(status);
  8006. if (i == fg_pipe->num_cmds-1)
  8007. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8008. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8009. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8010. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8011. * Maybe we need to use sig | 128? */
  8012. ex = sig + 128;
  8013. }
  8014. fg_pipe->cmds[i].cmd_exitcode = ex;
  8015. } else {
  8016. fg_pipe->stopped_cmds++;
  8017. }
  8018. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8019. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8020. rcode = job_exited_or_stopped(fg_pipe);
  8021. if (rcode >= 0) {
  8022. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8023. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8024. * and "killall -STOP cat" */
  8025. if (G_interactive_fd) {
  8026. #if ENABLE_HUSH_JOB
  8027. if (fg_pipe->alive_cmds != 0)
  8028. insert_job_into_table(fg_pipe);
  8029. #endif
  8030. return rcode;
  8031. }
  8032. if (fg_pipe->alive_cmds == 0)
  8033. return rcode;
  8034. }
  8035. /* There are still running processes in the fg_pipe */
  8036. return -1;
  8037. }
  8038. /* It wasn't in fg_pipe, look for process in bg pipes */
  8039. }
  8040. #if ENABLE_HUSH_JOB
  8041. /* We were asked to wait for bg or orphaned children */
  8042. /* No need to remember exitcode in this case */
  8043. for (pi = G.job_list; pi; pi = pi->next) {
  8044. for (i = 0; i < pi->num_cmds; i++) {
  8045. if (pi->cmds[i].pid == childpid)
  8046. goto found_pi_and_prognum;
  8047. }
  8048. }
  8049. /* Happens when shell is used as init process (init=/bin/sh) */
  8050. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8051. return -1; /* this wasn't a process from fg_pipe */
  8052. found_pi_and_prognum:
  8053. if (dead) {
  8054. /* child exited */
  8055. int rcode = WEXITSTATUS(status);
  8056. if (WIFSIGNALED(status))
  8057. rcode = 128 + WTERMSIG(status);
  8058. pi->cmds[i].cmd_exitcode = rcode;
  8059. if (G.last_bg_pid == pi->cmds[i].pid)
  8060. G.last_bg_pid_exitcode = rcode;
  8061. pi->cmds[i].pid = 0;
  8062. pi->alive_cmds--;
  8063. if (!pi->alive_cmds) {
  8064. if (G_interactive_fd) {
  8065. printf(JOB_STATUS_FORMAT, pi->jobid,
  8066. "Done", pi->cmdtext);
  8067. delete_finished_job(pi);
  8068. } else {
  8069. /*
  8070. * bash deletes finished jobs from job table only in interactive mode,
  8071. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8072. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8073. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8074. * We only retain one "dead" job, if it's the single job on the list.
  8075. * This covers most of real-world scenarios where this is useful.
  8076. */
  8077. if (pi != G.job_list)
  8078. delete_finished_job(pi);
  8079. }
  8080. }
  8081. } else {
  8082. /* child stopped */
  8083. pi->stopped_cmds++;
  8084. }
  8085. #endif
  8086. return -1; /* this wasn't a process from fg_pipe */
  8087. }
  8088. /* Check to see if any processes have exited -- if they have,
  8089. * figure out why and see if a job has completed.
  8090. *
  8091. * If non-NULL fg_pipe: wait for its completion or stop.
  8092. * Return its exitcode or zero if stopped.
  8093. *
  8094. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8095. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8096. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8097. * or 0 if no children changed status.
  8098. *
  8099. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8100. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8101. * or 0 if no children changed status.
  8102. */
  8103. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8104. {
  8105. int attributes;
  8106. int status;
  8107. int rcode = 0;
  8108. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8109. attributes = WUNTRACED;
  8110. if (fg_pipe == NULL)
  8111. attributes |= WNOHANG;
  8112. errno = 0;
  8113. #if ENABLE_HUSH_FAST
  8114. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8115. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8116. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8117. /* There was neither fork nor SIGCHLD since last waitpid */
  8118. /* Avoid doing waitpid syscall if possible */
  8119. if (!G.we_have_children) {
  8120. errno = ECHILD;
  8121. return -1;
  8122. }
  8123. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8124. /* We have children, but they did not exit
  8125. * or stop yet (we saw no SIGCHLD) */
  8126. return 0;
  8127. }
  8128. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8129. }
  8130. #endif
  8131. /* Do we do this right?
  8132. * bash-3.00# sleep 20 | false
  8133. * <ctrl-Z pressed>
  8134. * [3]+ Stopped sleep 20 | false
  8135. * bash-3.00# echo $?
  8136. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8137. * [hush 1.14.0: yes we do it right]
  8138. */
  8139. while (1) {
  8140. pid_t childpid;
  8141. #if ENABLE_HUSH_FAST
  8142. int i;
  8143. i = G.count_SIGCHLD;
  8144. #endif
  8145. childpid = waitpid(-1, &status, attributes);
  8146. if (childpid <= 0) {
  8147. if (childpid && errno != ECHILD)
  8148. bb_perror_msg("waitpid");
  8149. #if ENABLE_HUSH_FAST
  8150. else { /* Until next SIGCHLD, waitpid's are useless */
  8151. G.we_have_children = (childpid == 0);
  8152. G.handled_SIGCHLD = i;
  8153. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8154. }
  8155. #endif
  8156. /* ECHILD (no children), or 0 (no change in children status) */
  8157. rcode = childpid;
  8158. break;
  8159. }
  8160. rcode = process_wait_result(fg_pipe, childpid, status);
  8161. if (rcode >= 0) {
  8162. /* fg_pipe exited or stopped */
  8163. break;
  8164. }
  8165. if (childpid == waitfor_pid) {
  8166. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8167. rcode = WEXITSTATUS(status);
  8168. if (WIFSIGNALED(status))
  8169. rcode = 128 + WTERMSIG(status);
  8170. if (WIFSTOPPED(status))
  8171. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8172. rcode = 128 + WSTOPSIG(status);
  8173. rcode++;
  8174. break; /* "wait PID" called us, give it exitcode+1 */
  8175. }
  8176. /* This wasn't one of our processes, or */
  8177. /* fg_pipe still has running processes, do waitpid again */
  8178. } /* while (waitpid succeeds)... */
  8179. return rcode;
  8180. }
  8181. #if ENABLE_HUSH_JOB
  8182. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8183. {
  8184. pid_t p;
  8185. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8186. if (G_saved_tty_pgrp) {
  8187. /* Job finished, move the shell to the foreground */
  8188. p = getpgrp(); /* our process group id */
  8189. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8190. tcsetpgrp(G_interactive_fd, p);
  8191. }
  8192. return rcode;
  8193. }
  8194. #endif
  8195. /* Start all the jobs, but don't wait for anything to finish.
  8196. * See checkjobs().
  8197. *
  8198. * Return code is normally -1, when the caller has to wait for children
  8199. * to finish to determine the exit status of the pipe. If the pipe
  8200. * is a simple builtin command, however, the action is done by the
  8201. * time run_pipe returns, and the exit code is provided as the
  8202. * return value.
  8203. *
  8204. * Returns -1 only if started some children. IOW: we have to
  8205. * mask out retvals of builtins etc with 0xff!
  8206. *
  8207. * The only case when we do not need to [v]fork is when the pipe
  8208. * is single, non-backgrounded, non-subshell command. Examples:
  8209. * cmd ; ... { list } ; ...
  8210. * cmd && ... { list } && ...
  8211. * cmd || ... { list } || ...
  8212. * If it is, then we can run cmd as a builtin, NOFORK,
  8213. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8214. * with run_list. If it isn't one of these, we fork and exec cmd.
  8215. *
  8216. * Cases when we must fork:
  8217. * non-single: cmd | cmd
  8218. * backgrounded: cmd & { list } &
  8219. * subshell: ( list ) [&]
  8220. */
  8221. #if !ENABLE_HUSH_MODE_X
  8222. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8223. redirect_and_varexp_helper(command, sqp)
  8224. #endif
  8225. static int redirect_and_varexp_helper(
  8226. struct command *command,
  8227. struct squirrel **sqp,
  8228. char **argv_expanded)
  8229. {
  8230. /* Assignments occur before redirects. Try:
  8231. * a=`sleep 1` sleep 2 3>/qwe/rty
  8232. */
  8233. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8234. dump_cmd_in_x_mode(new_env);
  8235. dump_cmd_in_x_mode(argv_expanded);
  8236. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8237. set_vars_and_save_old(new_env);
  8238. return setup_redirects(command, sqp);
  8239. }
  8240. static NOINLINE int run_pipe(struct pipe *pi)
  8241. {
  8242. static const char *const null_ptr = NULL;
  8243. int cmd_no;
  8244. int next_infd;
  8245. struct command *command;
  8246. char **argv_expanded;
  8247. char **argv;
  8248. struct squirrel *squirrel = NULL;
  8249. int rcode;
  8250. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8251. debug_enter();
  8252. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8253. * Result should be 3 lines: q w e, qwe, q w e
  8254. */
  8255. if (G.ifs_whitespace != G.ifs)
  8256. free(G.ifs_whitespace);
  8257. G.ifs = get_local_var_value("IFS");
  8258. if (G.ifs) {
  8259. char *p;
  8260. G.ifs_whitespace = (char*)G.ifs;
  8261. p = skip_whitespace(G.ifs);
  8262. if (*p) {
  8263. /* Not all $IFS is whitespace */
  8264. char *d;
  8265. int len = p - G.ifs;
  8266. p = skip_non_whitespace(p);
  8267. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8268. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8269. while (*p) {
  8270. if (isspace(*p))
  8271. *d++ = *p;
  8272. p++;
  8273. }
  8274. *d = '\0';
  8275. }
  8276. } else {
  8277. G.ifs = defifs;
  8278. G.ifs_whitespace = (char*)G.ifs;
  8279. }
  8280. IF_HUSH_JOB(pi->pgrp = -1;)
  8281. pi->stopped_cmds = 0;
  8282. command = &pi->cmds[0];
  8283. argv_expanded = NULL;
  8284. if (pi->num_cmds != 1
  8285. || pi->followup == PIPE_BG
  8286. || command->cmd_type == CMD_SUBSHELL
  8287. ) {
  8288. goto must_fork;
  8289. }
  8290. pi->alive_cmds = 1;
  8291. debug_printf_exec(": group:%p argv:'%s'\n",
  8292. command->group, command->argv ? command->argv[0] : "NONE");
  8293. if (command->group) {
  8294. #if ENABLE_HUSH_FUNCTIONS
  8295. if (command->cmd_type == CMD_FUNCDEF) {
  8296. /* "executing" func () { list } */
  8297. struct function *funcp;
  8298. funcp = new_function(command->argv[0]);
  8299. /* funcp->name is already set to argv[0] */
  8300. funcp->body = command->group;
  8301. # if !BB_MMU
  8302. funcp->body_as_string = command->group_as_string;
  8303. command->group_as_string = NULL;
  8304. # endif
  8305. command->group = NULL;
  8306. command->argv[0] = NULL;
  8307. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8308. funcp->parent_cmd = command;
  8309. command->child_func = funcp;
  8310. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8311. debug_leave();
  8312. return EXIT_SUCCESS;
  8313. }
  8314. #endif
  8315. /* { list } */
  8316. debug_printf_exec("non-subshell group\n");
  8317. rcode = 1; /* exitcode if redir failed */
  8318. if (setup_redirects(command, &squirrel) == 0) {
  8319. debug_printf_exec(": run_list\n");
  8320. //FIXME: we need to pass squirrel down into run_list()
  8321. //for SH_STANDALONE case, or else this construct:
  8322. // { find /proc/self/fd; true; } >FILE; cmd2
  8323. //has no way of closing saved fd#1 for "find",
  8324. //and in SH_STANDALONE mode, "find" is not execed,
  8325. //therefore CLOEXEC on saved fd does not help.
  8326. rcode = run_list(command->group) & 0xff;
  8327. }
  8328. restore_redirects(squirrel);
  8329. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8330. debug_leave();
  8331. debug_printf_exec("run_pipe: return %d\n", rcode);
  8332. return rcode;
  8333. }
  8334. argv = command->argv ? command->argv : (char **) &null_ptr;
  8335. {
  8336. const struct built_in_command *x;
  8337. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8338. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8339. struct variable **sv_shadowed;
  8340. struct variable *old_vars;
  8341. #if ENABLE_HUSH_LINENO_VAR
  8342. if (G.lineno_var)
  8343. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  8344. #endif
  8345. if (argv[command->assignment_cnt] == NULL) {
  8346. /* Assignments, but no command.
  8347. * Ensure redirects take effect (that is, create files).
  8348. * Try "a=t >file"
  8349. */
  8350. unsigned i;
  8351. G.expand_exitcode = 0;
  8352. only_assignments:
  8353. rcode = setup_redirects(command, &squirrel);
  8354. restore_redirects(squirrel);
  8355. /* Set shell variables */
  8356. i = 0;
  8357. while (i < command->assignment_cnt) {
  8358. char *p = expand_string_to_string(argv[i],
  8359. EXP_FLAG_ESC_GLOB_CHARS,
  8360. /*unbackslash:*/ 1
  8361. );
  8362. #if ENABLE_HUSH_MODE_X
  8363. if (G_x_mode) {
  8364. char *eq;
  8365. if (i == 0)
  8366. x_mode_prefix();
  8367. x_mode_addchr(' ');
  8368. eq = strchrnul(p, '=');
  8369. if (*eq) eq++;
  8370. x_mode_addblock(p, (eq - p));
  8371. x_mode_print_optionally_squoted(eq);
  8372. x_mode_flush();
  8373. }
  8374. #endif
  8375. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8376. if (set_local_var(p, /*flag:*/ 0)) {
  8377. /* assignment to readonly var / putenv error? */
  8378. rcode = 1;
  8379. }
  8380. i++;
  8381. }
  8382. /* Redirect error sets $? to 1. Otherwise,
  8383. * if evaluating assignment value set $?, retain it.
  8384. * Else, clear $?:
  8385. * false; q=`exit 2`; echo $? - should print 2
  8386. * false; x=1; echo $? - should print 0
  8387. * Because of the 2nd case, we can't just use G.last_exitcode.
  8388. */
  8389. if (rcode == 0)
  8390. rcode = G.expand_exitcode;
  8391. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8392. debug_leave();
  8393. debug_printf_exec("run_pipe: return %d\n", rcode);
  8394. return rcode;
  8395. }
  8396. /* Expand the rest into (possibly) many strings each */
  8397. #if defined(CMD_SINGLEWORD_NOGLOB)
  8398. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8399. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8400. else
  8401. #endif
  8402. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8403. /* If someone gives us an empty string: `cmd with empty output` */
  8404. if (!argv_expanded[0]) {
  8405. free(argv_expanded);
  8406. /* `false` still has to set exitcode 1 */
  8407. G.expand_exitcode = G.last_exitcode;
  8408. goto only_assignments;
  8409. }
  8410. old_vars = NULL;
  8411. sv_shadowed = G.shadowed_vars_pp;
  8412. /* Check if argv[0] matches any functions (this goes before bltins) */
  8413. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8414. IF_HUSH_FUNCTIONS(x = NULL;)
  8415. IF_HUSH_FUNCTIONS(if (!funcp))
  8416. x = find_builtin(argv_expanded[0]);
  8417. if (x || funcp) {
  8418. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8419. debug_printf("exec with redirects only\n");
  8420. /*
  8421. * Variable assignments are executed, but then "forgotten":
  8422. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8423. * sleeps, but prints nothing.
  8424. */
  8425. enter_var_nest_level();
  8426. G.shadowed_vars_pp = &old_vars;
  8427. rcode = redirect_and_varexp_helper(command,
  8428. /*squirrel:*/ ERR_PTR,
  8429. argv_expanded
  8430. );
  8431. G.shadowed_vars_pp = sv_shadowed;
  8432. /* rcode=1 can be if redir file can't be opened */
  8433. goto clean_up_and_ret1;
  8434. }
  8435. /* Bump var nesting, or this will leak exported $a:
  8436. * a=b true; env | grep ^a=
  8437. */
  8438. enter_var_nest_level();
  8439. /* Collect all variables "shadowed" by helper
  8440. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8441. * into old_vars list:
  8442. */
  8443. G.shadowed_vars_pp = &old_vars;
  8444. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8445. if (rcode == 0) {
  8446. if (!funcp) {
  8447. /* Do not collect *to old_vars list* vars shadowed
  8448. * by e.g. "local VAR" builtin (collect them
  8449. * in the previously nested list instead):
  8450. * don't want them to be restored immediately
  8451. * after "local" completes.
  8452. */
  8453. G.shadowed_vars_pp = sv_shadowed;
  8454. debug_printf_exec(": builtin '%s' '%s'...\n",
  8455. x->b_cmd, argv_expanded[1]);
  8456. fflush_all();
  8457. rcode = x->b_function(argv_expanded) & 0xff;
  8458. fflush_all();
  8459. }
  8460. #if ENABLE_HUSH_FUNCTIONS
  8461. else {
  8462. debug_printf_exec(": function '%s' '%s'...\n",
  8463. funcp->name, argv_expanded[1]);
  8464. rcode = run_function(funcp, argv_expanded) & 0xff;
  8465. /*
  8466. * But do collect *to old_vars list* vars shadowed
  8467. * within function execution. To that end, restore
  8468. * this pointer _after_ function run:
  8469. */
  8470. G.shadowed_vars_pp = sv_shadowed;
  8471. }
  8472. #endif
  8473. }
  8474. } else
  8475. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8476. int n = find_applet_by_name(argv_expanded[0]);
  8477. if (n < 0 || !APPLET_IS_NOFORK(n))
  8478. goto must_fork;
  8479. enter_var_nest_level();
  8480. /* Collect all variables "shadowed" by helper into old_vars list */
  8481. G.shadowed_vars_pp = &old_vars;
  8482. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8483. G.shadowed_vars_pp = sv_shadowed;
  8484. if (rcode == 0) {
  8485. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8486. argv_expanded[0], argv_expanded[1]);
  8487. /*
  8488. * Note: signals (^C) can't interrupt here.
  8489. * We remember them and they will be acted upon
  8490. * after applet returns.
  8491. * This makes applets which can run for a long time
  8492. * and/or wait for user input ineligible for NOFORK:
  8493. * for example, "yes" or "rm" (rm -i waits for input).
  8494. */
  8495. rcode = run_nofork_applet(n, argv_expanded);
  8496. }
  8497. } else
  8498. goto must_fork;
  8499. restore_redirects(squirrel);
  8500. clean_up_and_ret1:
  8501. leave_var_nest_level();
  8502. add_vars(old_vars);
  8503. /*
  8504. * Try "usleep 99999999" + ^C + "echo $?"
  8505. * with FEATURE_SH_NOFORK=y.
  8506. */
  8507. if (!funcp) {
  8508. /* It was builtin or nofork.
  8509. * if this would be a real fork/execed program,
  8510. * it should have died if a fatal sig was received.
  8511. * But OTOH, there was no separate process,
  8512. * the sig was sent to _shell_, not to non-existing
  8513. * child.
  8514. * Let's just handle ^C only, this one is obvious:
  8515. * we aren't ok with exitcode 0 when ^C was pressed
  8516. * during builtin/nofork.
  8517. */
  8518. if (sigismember(&G.pending_set, SIGINT))
  8519. rcode = 128 + SIGINT;
  8520. }
  8521. free(argv_expanded);
  8522. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8523. debug_leave();
  8524. debug_printf_exec("run_pipe return %d\n", rcode);
  8525. return rcode;
  8526. }
  8527. must_fork:
  8528. /* NB: argv_expanded may already be created, and that
  8529. * might include `cmd` runs! Do not rerun it! We *must*
  8530. * use argv_expanded if it's non-NULL */
  8531. /* Going to fork a child per each pipe member */
  8532. pi->alive_cmds = 0;
  8533. next_infd = 0;
  8534. cmd_no = 0;
  8535. while (cmd_no < pi->num_cmds) {
  8536. struct fd_pair pipefds;
  8537. #if !BB_MMU
  8538. int sv_var_nest_level = G.var_nest_level;
  8539. volatile nommu_save_t nommu_save;
  8540. nommu_save.old_vars = NULL;
  8541. nommu_save.argv = NULL;
  8542. nommu_save.argv_from_re_execing = NULL;
  8543. #endif
  8544. command = &pi->cmds[cmd_no];
  8545. cmd_no++;
  8546. if (command->argv) {
  8547. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8548. command->argv[0], command->argv[1]);
  8549. } else {
  8550. debug_printf_exec(": pipe member with no argv\n");
  8551. }
  8552. /* pipes are inserted between pairs of commands */
  8553. pipefds.rd = 0;
  8554. pipefds.wr = 1;
  8555. if (cmd_no < pi->num_cmds)
  8556. xpiped_pair(pipefds);
  8557. #if ENABLE_HUSH_LINENO_VAR
  8558. if (G.lineno_var)
  8559. strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
  8560. #endif
  8561. command->pid = BB_MMU ? fork() : vfork();
  8562. if (!command->pid) { /* child */
  8563. #if ENABLE_HUSH_JOB
  8564. disable_restore_tty_pgrp_on_exit();
  8565. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8566. /* Every child adds itself to new process group
  8567. * with pgid == pid_of_first_child_in_pipe */
  8568. if (G.run_list_level == 1 && G_interactive_fd) {
  8569. pid_t pgrp;
  8570. pgrp = pi->pgrp;
  8571. if (pgrp < 0) /* true for 1st process only */
  8572. pgrp = getpid();
  8573. if (setpgid(0, pgrp) == 0
  8574. && pi->followup != PIPE_BG
  8575. && G_saved_tty_pgrp /* we have ctty */
  8576. ) {
  8577. /* We do it in *every* child, not just first,
  8578. * to avoid races */
  8579. tcsetpgrp(G_interactive_fd, pgrp);
  8580. }
  8581. }
  8582. #endif
  8583. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8584. /* 1st cmd in backgrounded pipe
  8585. * should have its stdin /dev/null'ed */
  8586. close(0);
  8587. if (open(bb_dev_null, O_RDONLY))
  8588. xopen("/", O_RDONLY);
  8589. } else {
  8590. xmove_fd(next_infd, 0);
  8591. }
  8592. xmove_fd(pipefds.wr, 1);
  8593. if (pipefds.rd > 1)
  8594. close(pipefds.rd);
  8595. /* Like bash, explicit redirects override pipes,
  8596. * and the pipe fd (fd#1) is available for dup'ing:
  8597. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8598. * of cmd1 goes into pipe.
  8599. */
  8600. if (setup_redirects(command, NULL)) {
  8601. /* Happens when redir file can't be opened:
  8602. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8603. * FOO
  8604. * hush: can't open '/qwe/rty': No such file or directory
  8605. * BAZ
  8606. * (echo BAR is not executed, it hits _exit(1) below)
  8607. */
  8608. _exit(1);
  8609. }
  8610. /* Stores to nommu_save list of env vars putenv'ed
  8611. * (NOMMU, on MMU we don't need that) */
  8612. /* cast away volatility... */
  8613. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8614. /* pseudo_exec() does not return */
  8615. }
  8616. /* parent or error */
  8617. #if ENABLE_HUSH_FAST
  8618. G.count_SIGCHLD++;
  8619. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8620. #endif
  8621. enable_restore_tty_pgrp_on_exit();
  8622. #if !BB_MMU
  8623. /* Clean up after vforked child */
  8624. free(nommu_save.argv);
  8625. free(nommu_save.argv_from_re_execing);
  8626. G.var_nest_level = sv_var_nest_level;
  8627. remove_nested_vars();
  8628. add_vars(nommu_save.old_vars);
  8629. #endif
  8630. free(argv_expanded);
  8631. argv_expanded = NULL;
  8632. if (command->pid < 0) { /* [v]fork failed */
  8633. /* Clearly indicate, was it fork or vfork */
  8634. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8635. } else {
  8636. pi->alive_cmds++;
  8637. #if ENABLE_HUSH_JOB
  8638. /* Second and next children need to know pid of first one */
  8639. if (pi->pgrp < 0)
  8640. pi->pgrp = command->pid;
  8641. #endif
  8642. }
  8643. if (cmd_no > 1)
  8644. close(next_infd);
  8645. if (cmd_no < pi->num_cmds)
  8646. close(pipefds.wr);
  8647. /* Pass read (output) pipe end to next iteration */
  8648. next_infd = pipefds.rd;
  8649. }
  8650. if (!pi->alive_cmds) {
  8651. debug_leave();
  8652. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8653. return 1;
  8654. }
  8655. debug_leave();
  8656. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8657. return -1;
  8658. }
  8659. /* NB: called by pseudo_exec, and therefore must not modify any
  8660. * global data until exec/_exit (we can be a child after vfork!) */
  8661. static int run_list(struct pipe *pi)
  8662. {
  8663. #if ENABLE_HUSH_CASE
  8664. char *case_word = NULL;
  8665. #endif
  8666. #if ENABLE_HUSH_LOOPS
  8667. struct pipe *loop_top = NULL;
  8668. char **for_lcur = NULL;
  8669. char **for_list = NULL;
  8670. #endif
  8671. smallint last_followup;
  8672. smalluint rcode;
  8673. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8674. smalluint cond_code = 0;
  8675. #else
  8676. enum { cond_code = 0 };
  8677. #endif
  8678. #if HAS_KEYWORDS
  8679. smallint rword; /* RES_foo */
  8680. smallint last_rword; /* ditto */
  8681. #endif
  8682. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8683. debug_enter();
  8684. #if ENABLE_HUSH_LOOPS
  8685. /* Check syntax for "for" */
  8686. {
  8687. struct pipe *cpipe;
  8688. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8689. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8690. continue;
  8691. /* current word is FOR or IN (BOLD in comments below) */
  8692. if (cpipe->next == NULL) {
  8693. syntax_error("malformed for");
  8694. debug_leave();
  8695. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8696. return 1;
  8697. }
  8698. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8699. if (cpipe->next->res_word == RES_DO)
  8700. continue;
  8701. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8702. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8703. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8704. ) {
  8705. syntax_error("malformed for");
  8706. debug_leave();
  8707. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8708. return 1;
  8709. }
  8710. }
  8711. }
  8712. #endif
  8713. /* Past this point, all code paths should jump to ret: label
  8714. * in order to return, no direct "return" statements please.
  8715. * This helps to ensure that no memory is leaked. */
  8716. #if ENABLE_HUSH_JOB
  8717. G.run_list_level++;
  8718. #endif
  8719. #if HAS_KEYWORDS
  8720. rword = RES_NONE;
  8721. last_rword = RES_XXXX;
  8722. #endif
  8723. last_followup = PIPE_SEQ;
  8724. rcode = G.last_exitcode;
  8725. /* Go through list of pipes, (maybe) executing them. */
  8726. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8727. int r;
  8728. int sv_errexit_depth;
  8729. if (G.flag_SIGINT)
  8730. break;
  8731. if (G_flag_return_in_progress == 1)
  8732. break;
  8733. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8734. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8735. rword, cond_code, last_rword);
  8736. sv_errexit_depth = G.errexit_depth;
  8737. if (
  8738. #if ENABLE_HUSH_IF
  8739. rword == RES_IF || rword == RES_ELIF ||
  8740. #endif
  8741. pi->followup != PIPE_SEQ
  8742. ) {
  8743. G.errexit_depth++;
  8744. }
  8745. #if ENABLE_HUSH_LOOPS
  8746. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8747. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8748. ) {
  8749. /* start of a loop: remember where loop starts */
  8750. loop_top = pi;
  8751. G.depth_of_loop++;
  8752. }
  8753. #endif
  8754. /* Still in the same "if...", "then..." or "do..." branch? */
  8755. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8756. if ((rcode == 0 && last_followup == PIPE_OR)
  8757. || (rcode != 0 && last_followup == PIPE_AND)
  8758. ) {
  8759. /* It is "<true> || CMD" or "<false> && CMD"
  8760. * and we should not execute CMD */
  8761. debug_printf_exec("skipped cmd because of || or &&\n");
  8762. last_followup = pi->followup;
  8763. goto dont_check_jobs_but_continue;
  8764. }
  8765. }
  8766. last_followup = pi->followup;
  8767. IF_HAS_KEYWORDS(last_rword = rword;)
  8768. #if ENABLE_HUSH_IF
  8769. if (cond_code) {
  8770. if (rword == RES_THEN) {
  8771. /* if false; then ... fi has exitcode 0! */
  8772. G.last_exitcode = rcode = EXIT_SUCCESS;
  8773. /* "if <false> THEN cmd": skip cmd */
  8774. continue;
  8775. }
  8776. } else {
  8777. if (rword == RES_ELSE || rword == RES_ELIF) {
  8778. /* "if <true> then ... ELSE/ELIF cmd":
  8779. * skip cmd and all following ones */
  8780. break;
  8781. }
  8782. }
  8783. #endif
  8784. #if ENABLE_HUSH_LOOPS
  8785. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8786. if (!for_lcur) {
  8787. /* first loop through for */
  8788. static const char encoded_dollar_at[] ALIGN1 = {
  8789. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8790. }; /* encoded representation of "$@" */
  8791. static const char *const encoded_dollar_at_argv[] = {
  8792. encoded_dollar_at, NULL
  8793. }; /* argv list with one element: "$@" */
  8794. char **vals;
  8795. G.last_exitcode = rcode = EXIT_SUCCESS;
  8796. vals = (char**)encoded_dollar_at_argv;
  8797. if (pi->next->res_word == RES_IN) {
  8798. /* if no variable values after "in" we skip "for" */
  8799. if (!pi->next->cmds[0].argv) {
  8800. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8801. break;
  8802. }
  8803. vals = pi->next->cmds[0].argv;
  8804. } /* else: "for var; do..." -> assume "$@" list */
  8805. /* create list of variable values */
  8806. debug_print_strings("for_list made from", vals);
  8807. for_list = expand_strvec_to_strvec(vals);
  8808. for_lcur = for_list;
  8809. debug_print_strings("for_list", for_list);
  8810. }
  8811. if (!*for_lcur) {
  8812. /* "for" loop is over, clean up */
  8813. free(for_list);
  8814. for_list = NULL;
  8815. for_lcur = NULL;
  8816. break;
  8817. }
  8818. /* Insert next value from for_lcur */
  8819. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8820. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8821. continue;
  8822. }
  8823. if (rword == RES_IN) {
  8824. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8825. }
  8826. if (rword == RES_DONE) {
  8827. continue; /* "done" has no cmds too */
  8828. }
  8829. #endif
  8830. #if ENABLE_HUSH_CASE
  8831. if (rword == RES_CASE) {
  8832. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8833. case_word = expand_string_to_string(pi->cmds->argv[0],
  8834. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8835. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8836. //unbackslash(case_word);
  8837. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8838. continue;
  8839. }
  8840. if (rword == RES_MATCH) {
  8841. char **argv;
  8842. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8843. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8844. break;
  8845. /* all prev words didn't match, does this one match? */
  8846. argv = pi->cmds->argv;
  8847. while (*argv) {
  8848. char *pattern;
  8849. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8850. pattern = expand_string_to_string(*argv,
  8851. EXP_FLAG_ESC_GLOB_CHARS,
  8852. /*unbackslash:*/ 0
  8853. );
  8854. /* TODO: which FNM_xxx flags to use? */
  8855. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8856. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8857. pattern, case_word, cond_code);
  8858. free(pattern);
  8859. if (cond_code == 0) {
  8860. /* match! we will execute this branch */
  8861. free(case_word);
  8862. case_word = NULL; /* make future "word)" stop */
  8863. break;
  8864. }
  8865. argv++;
  8866. }
  8867. continue;
  8868. }
  8869. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8870. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8871. if (cond_code != 0)
  8872. continue; /* not matched yet, skip this pipe */
  8873. }
  8874. if (rword == RES_ESAC) {
  8875. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8876. if (case_word) {
  8877. /* "case" did not match anything: still set $? (to 0) */
  8878. G.last_exitcode = rcode = EXIT_SUCCESS;
  8879. }
  8880. }
  8881. #endif
  8882. /* Just pressing <enter> in shell should check for jobs.
  8883. * OTOH, in non-interactive shell this is useless
  8884. * and only leads to extra job checks */
  8885. if (pi->num_cmds == 0) {
  8886. if (G_interactive_fd)
  8887. goto check_jobs_and_continue;
  8888. continue;
  8889. }
  8890. /* After analyzing all keywords and conditions, we decided
  8891. * to execute this pipe. NB: have to do checkjobs(NULL)
  8892. * after run_pipe to collect any background children,
  8893. * even if list execution is to be stopped. */
  8894. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8895. #if ENABLE_HUSH_LOOPS
  8896. G.flag_break_continue = 0;
  8897. #endif
  8898. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8899. if (r != -1) {
  8900. /* We ran a builtin, function, or group.
  8901. * rcode is already known
  8902. * and we don't need to wait for anything. */
  8903. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8904. G.last_exitcode = rcode;
  8905. check_and_run_traps();
  8906. #if ENABLE_HUSH_LOOPS
  8907. /* Was it "break" or "continue"? */
  8908. if (G.flag_break_continue) {
  8909. smallint fbc = G.flag_break_continue;
  8910. /* We might fall into outer *loop*,
  8911. * don't want to break it too */
  8912. if (loop_top) {
  8913. G.depth_break_continue--;
  8914. if (G.depth_break_continue == 0)
  8915. G.flag_break_continue = 0;
  8916. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8917. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8918. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8919. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8920. break;
  8921. }
  8922. /* "continue": simulate end of loop */
  8923. rword = RES_DONE;
  8924. continue;
  8925. }
  8926. #endif
  8927. if (G_flag_return_in_progress == 1) {
  8928. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8929. break;
  8930. }
  8931. } else if (pi->followup == PIPE_BG) {
  8932. /* What does bash do with attempts to background builtins? */
  8933. /* even bash 3.2 doesn't do that well with nested bg:
  8934. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8935. * I'm NOT treating inner &'s as jobs */
  8936. #if ENABLE_HUSH_JOB
  8937. if (G.run_list_level == 1)
  8938. insert_job_into_table(pi);
  8939. #endif
  8940. /* Last command's pid goes to $! */
  8941. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  8942. G.last_bg_pid_exitcode = 0;
  8943. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  8944. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  8945. rcode = EXIT_SUCCESS;
  8946. goto check_traps;
  8947. } else {
  8948. #if ENABLE_HUSH_JOB
  8949. if (G.run_list_level == 1 && G_interactive_fd) {
  8950. /* Waits for completion, then fg's main shell */
  8951. rcode = checkjobs_and_fg_shell(pi);
  8952. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  8953. goto check_traps;
  8954. }
  8955. #endif
  8956. /* This one just waits for completion */
  8957. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  8958. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  8959. check_traps:
  8960. G.last_exitcode = rcode;
  8961. check_and_run_traps();
  8962. }
  8963. /* Handle "set -e" */
  8964. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  8965. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  8966. if (G.errexit_depth == 0)
  8967. hush_exit(rcode);
  8968. }
  8969. G.errexit_depth = sv_errexit_depth;
  8970. /* Analyze how result affects subsequent commands */
  8971. #if ENABLE_HUSH_IF
  8972. if (rword == RES_IF || rword == RES_ELIF)
  8973. cond_code = rcode;
  8974. #endif
  8975. check_jobs_and_continue:
  8976. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8977. dont_check_jobs_but_continue: ;
  8978. #if ENABLE_HUSH_LOOPS
  8979. /* Beware of "while false; true; do ..."! */
  8980. if (pi->next
  8981. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  8982. /* check for RES_DONE is needed for "while ...; do \n done" case */
  8983. ) {
  8984. if (rword == RES_WHILE) {
  8985. if (rcode) {
  8986. /* "while false; do...done" - exitcode 0 */
  8987. G.last_exitcode = rcode = EXIT_SUCCESS;
  8988. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  8989. break;
  8990. }
  8991. }
  8992. if (rword == RES_UNTIL) {
  8993. if (!rcode) {
  8994. debug_printf_exec(": until expr is true: breaking\n");
  8995. break;
  8996. }
  8997. }
  8998. }
  8999. #endif
  9000. } /* for (pi) */
  9001. #if ENABLE_HUSH_JOB
  9002. G.run_list_level--;
  9003. #endif
  9004. #if ENABLE_HUSH_LOOPS
  9005. if (loop_top)
  9006. G.depth_of_loop--;
  9007. free(for_list);
  9008. #endif
  9009. #if ENABLE_HUSH_CASE
  9010. free(case_word);
  9011. #endif
  9012. debug_leave();
  9013. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9014. return rcode;
  9015. }
  9016. /* Select which version we will use */
  9017. static int run_and_free_list(struct pipe *pi)
  9018. {
  9019. int rcode = 0;
  9020. debug_printf_exec("run_and_free_list entered\n");
  9021. if (!G.o_opt[OPT_O_NOEXEC]) {
  9022. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9023. rcode = run_list(pi);
  9024. }
  9025. /* free_pipe_list has the side effect of clearing memory.
  9026. * In the long run that function can be merged with run_list,
  9027. * but doing that now would hobble the debugging effort. */
  9028. free_pipe_list(pi);
  9029. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9030. return rcode;
  9031. }
  9032. static void install_sighandlers(unsigned mask)
  9033. {
  9034. sighandler_t old_handler;
  9035. unsigned sig = 0;
  9036. while ((mask >>= 1) != 0) {
  9037. sig++;
  9038. if (!(mask & 1))
  9039. continue;
  9040. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9041. /* POSIX allows shell to re-enable SIGCHLD
  9042. * even if it was SIG_IGN on entry.
  9043. * Therefore we skip IGN check for it:
  9044. */
  9045. if (sig == SIGCHLD)
  9046. continue;
  9047. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  9048. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  9049. */
  9050. //if (sig == SIGHUP) continue; - TODO?
  9051. if (old_handler == SIG_IGN) {
  9052. /* oops... restore back to IGN, and record this fact */
  9053. install_sighandler(sig, old_handler);
  9054. #if ENABLE_HUSH_TRAP
  9055. if (!G_traps)
  9056. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9057. free(G_traps[sig]);
  9058. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9059. #endif
  9060. }
  9061. }
  9062. }
  9063. /* Called a few times only (or even once if "sh -c") */
  9064. static void install_special_sighandlers(void)
  9065. {
  9066. unsigned mask;
  9067. /* Which signals are shell-special? */
  9068. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9069. if (G_interactive_fd) {
  9070. mask |= SPECIAL_INTERACTIVE_SIGS;
  9071. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9072. mask |= SPECIAL_JOBSTOP_SIGS;
  9073. }
  9074. /* Careful, do not re-install handlers we already installed */
  9075. if (G.special_sig_mask != mask) {
  9076. unsigned diff = mask & ~G.special_sig_mask;
  9077. G.special_sig_mask = mask;
  9078. install_sighandlers(diff);
  9079. }
  9080. }
  9081. #if ENABLE_HUSH_JOB
  9082. /* helper */
  9083. /* Set handlers to restore tty pgrp and exit */
  9084. static void install_fatal_sighandlers(void)
  9085. {
  9086. unsigned mask;
  9087. /* We will restore tty pgrp on these signals */
  9088. mask = 0
  9089. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9090. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9091. + (1 << SIGBUS ) * HUSH_DEBUG
  9092. + (1 << SIGSEGV) * HUSH_DEBUG
  9093. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9094. + (1 << SIGABRT)
  9095. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9096. + (1 << SIGPIPE)
  9097. + (1 << SIGALRM)
  9098. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9099. * if we aren't interactive... but in this case
  9100. * we never want to restore pgrp on exit, and this fn is not called
  9101. */
  9102. /*+ (1 << SIGHUP )*/
  9103. /*+ (1 << SIGTERM)*/
  9104. /*+ (1 << SIGINT )*/
  9105. ;
  9106. G_fatal_sig_mask = mask;
  9107. install_sighandlers(mask);
  9108. }
  9109. #endif
  9110. static int set_mode(int state, char mode, const char *o_opt)
  9111. {
  9112. int idx;
  9113. switch (mode) {
  9114. case 'n':
  9115. G.o_opt[OPT_O_NOEXEC] = state;
  9116. break;
  9117. case 'x':
  9118. IF_HUSH_MODE_X(G_x_mode = state;)
  9119. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9120. break;
  9121. case 'o':
  9122. if (!o_opt) {
  9123. /* "set -+o" without parameter.
  9124. * in bash, set -o produces this output:
  9125. * pipefail off
  9126. * and set +o:
  9127. * set +o pipefail
  9128. * We always use the second form.
  9129. */
  9130. const char *p = o_opt_strings;
  9131. idx = 0;
  9132. while (*p) {
  9133. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9134. idx++;
  9135. p += strlen(p) + 1;
  9136. }
  9137. break;
  9138. }
  9139. idx = index_in_strings(o_opt_strings, o_opt);
  9140. if (idx >= 0) {
  9141. G.o_opt[idx] = state;
  9142. break;
  9143. }
  9144. case 'e':
  9145. G.o_opt[OPT_O_ERREXIT] = state;
  9146. break;
  9147. default:
  9148. return EXIT_FAILURE;
  9149. }
  9150. return EXIT_SUCCESS;
  9151. }
  9152. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9153. int hush_main(int argc, char **argv)
  9154. {
  9155. enum {
  9156. OPT_login = (1 << 0),
  9157. OPT_s = (1 << 1),
  9158. };
  9159. unsigned flags;
  9160. unsigned builtin_argc;
  9161. char **e;
  9162. struct variable *cur_var;
  9163. struct variable *shell_ver;
  9164. INIT_G();
  9165. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9166. G.last_exitcode = EXIT_SUCCESS;
  9167. #if ENABLE_HUSH_FAST
  9168. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9169. #endif
  9170. #if !BB_MMU
  9171. G.argv0_for_re_execing = argv[0];
  9172. #endif
  9173. /* Deal with HUSH_VERSION */
  9174. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9175. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9176. shell_ver = xzalloc(sizeof(*shell_ver));
  9177. shell_ver->flg_export = 1;
  9178. shell_ver->flg_read_only = 1;
  9179. /* Code which handles ${var<op>...} needs writable values for all variables,
  9180. * therefore we xstrdup: */
  9181. shell_ver->varstr = xstrdup(hush_version_str);
  9182. /* Create shell local variables from the values
  9183. * currently living in the environment */
  9184. G.top_var = shell_ver;
  9185. cur_var = G.top_var;
  9186. e = environ;
  9187. if (e) while (*e) {
  9188. char *value = strchr(*e, '=');
  9189. if (value) { /* paranoia */
  9190. cur_var->next = xzalloc(sizeof(*cur_var));
  9191. cur_var = cur_var->next;
  9192. cur_var->varstr = *e;
  9193. cur_var->max_len = strlen(*e);
  9194. cur_var->flg_export = 1;
  9195. }
  9196. e++;
  9197. }
  9198. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9199. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9200. putenv(shell_ver->varstr);
  9201. /* Export PWD */
  9202. set_pwd_var(SETFLAG_EXPORT);
  9203. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9204. /* Set (but not export) PS1/2 unless already set */
  9205. if (!get_local_var_value("PS1"))
  9206. set_local_var_from_halves("PS1", "\\w \\$ ");
  9207. if (!get_local_var_value("PS2"))
  9208. set_local_var_from_halves("PS2", "> ");
  9209. #endif
  9210. #if BASH_HOSTNAME_VAR
  9211. /* Set (but not export) HOSTNAME unless already set */
  9212. if (!get_local_var_value("HOSTNAME")) {
  9213. struct utsname uts;
  9214. uname(&uts);
  9215. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9216. }
  9217. #endif
  9218. /* IFS is not inherited from the parent environment */
  9219. set_local_var_from_halves("IFS", defifs);
  9220. /* bash also exports SHLVL and _,
  9221. * and sets (but doesn't export) the following variables:
  9222. * BASH=/bin/bash
  9223. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9224. * BASH_VERSION='3.2.0(1)-release'
  9225. * HOSTTYPE=i386
  9226. * MACHTYPE=i386-pc-linux-gnu
  9227. * OSTYPE=linux-gnu
  9228. * PPID=<NNNNN> - we also do it elsewhere
  9229. * EUID=<NNNNN>
  9230. * UID=<NNNNN>
  9231. * GROUPS=()
  9232. * LINES=<NNN>
  9233. * COLUMNS=<NNN>
  9234. * BASH_ARGC=()
  9235. * BASH_ARGV=()
  9236. * BASH_LINENO=()
  9237. * BASH_SOURCE=()
  9238. * DIRSTACK=()
  9239. * PIPESTATUS=([0]="0")
  9240. * HISTFILE=/<xxx>/.bash_history
  9241. * HISTFILESIZE=500
  9242. * HISTSIZE=500
  9243. * MAILCHECK=60
  9244. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9245. * SHELL=/bin/bash
  9246. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9247. * TERM=dumb
  9248. * OPTERR=1
  9249. * OPTIND=1
  9250. * PS4='+ '
  9251. */
  9252. #if ENABLE_HUSH_LINENO_VAR
  9253. if (ENABLE_HUSH_LINENO_VAR) {
  9254. char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
  9255. set_local_var(p, /*flags*/ 0);
  9256. G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
  9257. }
  9258. #endif
  9259. #if ENABLE_FEATURE_EDITING
  9260. G.line_input_state = new_line_input_t(FOR_SHELL);
  9261. #endif
  9262. /* Initialize some more globals to non-zero values */
  9263. cmdedit_update_prompt();
  9264. die_func = restore_ttypgrp_and__exit;
  9265. /* Shell is non-interactive at first. We need to call
  9266. * install_special_sighandlers() if we are going to execute "sh <script>",
  9267. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9268. * If we later decide that we are interactive, we run install_special_sighandlers()
  9269. * in order to intercept (more) signals.
  9270. */
  9271. /* Parse options */
  9272. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9273. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9274. builtin_argc = 0;
  9275. while (1) {
  9276. int opt = getopt(argc, argv, "+c:exinsl"
  9277. #if !BB_MMU
  9278. "<:$:R:V:"
  9279. # if ENABLE_HUSH_FUNCTIONS
  9280. "F:"
  9281. # endif
  9282. #endif
  9283. );
  9284. if (opt <= 0)
  9285. break;
  9286. switch (opt) {
  9287. case 'c':
  9288. /* Possibilities:
  9289. * sh ... -c 'script'
  9290. * sh ... -c 'script' ARG0 [ARG1...]
  9291. * On NOMMU, if builtin_argc != 0,
  9292. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9293. * "" needs to be replaced with NULL
  9294. * and BARGV vector fed to builtin function.
  9295. * Note: the form without ARG0 never happens:
  9296. * sh ... -c 'builtin' BARGV... ""
  9297. */
  9298. if (!G.root_pid) {
  9299. G.root_pid = getpid();
  9300. G.root_ppid = getppid();
  9301. }
  9302. G.global_argv = argv + optind;
  9303. G.global_argc = argc - optind;
  9304. if (builtin_argc) {
  9305. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9306. const struct built_in_command *x;
  9307. install_special_sighandlers();
  9308. x = find_builtin(optarg);
  9309. if (x) { /* paranoia */
  9310. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9311. G.global_argv += builtin_argc;
  9312. G.global_argv[-1] = NULL; /* replace "" */
  9313. fflush_all();
  9314. G.last_exitcode = x->b_function(argv + optind - 1);
  9315. }
  9316. goto final_return;
  9317. }
  9318. if (!G.global_argv[0]) {
  9319. /* -c 'script' (no params): prevent empty $0 */
  9320. G.global_argv--; /* points to argv[i] of 'script' */
  9321. G.global_argv[0] = argv[0];
  9322. G.global_argc++;
  9323. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9324. install_special_sighandlers();
  9325. parse_and_run_string(optarg);
  9326. goto final_return;
  9327. case 'i':
  9328. /* Well, we cannot just declare interactiveness,
  9329. * we have to have some stuff (ctty, etc) */
  9330. /* G_interactive_fd++; */
  9331. break;
  9332. case 's':
  9333. flags |= OPT_s;
  9334. break;
  9335. case 'l':
  9336. flags |= OPT_login;
  9337. break;
  9338. #if !BB_MMU
  9339. case '<': /* "big heredoc" support */
  9340. full_write1_str(optarg);
  9341. _exit(0);
  9342. case '$': {
  9343. unsigned long long empty_trap_mask;
  9344. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9345. optarg++;
  9346. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9347. optarg++;
  9348. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9349. optarg++;
  9350. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9351. optarg++;
  9352. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9353. optarg++;
  9354. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9355. if (empty_trap_mask != 0) {
  9356. IF_HUSH_TRAP(int sig;)
  9357. install_special_sighandlers();
  9358. # if ENABLE_HUSH_TRAP
  9359. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9360. for (sig = 1; sig < NSIG; sig++) {
  9361. if (empty_trap_mask & (1LL << sig)) {
  9362. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9363. install_sighandler(sig, SIG_IGN);
  9364. }
  9365. }
  9366. # endif
  9367. }
  9368. # if ENABLE_HUSH_LOOPS
  9369. optarg++;
  9370. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9371. # endif
  9372. # if ENABLE_HUSH_FUNCTIONS
  9373. /* nommu uses re-exec trick for "... | func | ...",
  9374. * should allow "return".
  9375. * This accidentally allows returns in subshells.
  9376. */
  9377. G_flag_return_in_progress = -1;
  9378. # endif
  9379. break;
  9380. }
  9381. case 'R':
  9382. case 'V':
  9383. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9384. break;
  9385. # if ENABLE_HUSH_FUNCTIONS
  9386. case 'F': {
  9387. struct function *funcp = new_function(optarg);
  9388. /* funcp->name is already set to optarg */
  9389. /* funcp->body is set to NULL. It's a special case. */
  9390. funcp->body_as_string = argv[optind];
  9391. optind++;
  9392. break;
  9393. }
  9394. # endif
  9395. #endif
  9396. case 'n':
  9397. case 'x':
  9398. case 'e':
  9399. if (set_mode(1, opt, NULL) == 0) /* no error */
  9400. break;
  9401. default:
  9402. #ifndef BB_VER
  9403. fprintf(stderr, "Usage: sh [FILE]...\n"
  9404. " or: sh -c command [args]...\n\n");
  9405. exit(EXIT_FAILURE);
  9406. #else
  9407. bb_show_usage();
  9408. #endif
  9409. }
  9410. } /* option parsing loop */
  9411. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9412. G.global_argc = argc - (optind - 1);
  9413. G.global_argv = argv + (optind - 1);
  9414. G.global_argv[0] = argv[0];
  9415. if (!G.root_pid) {
  9416. G.root_pid = getpid();
  9417. G.root_ppid = getppid();
  9418. }
  9419. /* If we are login shell... */
  9420. if (flags & OPT_login) {
  9421. HFILE *input;
  9422. debug_printf("sourcing /etc/profile\n");
  9423. input = hfopen("/etc/profile");
  9424. if (input != NULL) {
  9425. install_special_sighandlers();
  9426. parse_and_run_file(input);
  9427. hfclose(input);
  9428. }
  9429. /* bash: after sourcing /etc/profile,
  9430. * tries to source (in the given order):
  9431. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9432. * stopping on first found. --noprofile turns this off.
  9433. * bash also sources ~/.bash_logout on exit.
  9434. * If called as sh, skips .bash_XXX files.
  9435. */
  9436. }
  9437. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9438. if (!(flags & OPT_s) && G.global_argv[1]) {
  9439. HFILE *input;
  9440. /*
  9441. * "bash <script>" (which is never interactive (unless -i?))
  9442. * sources $BASH_ENV here (without scanning $PATH).
  9443. * If called as sh, does the same but with $ENV.
  9444. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9445. */
  9446. G.global_argc--;
  9447. G.global_argv++;
  9448. debug_printf("running script '%s'\n", G.global_argv[0]);
  9449. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9450. input = hfopen(G.global_argv[0]);
  9451. if (!input) {
  9452. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9453. }
  9454. xfunc_error_retval = 1;
  9455. install_special_sighandlers();
  9456. parse_and_run_file(input);
  9457. #if ENABLE_FEATURE_CLEAN_UP
  9458. hfclose(input);
  9459. #endif
  9460. goto final_return;
  9461. }
  9462. /* Up to here, shell was non-interactive. Now it may become one.
  9463. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9464. */
  9465. /* A shell is interactive if the '-i' flag was given,
  9466. * or if all of the following conditions are met:
  9467. * no -c command
  9468. * no arguments remaining or the -s flag given
  9469. * standard input is a terminal
  9470. * standard output is a terminal
  9471. * Refer to Posix.2, the description of the 'sh' utility.
  9472. */
  9473. #if ENABLE_HUSH_JOB
  9474. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9475. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9476. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9477. if (G_saved_tty_pgrp < 0)
  9478. G_saved_tty_pgrp = 0;
  9479. /* try to dup stdin to high fd#, >= 255 */
  9480. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9481. if (G_interactive_fd < 0) {
  9482. /* try to dup to any fd */
  9483. G_interactive_fd = dup(STDIN_FILENO);
  9484. if (G_interactive_fd < 0) {
  9485. /* give up */
  9486. G_interactive_fd = 0;
  9487. G_saved_tty_pgrp = 0;
  9488. }
  9489. }
  9490. // TODO: track & disallow any attempts of user
  9491. // to (inadvertently) close/redirect G_interactive_fd
  9492. }
  9493. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9494. if (G_interactive_fd) {
  9495. close_on_exec_on(G_interactive_fd);
  9496. if (G_saved_tty_pgrp) {
  9497. /* If we were run as 'hush &', sleep until we are
  9498. * in the foreground (tty pgrp == our pgrp).
  9499. * If we get started under a job aware app (like bash),
  9500. * make sure we are now in charge so we don't fight over
  9501. * who gets the foreground */
  9502. while (1) {
  9503. pid_t shell_pgrp = getpgrp();
  9504. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9505. if (G_saved_tty_pgrp == shell_pgrp)
  9506. break;
  9507. /* send TTIN to ourself (should stop us) */
  9508. kill(- shell_pgrp, SIGTTIN);
  9509. }
  9510. }
  9511. /* Install more signal handlers */
  9512. install_special_sighandlers();
  9513. if (G_saved_tty_pgrp) {
  9514. /* Set other signals to restore saved_tty_pgrp */
  9515. install_fatal_sighandlers();
  9516. /* Put ourselves in our own process group
  9517. * (bash, too, does this only if ctty is available) */
  9518. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9519. /* Grab control of the terminal */
  9520. tcsetpgrp(G_interactive_fd, getpid());
  9521. }
  9522. enable_restore_tty_pgrp_on_exit();
  9523. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9524. {
  9525. const char *hp = get_local_var_value("HISTFILE");
  9526. if (!hp) {
  9527. hp = get_local_var_value("HOME");
  9528. if (hp)
  9529. hp = concat_path_file(hp, ".hush_history");
  9530. } else {
  9531. hp = xstrdup(hp);
  9532. }
  9533. if (hp) {
  9534. G.line_input_state->hist_file = hp;
  9535. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9536. }
  9537. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9538. hp = get_local_var_value("HISTFILESIZE");
  9539. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9540. # endif
  9541. }
  9542. # endif
  9543. } else {
  9544. install_special_sighandlers();
  9545. }
  9546. #elif ENABLE_HUSH_INTERACTIVE
  9547. /* No job control compiled in, only prompt/line editing */
  9548. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9549. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9550. if (G_interactive_fd < 0) {
  9551. /* try to dup to any fd */
  9552. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9553. if (G_interactive_fd < 0)
  9554. /* give up */
  9555. G_interactive_fd = 0;
  9556. }
  9557. }
  9558. if (G_interactive_fd) {
  9559. close_on_exec_on(G_interactive_fd);
  9560. }
  9561. install_special_sighandlers();
  9562. #else
  9563. /* We have interactiveness code disabled */
  9564. install_special_sighandlers();
  9565. #endif
  9566. /* bash:
  9567. * if interactive but not a login shell, sources ~/.bashrc
  9568. * (--norc turns this off, --rcfile <file> overrides)
  9569. */
  9570. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  9571. /* note: ash and hush share this string */
  9572. printf("\n\n%s %s\n"
  9573. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9574. "\n",
  9575. bb_banner,
  9576. "hush - the humble shell"
  9577. );
  9578. }
  9579. parse_and_run_file(hfopen(NULL)); /* stdin */
  9580. final_return:
  9581. hush_exit(G.last_exitcode);
  9582. }
  9583. /*
  9584. * Built-ins
  9585. */
  9586. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9587. {
  9588. return 0;
  9589. }
  9590. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9591. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9592. {
  9593. int argc = string_array_len(argv);
  9594. return applet_main_func(argc, argv);
  9595. }
  9596. #endif
  9597. #if ENABLE_HUSH_TEST || BASH_TEST2
  9598. static int FAST_FUNC builtin_test(char **argv)
  9599. {
  9600. return run_applet_main(argv, test_main);
  9601. }
  9602. #endif
  9603. #if ENABLE_HUSH_ECHO
  9604. static int FAST_FUNC builtin_echo(char **argv)
  9605. {
  9606. return run_applet_main(argv, echo_main);
  9607. }
  9608. #endif
  9609. #if ENABLE_HUSH_PRINTF
  9610. static int FAST_FUNC builtin_printf(char **argv)
  9611. {
  9612. return run_applet_main(argv, printf_main);
  9613. }
  9614. #endif
  9615. #if ENABLE_HUSH_HELP
  9616. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9617. {
  9618. const struct built_in_command *x;
  9619. printf(
  9620. "Built-in commands:\n"
  9621. "------------------\n");
  9622. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9623. if (x->b_descr)
  9624. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9625. }
  9626. return EXIT_SUCCESS;
  9627. }
  9628. #endif
  9629. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9630. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9631. {
  9632. show_history(G.line_input_state);
  9633. return EXIT_SUCCESS;
  9634. }
  9635. #endif
  9636. static char **skip_dash_dash(char **argv)
  9637. {
  9638. argv++;
  9639. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9640. argv++;
  9641. return argv;
  9642. }
  9643. static int FAST_FUNC builtin_cd(char **argv)
  9644. {
  9645. const char *newdir;
  9646. argv = skip_dash_dash(argv);
  9647. newdir = argv[0];
  9648. if (newdir == NULL) {
  9649. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9650. * bash says "bash: cd: HOME not set" and does nothing
  9651. * (exitcode 1)
  9652. */
  9653. const char *home = get_local_var_value("HOME");
  9654. newdir = home ? home : "/";
  9655. }
  9656. if (chdir(newdir)) {
  9657. /* Mimic bash message exactly */
  9658. bb_perror_msg("cd: %s", newdir);
  9659. return EXIT_FAILURE;
  9660. }
  9661. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9662. * Note: do not enforce exporting. If PWD was unset or unexported,
  9663. * set it again, but do not export. bash does the same.
  9664. */
  9665. set_pwd_var(/*flag:*/ 0);
  9666. return EXIT_SUCCESS;
  9667. }
  9668. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9669. {
  9670. puts(get_cwd(0));
  9671. return EXIT_SUCCESS;
  9672. }
  9673. static int FAST_FUNC builtin_eval(char **argv)
  9674. {
  9675. argv = skip_dash_dash(argv);
  9676. if (!argv[0])
  9677. return EXIT_SUCCESS;
  9678. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9679. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9680. if (!argv[1]) {
  9681. /* bash:
  9682. * eval "echo Hi; done" ("done" is syntax error):
  9683. * "echo Hi" will not execute too.
  9684. */
  9685. parse_and_run_string(argv[0]);
  9686. } else {
  9687. /* "The eval utility shall construct a command by
  9688. * concatenating arguments together, separating
  9689. * each with a <space> character."
  9690. */
  9691. char *str, *p;
  9692. unsigned len = 0;
  9693. char **pp = argv;
  9694. do
  9695. len += strlen(*pp) + 1;
  9696. while (*++pp);
  9697. str = p = xmalloc(len);
  9698. pp = argv;
  9699. for (;;) {
  9700. p = stpcpy(p, *pp);
  9701. pp++;
  9702. if (!*pp)
  9703. break;
  9704. *p++ = ' ';
  9705. }
  9706. parse_and_run_string(str);
  9707. free(str);
  9708. }
  9709. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9710. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9711. return G.last_exitcode;
  9712. }
  9713. static int FAST_FUNC builtin_exec(char **argv)
  9714. {
  9715. argv = skip_dash_dash(argv);
  9716. if (argv[0] == NULL)
  9717. return EXIT_SUCCESS; /* bash does this */
  9718. /* Careful: we can end up here after [v]fork. Do not restore
  9719. * tty pgrp then, only top-level shell process does that */
  9720. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9721. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9722. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9723. * open here. However, they are all CLOEXEC, and execv below
  9724. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9725. * it should show no extra open fds in the "ls" process.
  9726. * If we'd try to run builtins/NOEXECs, this would need improving.
  9727. */
  9728. //close_saved_fds_and_FILE_fds();
  9729. /* TODO: if exec fails, bash does NOT exit! We do.
  9730. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9731. * and tcsetpgrp, and this is inherently racy.
  9732. */
  9733. execvp_or_die(argv);
  9734. }
  9735. static int FAST_FUNC builtin_exit(char **argv)
  9736. {
  9737. debug_printf_exec("%s()\n", __func__);
  9738. /* interactive bash:
  9739. * # trap "echo EEE" EXIT
  9740. * # exit
  9741. * exit
  9742. * There are stopped jobs.
  9743. * (if there are _stopped_ jobs, running ones don't count)
  9744. * # exit
  9745. * exit
  9746. * EEE (then bash exits)
  9747. *
  9748. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9749. */
  9750. /* note: EXIT trap is run by hush_exit */
  9751. argv = skip_dash_dash(argv);
  9752. if (argv[0] == NULL)
  9753. hush_exit(G.last_exitcode);
  9754. /* mimic bash: exit 123abc == exit 255 + error msg */
  9755. xfunc_error_retval = 255;
  9756. /* bash: exit -2 == exit 254, no error msg */
  9757. hush_exit(xatoi(argv[0]) & 0xff);
  9758. }
  9759. #if ENABLE_HUSH_TYPE
  9760. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9761. static int FAST_FUNC builtin_type(char **argv)
  9762. {
  9763. int ret = EXIT_SUCCESS;
  9764. while (*++argv) {
  9765. const char *type;
  9766. char *path = NULL;
  9767. if (0) {} /* make conditional compile easier below */
  9768. /*else if (find_alias(*argv))
  9769. type = "an alias";*/
  9770. #if ENABLE_HUSH_FUNCTIONS
  9771. else if (find_function(*argv))
  9772. type = "a function";
  9773. #endif
  9774. else if (find_builtin(*argv))
  9775. type = "a shell builtin";
  9776. else if ((path = find_in_path(*argv)) != NULL)
  9777. type = path;
  9778. else {
  9779. bb_error_msg("type: %s: not found", *argv);
  9780. ret = EXIT_FAILURE;
  9781. continue;
  9782. }
  9783. printf("%s is %s\n", *argv, type);
  9784. free(path);
  9785. }
  9786. return ret;
  9787. }
  9788. #endif
  9789. #if ENABLE_HUSH_READ
  9790. /* Interruptibility of read builtin in bash
  9791. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9792. *
  9793. * Empty trap makes read ignore corresponding signal, for any signal.
  9794. *
  9795. * SIGINT:
  9796. * - terminates non-interactive shell;
  9797. * - interrupts read in interactive shell;
  9798. * if it has non-empty trap:
  9799. * - executes trap and returns to command prompt in interactive shell;
  9800. * - executes trap and returns to read in non-interactive shell;
  9801. * SIGTERM:
  9802. * - is ignored (does not interrupt) read in interactive shell;
  9803. * - terminates non-interactive shell;
  9804. * if it has non-empty trap:
  9805. * - executes trap and returns to read;
  9806. * SIGHUP:
  9807. * - terminates shell (regardless of interactivity);
  9808. * if it has non-empty trap:
  9809. * - executes trap and returns to read;
  9810. * SIGCHLD from children:
  9811. * - does not interrupt read regardless of interactivity:
  9812. * try: sleep 1 & read x; echo $x
  9813. */
  9814. static int FAST_FUNC builtin_read(char **argv)
  9815. {
  9816. const char *r;
  9817. struct builtin_read_params params;
  9818. memset(&params, 0, sizeof(params));
  9819. /* "!": do not abort on errors.
  9820. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9821. */
  9822. params.read_flags = getopt32(argv,
  9823. #if BASH_READ_D
  9824. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9825. #else
  9826. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9827. #endif
  9828. );
  9829. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9830. return EXIT_FAILURE;
  9831. argv += optind;
  9832. params.argv = argv;
  9833. params.setvar = set_local_var_from_halves;
  9834. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9835. again:
  9836. r = shell_builtin_read(&params);
  9837. if ((uintptr_t)r == 1 && errno == EINTR) {
  9838. unsigned sig = check_and_run_traps();
  9839. if (sig != SIGINT)
  9840. goto again;
  9841. }
  9842. if ((uintptr_t)r > 1) {
  9843. bb_error_msg("%s", r);
  9844. r = (char*)(uintptr_t)1;
  9845. }
  9846. return (uintptr_t)r;
  9847. }
  9848. #endif
  9849. #if ENABLE_HUSH_UMASK
  9850. static int FAST_FUNC builtin_umask(char **argv)
  9851. {
  9852. int rc;
  9853. mode_t mask;
  9854. rc = 1;
  9855. mask = umask(0);
  9856. argv = skip_dash_dash(argv);
  9857. if (argv[0]) {
  9858. mode_t old_mask = mask;
  9859. /* numeric umasks are taken as-is */
  9860. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9861. if (!isdigit(argv[0][0]))
  9862. mask ^= 0777;
  9863. mask = bb_parse_mode(argv[0], mask);
  9864. if (!isdigit(argv[0][0]))
  9865. mask ^= 0777;
  9866. if ((unsigned)mask > 0777) {
  9867. mask = old_mask;
  9868. /* bash messages:
  9869. * bash: umask: 'q': invalid symbolic mode operator
  9870. * bash: umask: 999: octal number out of range
  9871. */
  9872. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9873. rc = 0;
  9874. }
  9875. } else {
  9876. /* Mimic bash */
  9877. printf("%04o\n", (unsigned) mask);
  9878. /* fall through and restore mask which we set to 0 */
  9879. }
  9880. umask(mask);
  9881. return !rc; /* rc != 0 - success */
  9882. }
  9883. #endif
  9884. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9885. static void print_escaped(const char *s)
  9886. {
  9887. if (*s == '\'')
  9888. goto squote;
  9889. do {
  9890. const char *p = strchrnul(s, '\'');
  9891. /* print 'xxxx', possibly just '' */
  9892. printf("'%.*s'", (int)(p - s), s);
  9893. if (*p == '\0')
  9894. break;
  9895. s = p;
  9896. squote:
  9897. /* s points to '; print "'''...'''" */
  9898. putchar('"');
  9899. do putchar('\''); while (*++s == '\'');
  9900. putchar('"');
  9901. } while (*s);
  9902. }
  9903. #endif
  9904. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9905. static int helper_export_local(char **argv, unsigned flags)
  9906. {
  9907. do {
  9908. char *name = *argv;
  9909. char *name_end = strchrnul(name, '=');
  9910. /* So far we do not check that name is valid (TODO?) */
  9911. if (*name_end == '\0') {
  9912. struct variable *var, **vpp;
  9913. vpp = get_ptr_to_local_var(name, name_end - name);
  9914. var = vpp ? *vpp : NULL;
  9915. if (flags & SETFLAG_UNEXPORT) {
  9916. /* export -n NAME (without =VALUE) */
  9917. if (var) {
  9918. var->flg_export = 0;
  9919. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9920. unsetenv(name);
  9921. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9922. continue;
  9923. }
  9924. if (flags & SETFLAG_EXPORT) {
  9925. /* export NAME (without =VALUE) */
  9926. if (var) {
  9927. var->flg_export = 1;
  9928. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  9929. putenv(var->varstr);
  9930. continue;
  9931. }
  9932. }
  9933. if (flags & SETFLAG_MAKE_RO) {
  9934. /* readonly NAME (without =VALUE) */
  9935. if (var) {
  9936. var->flg_read_only = 1;
  9937. continue;
  9938. }
  9939. }
  9940. # if ENABLE_HUSH_LOCAL
  9941. /* Is this "local" bltin? */
  9942. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  9943. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  9944. if (var && var->var_nest_level == lvl) {
  9945. /* "local x=abc; ...; local x" - ignore second local decl */
  9946. continue;
  9947. }
  9948. }
  9949. # endif
  9950. /* Exporting non-existing variable.
  9951. * bash does not put it in environment,
  9952. * but remembers that it is exported,
  9953. * and does put it in env when it is set later.
  9954. * We just set it to "" and export.
  9955. */
  9956. /* Or, it's "local NAME" (without =VALUE).
  9957. * bash sets the value to "".
  9958. */
  9959. /* Or, it's "readonly NAME" (without =VALUE).
  9960. * bash remembers NAME and disallows its creation
  9961. * in the future.
  9962. */
  9963. name = xasprintf("%s=", name);
  9964. } else {
  9965. /* (Un)exporting/making local NAME=VALUE */
  9966. name = xstrdup(name);
  9967. }
  9968. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  9969. if (set_local_var(name, flags))
  9970. return EXIT_FAILURE;
  9971. } while (*++argv);
  9972. return EXIT_SUCCESS;
  9973. }
  9974. #endif
  9975. #if ENABLE_HUSH_EXPORT
  9976. static int FAST_FUNC builtin_export(char **argv)
  9977. {
  9978. unsigned opt_unexport;
  9979. #if ENABLE_HUSH_EXPORT_N
  9980. /* "!": do not abort on errors */
  9981. opt_unexport = getopt32(argv, "!n");
  9982. if (opt_unexport == (uint32_t)-1)
  9983. return EXIT_FAILURE;
  9984. argv += optind;
  9985. #else
  9986. opt_unexport = 0;
  9987. argv++;
  9988. #endif
  9989. if (argv[0] == NULL) {
  9990. char **e = environ;
  9991. if (e) {
  9992. while (*e) {
  9993. #if 0
  9994. puts(*e++);
  9995. #else
  9996. /* ash emits: export VAR='VAL'
  9997. * bash: declare -x VAR="VAL"
  9998. * we follow ash example */
  9999. const char *s = *e++;
  10000. const char *p = strchr(s, '=');
  10001. if (!p) /* wtf? take next variable */
  10002. continue;
  10003. /* export var= */
  10004. printf("export %.*s", (int)(p - s) + 1, s);
  10005. print_escaped(p + 1);
  10006. putchar('\n');
  10007. #endif
  10008. }
  10009. /*fflush_all(); - done after each builtin anyway */
  10010. }
  10011. return EXIT_SUCCESS;
  10012. }
  10013. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10014. }
  10015. #endif
  10016. #if ENABLE_HUSH_LOCAL
  10017. static int FAST_FUNC builtin_local(char **argv)
  10018. {
  10019. if (G.func_nest_level == 0) {
  10020. bb_error_msg("%s: not in a function", argv[0]);
  10021. return EXIT_FAILURE; /* bash compat */
  10022. }
  10023. argv++;
  10024. /* Since all builtins run in a nested variable level,
  10025. * need to use level - 1 here. Or else the variable will be removed at once
  10026. * after builtin returns.
  10027. */
  10028. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10029. }
  10030. #endif
  10031. #if ENABLE_HUSH_READONLY
  10032. static int FAST_FUNC builtin_readonly(char **argv)
  10033. {
  10034. argv++;
  10035. if (*argv == NULL) {
  10036. /* bash: readonly [-p]: list all readonly VARs
  10037. * (-p has no effect in bash)
  10038. */
  10039. struct variable *e;
  10040. for (e = G.top_var; e; e = e->next) {
  10041. if (e->flg_read_only) {
  10042. //TODO: quote value: readonly VAR='VAL'
  10043. printf("readonly %s\n", e->varstr);
  10044. }
  10045. }
  10046. return EXIT_SUCCESS;
  10047. }
  10048. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10049. }
  10050. #endif
  10051. #if ENABLE_HUSH_UNSET
  10052. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10053. static int FAST_FUNC builtin_unset(char **argv)
  10054. {
  10055. int ret;
  10056. unsigned opts;
  10057. /* "!": do not abort on errors */
  10058. /* "+": stop at 1st non-option */
  10059. opts = getopt32(argv, "!+vf");
  10060. if (opts == (unsigned)-1)
  10061. return EXIT_FAILURE;
  10062. if (opts == 3) {
  10063. bb_error_msg("unset: -v and -f are exclusive");
  10064. return EXIT_FAILURE;
  10065. }
  10066. argv += optind;
  10067. ret = EXIT_SUCCESS;
  10068. while (*argv) {
  10069. if (!(opts & 2)) { /* not -f */
  10070. if (unset_local_var(*argv)) {
  10071. /* unset <nonexistent_var> doesn't fail.
  10072. * Error is when one tries to unset RO var.
  10073. * Message was printed by unset_local_var. */
  10074. ret = EXIT_FAILURE;
  10075. }
  10076. }
  10077. # if ENABLE_HUSH_FUNCTIONS
  10078. else {
  10079. unset_func(*argv);
  10080. }
  10081. # endif
  10082. argv++;
  10083. }
  10084. return ret;
  10085. }
  10086. #endif
  10087. #if ENABLE_HUSH_SET
  10088. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10089. * built-in 'set' handler
  10090. * SUSv3 says:
  10091. * set [-abCefhmnuvx] [-o option] [argument...]
  10092. * set [+abCefhmnuvx] [+o option] [argument...]
  10093. * set -- [argument...]
  10094. * set -o
  10095. * set +o
  10096. * Implementations shall support the options in both their hyphen and
  10097. * plus-sign forms. These options can also be specified as options to sh.
  10098. * Examples:
  10099. * Write out all variables and their values: set
  10100. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10101. * Turn on the -x and -v options: set -xv
  10102. * Unset all positional parameters: set --
  10103. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10104. * Set the positional parameters to the expansion of x, even if x expands
  10105. * with a leading '-' or '+': set -- $x
  10106. *
  10107. * So far, we only support "set -- [argument...]" and some of the short names.
  10108. */
  10109. static int FAST_FUNC builtin_set(char **argv)
  10110. {
  10111. int n;
  10112. char **pp, **g_argv;
  10113. char *arg = *++argv;
  10114. if (arg == NULL) {
  10115. struct variable *e;
  10116. for (e = G.top_var; e; e = e->next)
  10117. puts(e->varstr);
  10118. return EXIT_SUCCESS;
  10119. }
  10120. do {
  10121. if (strcmp(arg, "--") == 0) {
  10122. ++argv;
  10123. goto set_argv;
  10124. }
  10125. if (arg[0] != '+' && arg[0] != '-')
  10126. break;
  10127. for (n = 1; arg[n]; ++n) {
  10128. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  10129. goto error;
  10130. if (arg[n] == 'o' && argv[1])
  10131. argv++;
  10132. }
  10133. } while ((arg = *++argv) != NULL);
  10134. /* Now argv[0] is 1st argument */
  10135. if (arg == NULL)
  10136. return EXIT_SUCCESS;
  10137. set_argv:
  10138. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10139. g_argv = G.global_argv;
  10140. if (G.global_args_malloced) {
  10141. pp = g_argv;
  10142. while (*++pp)
  10143. free(*pp);
  10144. g_argv[1] = NULL;
  10145. } else {
  10146. G.global_args_malloced = 1;
  10147. pp = xzalloc(sizeof(pp[0]) * 2);
  10148. pp[0] = g_argv[0]; /* retain $0 */
  10149. g_argv = pp;
  10150. }
  10151. /* This realloc's G.global_argv */
  10152. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10153. G.global_argc = 1 + string_array_len(pp + 1);
  10154. return EXIT_SUCCESS;
  10155. /* Nothing known, so abort */
  10156. error:
  10157. bb_error_msg("%s: %s: invalid option", "set", arg);
  10158. return EXIT_FAILURE;
  10159. }
  10160. #endif
  10161. static int FAST_FUNC builtin_shift(char **argv)
  10162. {
  10163. int n = 1;
  10164. argv = skip_dash_dash(argv);
  10165. if (argv[0]) {
  10166. n = bb_strtou(argv[0], NULL, 10);
  10167. if (errno || n < 0) {
  10168. /* shared string with ash.c */
  10169. bb_error_msg("Illegal number: %s", argv[0]);
  10170. /*
  10171. * ash aborts in this case.
  10172. * bash prints error message and set $? to 1.
  10173. * Interestingly, for "shift 99999" bash does not
  10174. * print error message, but does set $? to 1
  10175. * (and does no shifting at all).
  10176. */
  10177. }
  10178. }
  10179. if (n >= 0 && n < G.global_argc) {
  10180. if (G_global_args_malloced) {
  10181. int m = 1;
  10182. while (m <= n)
  10183. free(G.global_argv[m++]);
  10184. }
  10185. G.global_argc -= n;
  10186. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10187. G.global_argc * sizeof(G.global_argv[0]));
  10188. return EXIT_SUCCESS;
  10189. }
  10190. return EXIT_FAILURE;
  10191. }
  10192. #if ENABLE_HUSH_GETOPTS
  10193. static int FAST_FUNC builtin_getopts(char **argv)
  10194. {
  10195. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10196. TODO:
  10197. If a required argument is not found, and getopts is not silent,
  10198. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10199. diagnostic message is printed. If getopts is silent, then a
  10200. colon (:) is placed in VAR and OPTARG is set to the option
  10201. character found.
  10202. Test that VAR is a valid variable name?
  10203. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10204. */
  10205. char cbuf[2];
  10206. const char *cp, *optstring, *var;
  10207. int c, n, exitcode, my_opterr;
  10208. unsigned count;
  10209. optstring = *++argv;
  10210. if (!optstring || !(var = *++argv)) {
  10211. bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10212. return EXIT_FAILURE;
  10213. }
  10214. if (argv[1])
  10215. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10216. else
  10217. argv = G.global_argv;
  10218. cbuf[1] = '\0';
  10219. my_opterr = 0;
  10220. if (optstring[0] != ':') {
  10221. cp = get_local_var_value("OPTERR");
  10222. /* 0 if "OPTERR=0", 1 otherwise */
  10223. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10224. }
  10225. /* getopts stops on first non-option. Add "+" to force that */
  10226. /*if (optstring[0] != '+')*/ {
  10227. char *s = alloca(strlen(optstring) + 2);
  10228. sprintf(s, "+%s", optstring);
  10229. optstring = s;
  10230. }
  10231. /* Naively, now we should just
  10232. * cp = get_local_var_value("OPTIND");
  10233. * optind = cp ? atoi(cp) : 0;
  10234. * optarg = NULL;
  10235. * opterr = my_opterr;
  10236. * c = getopt(string_array_len(argv), argv, optstring);
  10237. * and be done? Not so fast...
  10238. * Unlike normal getopt() usage in C programs, here
  10239. * each successive call will (usually) have the same argv[] CONTENTS,
  10240. * but not the ADDRESSES. Worse yet, it's possible that between
  10241. * invocations of "getopts", there will be calls to shell builtins
  10242. * which use getopt() internally. Example:
  10243. * while getopts "abc" RES -a -bc -abc de; do
  10244. * unset -ff func
  10245. * done
  10246. * This would not work correctly: getopt() call inside "unset"
  10247. * modifies internal libc state which is tracking position in
  10248. * multi-option strings ("-abc"). At best, it can skip options
  10249. * or return the same option infinitely. With glibc implementation
  10250. * of getopt(), it would use outright invalid pointers and return
  10251. * garbage even _without_ "unset" mangling internal state.
  10252. *
  10253. * We resort to resetting getopt() state and calling it N times,
  10254. * until we get Nth result (or failure).
  10255. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10256. */
  10257. GETOPT_RESET();
  10258. count = 0;
  10259. n = string_array_len(argv);
  10260. do {
  10261. optarg = NULL;
  10262. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10263. c = getopt(n, argv, optstring);
  10264. if (c < 0)
  10265. break;
  10266. count++;
  10267. } while (count <= G.getopt_count);
  10268. /* Set OPTIND. Prevent resetting of the magic counter! */
  10269. set_local_var_from_halves("OPTIND", utoa(optind));
  10270. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10271. GETOPT_RESET(); /* just in case */
  10272. /* Set OPTARG */
  10273. /* Always set or unset, never left as-is, even on exit/error:
  10274. * "If no option was found, or if the option that was found
  10275. * does not have an option-argument, OPTARG shall be unset."
  10276. */
  10277. cp = optarg;
  10278. if (c == '?') {
  10279. /* If ":optstring" and unknown option is seen,
  10280. * it is stored to OPTARG.
  10281. */
  10282. if (optstring[1] == ':') {
  10283. cbuf[0] = optopt;
  10284. cp = cbuf;
  10285. }
  10286. }
  10287. if (cp)
  10288. set_local_var_from_halves("OPTARG", cp);
  10289. else
  10290. unset_local_var("OPTARG");
  10291. /* Convert -1 to "?" */
  10292. exitcode = EXIT_SUCCESS;
  10293. if (c < 0) { /* -1: end of options */
  10294. exitcode = EXIT_FAILURE;
  10295. c = '?';
  10296. }
  10297. /* Set VAR */
  10298. cbuf[0] = c;
  10299. set_local_var_from_halves(var, cbuf);
  10300. return exitcode;
  10301. }
  10302. #endif
  10303. static int FAST_FUNC builtin_source(char **argv)
  10304. {
  10305. char *arg_path, *filename;
  10306. HFILE *input;
  10307. save_arg_t sv;
  10308. char *args_need_save;
  10309. #if ENABLE_HUSH_FUNCTIONS
  10310. smallint sv_flg;
  10311. #endif
  10312. argv = skip_dash_dash(argv);
  10313. filename = argv[0];
  10314. if (!filename) {
  10315. /* bash says: "bash: .: filename argument required" */
  10316. return 2; /* bash compat */
  10317. }
  10318. arg_path = NULL;
  10319. if (!strchr(filename, '/')) {
  10320. arg_path = find_in_path(filename);
  10321. if (arg_path)
  10322. filename = arg_path;
  10323. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10324. errno = ENOENT;
  10325. bb_simple_perror_msg(filename);
  10326. return EXIT_FAILURE;
  10327. }
  10328. }
  10329. input = hfopen(filename);
  10330. free(arg_path);
  10331. if (!input) {
  10332. bb_perror_msg("%s", filename);
  10333. /* POSIX: non-interactive shell should abort here,
  10334. * not merely fail. So far no one complained :)
  10335. */
  10336. return EXIT_FAILURE;
  10337. }
  10338. #if ENABLE_HUSH_FUNCTIONS
  10339. sv_flg = G_flag_return_in_progress;
  10340. /* "we are inside sourced file, ok to use return" */
  10341. G_flag_return_in_progress = -1;
  10342. #endif
  10343. args_need_save = argv[1]; /* used as a boolean variable */
  10344. if (args_need_save)
  10345. save_and_replace_G_args(&sv, argv);
  10346. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10347. G.last_exitcode = 0;
  10348. parse_and_run_file(input);
  10349. hfclose(input);
  10350. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10351. restore_G_args(&sv, argv);
  10352. #if ENABLE_HUSH_FUNCTIONS
  10353. G_flag_return_in_progress = sv_flg;
  10354. #endif
  10355. return G.last_exitcode;
  10356. }
  10357. #if ENABLE_HUSH_TRAP
  10358. static int FAST_FUNC builtin_trap(char **argv)
  10359. {
  10360. int sig;
  10361. char *new_cmd;
  10362. if (!G_traps)
  10363. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10364. argv++;
  10365. if (!*argv) {
  10366. int i;
  10367. /* No args: print all trapped */
  10368. for (i = 0; i < NSIG; ++i) {
  10369. if (G_traps[i]) {
  10370. printf("trap -- ");
  10371. print_escaped(G_traps[i]);
  10372. /* note: bash adds "SIG", but only if invoked
  10373. * as "bash". If called as "sh", or if set -o posix,
  10374. * then it prints short signal names.
  10375. * We are printing short names: */
  10376. printf(" %s\n", get_signame(i));
  10377. }
  10378. }
  10379. /*fflush_all(); - done after each builtin anyway */
  10380. return EXIT_SUCCESS;
  10381. }
  10382. new_cmd = NULL;
  10383. /* If first arg is a number: reset all specified signals */
  10384. sig = bb_strtou(*argv, NULL, 10);
  10385. if (errno == 0) {
  10386. int ret;
  10387. process_sig_list:
  10388. ret = EXIT_SUCCESS;
  10389. while (*argv) {
  10390. sighandler_t handler;
  10391. sig = get_signum(*argv++);
  10392. if (sig < 0) {
  10393. ret = EXIT_FAILURE;
  10394. /* Mimic bash message exactly */
  10395. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10396. continue;
  10397. }
  10398. free(G_traps[sig]);
  10399. G_traps[sig] = xstrdup(new_cmd);
  10400. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10401. get_signame(sig), sig, G_traps[sig]);
  10402. /* There is no signal for 0 (EXIT) */
  10403. if (sig == 0)
  10404. continue;
  10405. if (new_cmd)
  10406. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10407. else
  10408. /* We are removing trap handler */
  10409. handler = pick_sighandler(sig);
  10410. install_sighandler(sig, handler);
  10411. }
  10412. return ret;
  10413. }
  10414. if (!argv[1]) { /* no second arg */
  10415. bb_error_msg("trap: invalid arguments");
  10416. return EXIT_FAILURE;
  10417. }
  10418. /* First arg is "-": reset all specified to default */
  10419. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10420. /* Everything else: set arg as signal handler
  10421. * (includes "" case, which ignores signal) */
  10422. if (argv[0][0] == '-') {
  10423. if (argv[0][1] == '\0') { /* "-" */
  10424. /* new_cmd remains NULL: "reset these sigs" */
  10425. goto reset_traps;
  10426. }
  10427. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10428. argv++;
  10429. }
  10430. /* else: "-something", no special meaning */
  10431. }
  10432. new_cmd = *argv;
  10433. reset_traps:
  10434. argv++;
  10435. goto process_sig_list;
  10436. }
  10437. #endif
  10438. #if ENABLE_HUSH_JOB
  10439. static struct pipe *parse_jobspec(const char *str)
  10440. {
  10441. struct pipe *pi;
  10442. unsigned jobnum;
  10443. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10444. if (str[0] != '%'
  10445. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10446. ) {
  10447. bb_error_msg("bad argument '%s'", str);
  10448. return NULL;
  10449. }
  10450. /* It is "%%", "%+" or "%" - current job */
  10451. jobnum = G.last_jobid;
  10452. if (jobnum == 0) {
  10453. bb_error_msg("no current job");
  10454. return NULL;
  10455. }
  10456. }
  10457. for (pi = G.job_list; pi; pi = pi->next) {
  10458. if (pi->jobid == jobnum) {
  10459. return pi;
  10460. }
  10461. }
  10462. bb_error_msg("%u: no such job", jobnum);
  10463. return NULL;
  10464. }
  10465. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10466. {
  10467. struct pipe *job;
  10468. const char *status_string;
  10469. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10470. for (job = G.job_list; job; job = job->next) {
  10471. if (job->alive_cmds == job->stopped_cmds)
  10472. status_string = "Stopped";
  10473. else
  10474. status_string = "Running";
  10475. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10476. }
  10477. clean_up_last_dead_job();
  10478. return EXIT_SUCCESS;
  10479. }
  10480. /* built-in 'fg' and 'bg' handler */
  10481. static int FAST_FUNC builtin_fg_bg(char **argv)
  10482. {
  10483. int i;
  10484. struct pipe *pi;
  10485. if (!G_interactive_fd)
  10486. return EXIT_FAILURE;
  10487. /* If they gave us no args, assume they want the last backgrounded task */
  10488. if (!argv[1]) {
  10489. for (pi = G.job_list; pi; pi = pi->next) {
  10490. if (pi->jobid == G.last_jobid) {
  10491. goto found;
  10492. }
  10493. }
  10494. bb_error_msg("%s: no current job", argv[0]);
  10495. return EXIT_FAILURE;
  10496. }
  10497. pi = parse_jobspec(argv[1]);
  10498. if (!pi)
  10499. return EXIT_FAILURE;
  10500. found:
  10501. /* TODO: bash prints a string representation
  10502. * of job being foregrounded (like "sleep 1 | cat") */
  10503. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10504. /* Put the job into the foreground. */
  10505. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10506. }
  10507. /* Restart the processes in the job */
  10508. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10509. for (i = 0; i < pi->num_cmds; i++) {
  10510. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10511. }
  10512. pi->stopped_cmds = 0;
  10513. i = kill(- pi->pgrp, SIGCONT);
  10514. if (i < 0) {
  10515. if (errno == ESRCH) {
  10516. delete_finished_job(pi);
  10517. return EXIT_SUCCESS;
  10518. }
  10519. bb_perror_msg("kill (SIGCONT)");
  10520. }
  10521. if (argv[0][0] == 'f') {
  10522. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10523. return checkjobs_and_fg_shell(pi);
  10524. }
  10525. return EXIT_SUCCESS;
  10526. }
  10527. #endif
  10528. #if ENABLE_HUSH_KILL
  10529. static int FAST_FUNC builtin_kill(char **argv)
  10530. {
  10531. int ret = 0;
  10532. # if ENABLE_HUSH_JOB
  10533. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10534. int i = 1;
  10535. do {
  10536. struct pipe *pi;
  10537. char *dst;
  10538. int j, n;
  10539. if (argv[i][0] != '%')
  10540. continue;
  10541. /*
  10542. * "kill %N" - job kill
  10543. * Converting to pgrp / pid kill
  10544. */
  10545. pi = parse_jobspec(argv[i]);
  10546. if (!pi) {
  10547. /* Eat bad jobspec */
  10548. j = i;
  10549. do {
  10550. j++;
  10551. argv[j - 1] = argv[j];
  10552. } while (argv[j]);
  10553. ret = 1;
  10554. i--;
  10555. continue;
  10556. }
  10557. /*
  10558. * In jobs started under job control, we signal
  10559. * entire process group by kill -PGRP_ID.
  10560. * This happens, f.e., in interactive shell.
  10561. *
  10562. * Otherwise, we signal each child via
  10563. * kill PID1 PID2 PID3.
  10564. * Testcases:
  10565. * sh -c 'sleep 1|sleep 1 & kill %1'
  10566. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10567. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10568. */
  10569. n = G_interactive_fd ? 1 : pi->num_cmds;
  10570. dst = alloca(n * sizeof(int)*4);
  10571. argv[i] = dst;
  10572. if (G_interactive_fd)
  10573. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10574. else for (j = 0; j < n; j++) {
  10575. struct command *cmd = &pi->cmds[j];
  10576. /* Skip exited members of the job */
  10577. if (cmd->pid == 0)
  10578. continue;
  10579. /*
  10580. * kill_main has matching code to expect
  10581. * leading space. Needed to not confuse
  10582. * negative pids with "kill -SIGNAL_NO" syntax
  10583. */
  10584. dst += sprintf(dst, " %u", (int)cmd->pid);
  10585. }
  10586. *dst = '\0';
  10587. } while (argv[++i]);
  10588. }
  10589. # endif
  10590. if (argv[1] || ret == 0) {
  10591. ret = run_applet_main(argv, kill_main);
  10592. }
  10593. /* else: ret = 1, "kill %bad_jobspec" case */
  10594. return ret;
  10595. }
  10596. #endif
  10597. #if ENABLE_HUSH_WAIT
  10598. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10599. #if !ENABLE_HUSH_JOB
  10600. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10601. #endif
  10602. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10603. {
  10604. int ret = 0;
  10605. for (;;) {
  10606. int sig;
  10607. sigset_t oldset;
  10608. if (!sigisemptyset(&G.pending_set))
  10609. goto check_sig;
  10610. /* waitpid is not interruptible by SA_RESTARTed
  10611. * signals which we use. Thus, this ugly dance:
  10612. */
  10613. /* Make sure possible SIGCHLD is stored in kernel's
  10614. * pending signal mask before we call waitpid.
  10615. * Or else we may race with SIGCHLD, lose it,
  10616. * and get stuck in sigsuspend...
  10617. */
  10618. sigfillset(&oldset); /* block all signals, remember old set */
  10619. sigprocmask(SIG_SETMASK, &oldset, &oldset);
  10620. if (!sigisemptyset(&G.pending_set)) {
  10621. /* Crap! we raced with some signal! */
  10622. goto restore;
  10623. }
  10624. /*errno = 0; - checkjobs does this */
  10625. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10626. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10627. debug_printf_exec("checkjobs:%d\n", ret);
  10628. #if ENABLE_HUSH_JOB
  10629. if (waitfor_pipe) {
  10630. int rcode = job_exited_or_stopped(waitfor_pipe);
  10631. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10632. if (rcode >= 0) {
  10633. ret = rcode;
  10634. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10635. break;
  10636. }
  10637. }
  10638. #endif
  10639. /* if ECHILD, there are no children (ret is -1 or 0) */
  10640. /* if ret == 0, no children changed state */
  10641. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10642. if (errno == ECHILD || ret) {
  10643. ret--;
  10644. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10645. ret = 0;
  10646. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10647. break;
  10648. }
  10649. /* Wait for SIGCHLD or any other signal */
  10650. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10651. /* Note: sigsuspend invokes signal handler */
  10652. sigsuspend(&oldset);
  10653. restore:
  10654. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10655. check_sig:
  10656. /* So, did we get a signal? */
  10657. sig = check_and_run_traps();
  10658. if (sig /*&& sig != SIGCHLD - always true */) {
  10659. /* Do this for any (non-ignored) signal, not only for ^C */
  10660. ret = 128 + sig;
  10661. break;
  10662. }
  10663. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10664. }
  10665. return ret;
  10666. }
  10667. static int FAST_FUNC builtin_wait(char **argv)
  10668. {
  10669. int ret;
  10670. int status;
  10671. argv = skip_dash_dash(argv);
  10672. if (argv[0] == NULL) {
  10673. /* Don't care about wait results */
  10674. /* Note 1: must wait until there are no more children */
  10675. /* Note 2: must be interruptible */
  10676. /* Examples:
  10677. * $ sleep 3 & sleep 6 & wait
  10678. * [1] 30934 sleep 3
  10679. * [2] 30935 sleep 6
  10680. * [1] Done sleep 3
  10681. * [2] Done sleep 6
  10682. * $ sleep 3 & sleep 6 & wait
  10683. * [1] 30936 sleep 3
  10684. * [2] 30937 sleep 6
  10685. * [1] Done sleep 3
  10686. * ^C <-- after ~4 sec from keyboard
  10687. * $
  10688. */
  10689. return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
  10690. }
  10691. do {
  10692. pid_t pid = bb_strtou(*argv, NULL, 10);
  10693. if (errno || pid <= 0) {
  10694. #if ENABLE_HUSH_JOB
  10695. if (argv[0][0] == '%') {
  10696. struct pipe *wait_pipe;
  10697. ret = 127; /* bash compat for bad jobspecs */
  10698. wait_pipe = parse_jobspec(*argv);
  10699. if (wait_pipe) {
  10700. ret = job_exited_or_stopped(wait_pipe);
  10701. if (ret < 0) {
  10702. ret = wait_for_child_or_signal(wait_pipe, 0);
  10703. } else {
  10704. /* waiting on "last dead job" removes it */
  10705. clean_up_last_dead_job();
  10706. }
  10707. }
  10708. /* else: parse_jobspec() already emitted error msg */
  10709. continue;
  10710. }
  10711. #endif
  10712. /* mimic bash message */
  10713. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10714. ret = EXIT_FAILURE;
  10715. continue; /* bash checks all argv[] */
  10716. }
  10717. /* Do we have such child? */
  10718. ret = waitpid(pid, &status, WNOHANG);
  10719. if (ret < 0) {
  10720. /* No */
  10721. ret = 127;
  10722. if (errno == ECHILD) {
  10723. if (pid == G.last_bg_pid) {
  10724. /* "wait $!" but last bg task has already exited. Try:
  10725. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10726. * In bash it prints exitcode 0, then 3.
  10727. * In dash, it is 127.
  10728. */
  10729. ret = G.last_bg_pid_exitcode;
  10730. } else {
  10731. /* Example: "wait 1". mimic bash message */
  10732. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10733. }
  10734. } else {
  10735. /* ??? */
  10736. bb_perror_msg("wait %s", *argv);
  10737. }
  10738. continue; /* bash checks all argv[] */
  10739. }
  10740. if (ret == 0) {
  10741. /* Yes, and it still runs */
  10742. ret = wait_for_child_or_signal(NULL, pid);
  10743. } else {
  10744. /* Yes, and it just exited */
  10745. process_wait_result(NULL, pid, status);
  10746. ret = WEXITSTATUS(status);
  10747. if (WIFSIGNALED(status))
  10748. ret = 128 + WTERMSIG(status);
  10749. }
  10750. } while (*++argv);
  10751. return ret;
  10752. }
  10753. #endif
  10754. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10755. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10756. {
  10757. if (argv[1]) {
  10758. def = bb_strtou(argv[1], NULL, 10);
  10759. if (errno || def < def_min || argv[2]) {
  10760. bb_error_msg("%s: bad arguments", argv[0]);
  10761. def = UINT_MAX;
  10762. }
  10763. }
  10764. return def;
  10765. }
  10766. #endif
  10767. #if ENABLE_HUSH_LOOPS
  10768. static int FAST_FUNC builtin_break(char **argv)
  10769. {
  10770. unsigned depth;
  10771. if (G.depth_of_loop == 0) {
  10772. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10773. /* if we came from builtin_continue(), need to undo "= 1" */
  10774. G.flag_break_continue = 0;
  10775. return EXIT_SUCCESS; /* bash compat */
  10776. }
  10777. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10778. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10779. if (depth == UINT_MAX)
  10780. G.flag_break_continue = BC_BREAK;
  10781. if (G.depth_of_loop < depth)
  10782. G.depth_break_continue = G.depth_of_loop;
  10783. return EXIT_SUCCESS;
  10784. }
  10785. static int FAST_FUNC builtin_continue(char **argv)
  10786. {
  10787. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10788. return builtin_break(argv);
  10789. }
  10790. #endif
  10791. #if ENABLE_HUSH_FUNCTIONS
  10792. static int FAST_FUNC builtin_return(char **argv)
  10793. {
  10794. int rc;
  10795. if (G_flag_return_in_progress != -1) {
  10796. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10797. return EXIT_FAILURE; /* bash compat */
  10798. }
  10799. G_flag_return_in_progress = 1;
  10800. /* bash:
  10801. * out of range: wraps around at 256, does not error out
  10802. * non-numeric param:
  10803. * f() { false; return qwe; }; f; echo $?
  10804. * bash: return: qwe: numeric argument required <== we do this
  10805. * 255 <== we also do this
  10806. */
  10807. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10808. return rc;
  10809. }
  10810. #endif
  10811. #if ENABLE_HUSH_TIMES
  10812. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10813. {
  10814. static const uint8_t times_tbl[] ALIGN1 = {
  10815. ' ', offsetof(struct tms, tms_utime),
  10816. '\n', offsetof(struct tms, tms_stime),
  10817. ' ', offsetof(struct tms, tms_cutime),
  10818. '\n', offsetof(struct tms, tms_cstime),
  10819. 0
  10820. };
  10821. const uint8_t *p;
  10822. unsigned clk_tck;
  10823. struct tms buf;
  10824. clk_tck = bb_clk_tck();
  10825. times(&buf);
  10826. p = times_tbl;
  10827. do {
  10828. unsigned sec, frac;
  10829. unsigned long t;
  10830. t = *(clock_t *)(((char *) &buf) + p[1]);
  10831. sec = t / clk_tck;
  10832. frac = t % clk_tck;
  10833. printf("%um%u.%03us%c",
  10834. sec / 60, sec % 60,
  10835. (frac * 1000) / clk_tck,
  10836. p[0]);
  10837. p += 2;
  10838. } while (*p);
  10839. return EXIT_SUCCESS;
  10840. }
  10841. #endif
  10842. #if ENABLE_HUSH_MEMLEAK
  10843. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10844. {
  10845. void *p;
  10846. unsigned long l;
  10847. # ifdef M_TRIM_THRESHOLD
  10848. /* Optional. Reduces probability of false positives */
  10849. malloc_trim(0);
  10850. # endif
  10851. /* Crude attempt to find where "free memory" starts,
  10852. * sans fragmentation. */
  10853. p = malloc(240);
  10854. l = (unsigned long)p;
  10855. free(p);
  10856. p = malloc(3400);
  10857. if (l < (unsigned long)p) l = (unsigned long)p;
  10858. free(p);
  10859. # if 0 /* debug */
  10860. {
  10861. struct mallinfo mi = mallinfo();
  10862. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10863. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10864. }
  10865. # endif
  10866. if (!G.memleak_value)
  10867. G.memleak_value = l;
  10868. l -= G.memleak_value;
  10869. if ((long)l < 0)
  10870. l = 0;
  10871. l /= 1024;
  10872. if (l > 127)
  10873. l = 127;
  10874. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10875. return l;
  10876. }
  10877. #endif