hush.c 336 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200
  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. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (68 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_BASH_SOURCE_CURDIR
  131. //config: bool "'source' and '.' builtins search current directory after $PATH"
  132. //config: default n # do not encourage non-standard behavior
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config: help
  135. //config: This is not compliant with standards. Avoid if possible.
  136. //config:
  137. //config:config HUSH_LINENO_VAR
  138. //config: bool "$LINENO variable (bashism)"
  139. //config: default y
  140. //config: depends on SHELL_HUSH
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !ENABLE_SHELL_ASH
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  383. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  384. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  385. /* Build knobs */
  386. #define LEAK_HUNTING 0
  387. #define BUILD_AS_NOMMU 0
  388. /* Enable/disable sanity checks. Ok to enable in production,
  389. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  390. * Keeping 1 for now even in released versions.
  391. */
  392. #define HUSH_DEBUG 1
  393. /* Slightly bigger (+200 bytes), but faster hush.
  394. * So far it only enables a trick with counting SIGCHLDs and forks,
  395. * which allows us to do fewer waitpid's.
  396. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  397. * and therefore waitpid will return the same result as last time)
  398. */
  399. #define ENABLE_HUSH_FAST 0
  400. /* TODO: implement simplified code for users which do not need ${var%...} ops
  401. * So far ${var%...} ops are always enabled:
  402. */
  403. #define ENABLE_HUSH_DOLLAR_OPS 1
  404. #if BUILD_AS_NOMMU
  405. # undef BB_MMU
  406. # undef USE_FOR_NOMMU
  407. # undef USE_FOR_MMU
  408. # define BB_MMU 0
  409. # define USE_FOR_NOMMU(...) __VA_ARGS__
  410. # define USE_FOR_MMU(...)
  411. #endif
  412. #include "NUM_APPLETS.h"
  413. #if NUM_APPLETS == 1
  414. /* STANDALONE does not make sense, and won't compile */
  415. # undef CONFIG_FEATURE_SH_STANDALONE
  416. # undef ENABLE_FEATURE_SH_STANDALONE
  417. # undef IF_FEATURE_SH_STANDALONE
  418. # undef IF_NOT_FEATURE_SH_STANDALONE
  419. # define ENABLE_FEATURE_SH_STANDALONE 0
  420. # define IF_FEATURE_SH_STANDALONE(...)
  421. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  422. #endif
  423. #if !ENABLE_HUSH_INTERACTIVE
  424. # undef ENABLE_FEATURE_EDITING
  425. # define ENABLE_FEATURE_EDITING 0
  426. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  427. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  428. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  429. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  430. #endif
  431. /* Do we support ANY keywords? */
  432. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  433. # define HAS_KEYWORDS 1
  434. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  435. # define IF_HAS_NO_KEYWORDS(...)
  436. #else
  437. # define HAS_KEYWORDS 0
  438. # define IF_HAS_KEYWORDS(...)
  439. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  440. #endif
  441. /* If you comment out one of these below, it will be #defined later
  442. * to perform debug printfs to stderr: */
  443. #define debug_printf(...) do {} while (0)
  444. /* Finer-grained debug switches */
  445. #define debug_printf_parse(...) do {} while (0)
  446. #define debug_printf_heredoc(...) do {} while (0)
  447. #define debug_print_tree(a, b) do {} while (0)
  448. #define debug_printf_exec(...) do {} while (0)
  449. #define debug_printf_env(...) do {} while (0)
  450. #define debug_printf_jobs(...) do {} while (0)
  451. #define debug_printf_expand(...) do {} while (0)
  452. #define debug_printf_varexp(...) do {} while (0)
  453. #define debug_printf_glob(...) do {} while (0)
  454. #define debug_printf_redir(...) do {} while (0)
  455. #define debug_printf_list(...) do {} while (0)
  456. #define debug_printf_subst(...) do {} while (0)
  457. #define debug_printf_prompt(...) do {} while (0)
  458. #define debug_printf_clean(...) do {} while (0)
  459. #define ERR_PTR ((void*)(long)1)
  460. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  461. #define _SPECIAL_VARS_STR "_*@$!?#-"
  462. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  463. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  464. #if BASH_PATTERN_SUBST
  465. /* Support / and // replace ops */
  466. /* Note that // is stored as \ in "encoded" string representation */
  467. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  468. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  469. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  470. #else
  471. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  472. # define VAR_SUBST_OPS "%#:-=+?"
  473. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  474. #endif
  475. #define SPECIAL_VAR_SYMBOL_STR "\3"
  476. #define SPECIAL_VAR_SYMBOL 3
  477. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  478. #define SPECIAL_VAR_QUOTED_SVS 1
  479. struct variable;
  480. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  481. /* This supports saving pointers malloced in vfork child,
  482. * to be freed in the parent.
  483. */
  484. #if !BB_MMU
  485. typedef struct nommu_save_t {
  486. struct variable *old_vars;
  487. char **argv;
  488. char **argv_from_re_execing;
  489. } nommu_save_t;
  490. #endif
  491. enum {
  492. RES_NONE = 0,
  493. #if ENABLE_HUSH_IF
  494. RES_IF ,
  495. RES_THEN ,
  496. RES_ELIF ,
  497. RES_ELSE ,
  498. RES_FI ,
  499. #endif
  500. #if ENABLE_HUSH_LOOPS
  501. RES_FOR ,
  502. RES_WHILE ,
  503. RES_UNTIL ,
  504. RES_DO ,
  505. RES_DONE ,
  506. #endif
  507. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  508. RES_IN ,
  509. #endif
  510. #if ENABLE_HUSH_CASE
  511. RES_CASE ,
  512. /* three pseudo-keywords support contrived "case" syntax: */
  513. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  514. RES_MATCH , /* "word)" */
  515. RES_CASE_BODY, /* "this command is inside CASE" */
  516. RES_ESAC ,
  517. #endif
  518. RES_XXXX ,
  519. RES_SNTX
  520. };
  521. typedef struct o_string {
  522. char *data;
  523. int length; /* position where data is appended */
  524. int maxlen;
  525. int o_expflags;
  526. /* At least some part of the string was inside '' or "",
  527. * possibly empty one: word"", wo''rd etc. */
  528. smallint has_quoted_part;
  529. smallint has_empty_slot;
  530. smallint ended_in_ifs;
  531. } o_string;
  532. enum {
  533. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  534. EXP_FLAG_GLOB = 0x2,
  535. /* Protect newly added chars against globbing
  536. * by prepending \ to *, ?, [, \ */
  537. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  538. };
  539. /* Used for initialization: o_string foo = NULL_O_STRING; */
  540. #define NULL_O_STRING { NULL }
  541. #ifndef debug_printf_parse
  542. static const char *const assignment_flag[] = {
  543. "MAYBE_ASSIGNMENT",
  544. "DEFINITELY_ASSIGNMENT",
  545. "NOT_ASSIGNMENT",
  546. "WORD_IS_KEYWORD",
  547. };
  548. #endif
  549. /* We almost can use standard FILE api, but we need an ability to move
  550. * its fd when redirects coincide with it. No api exists for that
  551. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  552. * HFILE is our internal alternative. Only supports reading.
  553. * Since we now can, we incorporate linked list of all opened HFILEs
  554. * into the struct (used to be a separate mini-list).
  555. */
  556. typedef struct HFILE {
  557. char *cur;
  558. char *end;
  559. struct HFILE *next_hfile;
  560. int fd;
  561. char buf[1024];
  562. } HFILE;
  563. typedef struct in_str {
  564. const char *p;
  565. int peek_buf[2];
  566. int last_char;
  567. HFILE *file;
  568. } in_str;
  569. /* The descrip member of this structure is only used to make
  570. * debugging output pretty */
  571. static const struct {
  572. int32_t mode;
  573. signed char default_fd;
  574. char descrip[3];
  575. } redir_table[] ALIGN4 = {
  576. { O_RDONLY, 0, "<" },
  577. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  578. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  579. { O_CREAT|O_RDWR, 1, "<>" },
  580. { O_RDONLY, 0, "<<" },
  581. /* Should not be needed. Bogus default_fd helps in debugging */
  582. /* { O_RDONLY, 77, "<<" }, */
  583. };
  584. struct redir_struct {
  585. struct redir_struct *next;
  586. char *rd_filename; /* filename */
  587. int rd_fd; /* fd to redirect */
  588. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  589. int rd_dup;
  590. smallint rd_type; /* (enum redir_type) */
  591. /* note: for heredocs, rd_filename contains heredoc delimiter,
  592. * and subsequently heredoc itself; and rd_dup is a bitmask:
  593. * bit 0: do we need to trim leading tabs?
  594. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  595. */
  596. };
  597. typedef enum redir_type {
  598. REDIRECT_INPUT = 0,
  599. REDIRECT_OVERWRITE = 1,
  600. REDIRECT_APPEND = 2,
  601. REDIRECT_IO = 3,
  602. REDIRECT_HEREDOC = 4,
  603. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  604. REDIRFD_CLOSE = -3,
  605. REDIRFD_SYNTAX_ERR = -2,
  606. REDIRFD_TO_FILE = -1,
  607. /* otherwise, rd_fd is redirected to rd_dup */
  608. HEREDOC_SKIPTABS = 1,
  609. HEREDOC_QUOTED = 2,
  610. } redir_type;
  611. struct command {
  612. pid_t pid; /* 0 if exited */
  613. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  614. #if ENABLE_HUSH_LINENO_VAR
  615. unsigned lineno;
  616. #endif
  617. smallint cmd_type; /* CMD_xxx */
  618. #define CMD_NORMAL 0
  619. #define CMD_SUBSHELL 1
  620. #if BASH_TEST2
  621. /* used for "[[ EXPR ]]" */
  622. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  623. #endif
  624. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  625. /* used to prevent word splitting and globbing in "export v=t*" */
  626. # define CMD_SINGLEWORD_NOGLOB 3
  627. #endif
  628. #if ENABLE_HUSH_FUNCTIONS
  629. # define CMD_FUNCDEF 4
  630. #endif
  631. smalluint cmd_exitcode;
  632. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  633. struct pipe *group;
  634. #if !BB_MMU
  635. char *group_as_string;
  636. #endif
  637. #if ENABLE_HUSH_FUNCTIONS
  638. struct function *child_func;
  639. /* This field is used to prevent a bug here:
  640. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  641. * When we execute "f1() {a;}" cmd, we create new function and clear
  642. * cmd->group, cmd->group_as_string, cmd->argv[0].
  643. * When we execute "f1() {b;}", we notice that f1 exists,
  644. * and that its "parent cmd" struct is still "alive",
  645. * we put those fields back into cmd->xxx
  646. * (struct function has ->parent_cmd ptr to facilitate that).
  647. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  648. * Without this trick, loop would execute a;b;b;b;...
  649. * instead of correct sequence a;b;a;b;...
  650. * When command is freed, it severs the link
  651. * (sets ->child_func->parent_cmd to NULL).
  652. */
  653. #endif
  654. char **argv; /* command name and arguments */
  655. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  656. * and on execution these are substituted with their values.
  657. * Substitution can make _several_ words out of one argv[n]!
  658. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  659. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  660. */
  661. struct redir_struct *redirects; /* I/O redirections */
  662. };
  663. /* Is there anything in this command at all? */
  664. #define IS_NULL_CMD(cmd) \
  665. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  666. struct pipe {
  667. struct pipe *next;
  668. int num_cmds; /* total number of commands in pipe */
  669. int alive_cmds; /* number of commands running (not exited) */
  670. int stopped_cmds; /* number of commands alive, but stopped */
  671. #if ENABLE_HUSH_JOB
  672. unsigned jobid; /* job number */
  673. pid_t pgrp; /* process group ID for the job */
  674. char *cmdtext; /* name of job */
  675. #endif
  676. struct command *cmds; /* array of commands in pipe */
  677. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  678. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  679. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  680. };
  681. typedef enum pipe_style {
  682. PIPE_SEQ = 0,
  683. PIPE_AND = 1,
  684. PIPE_OR = 2,
  685. PIPE_BG = 3,
  686. } pipe_style;
  687. /* Is there anything in this pipe at all? */
  688. #define IS_NULL_PIPE(pi) \
  689. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  690. /* This holds pointers to the various results of parsing */
  691. struct parse_context {
  692. /* linked list of pipes */
  693. struct pipe *list_head;
  694. /* last pipe (being constructed right now) */
  695. struct pipe *pipe;
  696. /* last command in pipe (being constructed right now) */
  697. struct command *command;
  698. /* last redirect in command->redirects list */
  699. struct redir_struct *pending_redirect;
  700. o_string word;
  701. #if !BB_MMU
  702. o_string as_string;
  703. #endif
  704. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  705. #if HAS_KEYWORDS
  706. smallint ctx_res_w;
  707. smallint ctx_inverted; /* "! cmd | cmd" */
  708. #if ENABLE_HUSH_CASE
  709. smallint ctx_dsemicolon; /* ";;" seen */
  710. #endif
  711. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  712. int old_flag;
  713. /* group we are enclosed in:
  714. * example: "if pipe1; pipe2; then pipe3; fi"
  715. * when we see "if" or "then", we malloc and copy current context,
  716. * and make ->stack point to it. then we parse pipeN.
  717. * when closing "then" / fi" / whatever is found,
  718. * we move list_head into ->stack->command->group,
  719. * copy ->stack into current context, and delete ->stack.
  720. * (parsing of { list } and ( list ) doesn't use this method)
  721. */
  722. struct parse_context *stack;
  723. #endif
  724. };
  725. enum {
  726. MAYBE_ASSIGNMENT = 0,
  727. DEFINITELY_ASSIGNMENT = 1,
  728. NOT_ASSIGNMENT = 2,
  729. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  730. WORD_IS_KEYWORD = 3,
  731. };
  732. /* On program start, environ points to initial environment.
  733. * putenv adds new pointers into it, unsetenv removes them.
  734. * Neither of these (de)allocates the strings.
  735. * setenv allocates new strings in malloc space and does putenv,
  736. * and thus setenv is unusable (leaky) for shell's purposes */
  737. #define setenv(...) setenv_is_leaky_dont_use()
  738. struct variable {
  739. struct variable *next;
  740. char *varstr; /* points to "name=" portion */
  741. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  742. uint16_t var_nest_level;
  743. smallint flg_export; /* putenv should be done on this var */
  744. smallint flg_read_only;
  745. };
  746. enum {
  747. BC_BREAK = 1,
  748. BC_CONTINUE = 2,
  749. };
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function {
  752. struct function *next;
  753. char *name;
  754. struct command *parent_cmd;
  755. struct pipe *body;
  756. # if !BB_MMU
  757. char *body_as_string;
  758. # endif
  759. };
  760. #endif
  761. /* set -/+o OPT support. (TODO: make it optional)
  762. * bash supports the following opts:
  763. * allexport off
  764. * braceexpand on
  765. * emacs on
  766. * errexit off
  767. * errtrace off
  768. * functrace off
  769. * hashall on
  770. * histexpand off
  771. * history on
  772. * ignoreeof off
  773. * interactive-comments on
  774. * keyword off
  775. * monitor on
  776. * noclobber off
  777. * noexec off
  778. * noglob off
  779. * nolog off
  780. * notify off
  781. * nounset off
  782. * onecmd off
  783. * physical off
  784. * pipefail off
  785. * posix off
  786. * privileged off
  787. * verbose off
  788. * vi off
  789. * xtrace off
  790. */
  791. static const char o_opt_strings[] ALIGN1 =
  792. "pipefail\0"
  793. "noexec\0"
  794. "errexit\0"
  795. #if ENABLE_HUSH_MODE_X
  796. "xtrace\0"
  797. #endif
  798. ;
  799. enum {
  800. OPT_O_PIPEFAIL,
  801. OPT_O_NOEXEC,
  802. OPT_O_ERREXIT,
  803. #if ENABLE_HUSH_MODE_X
  804. OPT_O_XTRACE,
  805. #endif
  806. NUM_OPT_O
  807. };
  808. /* "Globals" within this file */
  809. /* Sorted roughly by size (smaller offsets == smaller code) */
  810. struct globals {
  811. /* interactive_fd != 0 means we are an interactive shell.
  812. * If we are, then saved_tty_pgrp can also be != 0, meaning
  813. * that controlling tty is available. With saved_tty_pgrp == 0,
  814. * job control still works, but terminal signals
  815. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  816. * process groups can only be created with "cmd &".
  817. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  818. * to give tty to the foreground process group,
  819. * and will take it back when the group is stopped (^Z)
  820. * or killed (^C).
  821. */
  822. #if ENABLE_HUSH_INTERACTIVE
  823. /* 'interactive_fd' is a fd# open to ctty, if we have one
  824. * _AND_ if we decided to act interactively */
  825. int interactive_fd;
  826. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  827. # define G_interactive_fd (G.interactive_fd)
  828. #else
  829. # define G_interactive_fd 0
  830. #endif
  831. #if ENABLE_FEATURE_EDITING
  832. line_input_t *line_input_state;
  833. #endif
  834. pid_t root_pid;
  835. pid_t root_ppid;
  836. pid_t last_bg_pid;
  837. #if ENABLE_HUSH_RANDOM_SUPPORT
  838. random_t random_gen;
  839. #endif
  840. #if ENABLE_HUSH_JOB
  841. int run_list_level;
  842. unsigned last_jobid;
  843. pid_t saved_tty_pgrp;
  844. struct pipe *job_list;
  845. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  846. #else
  847. # define G_saved_tty_pgrp 0
  848. #endif
  849. /* How deeply are we in context where "set -e" is ignored */
  850. int errexit_depth;
  851. /* "set -e" rules (do we follow them correctly?):
  852. * Exit if pipe, list, or compound command exits with a non-zero status.
  853. * Shell does not exit if failed command is part of condition in
  854. * if/while, part of && or || list except the last command, any command
  855. * in a pipe but the last, or if the command's return value is being
  856. * inverted with !. If a compound command other than a subshell returns a
  857. * non-zero status because a command failed while -e was being ignored, the
  858. * shell does not exit. A trap on ERR, if set, is executed before the shell
  859. * exits [ERR is a bashism].
  860. *
  861. * If a compound command or function executes in a context where -e is
  862. * ignored, none of the commands executed within are affected by the -e
  863. * setting. If a compound command or function sets -e while executing in a
  864. * context where -e is ignored, that setting does not have any effect until
  865. * the compound command or the command containing the function call completes.
  866. */
  867. char o_opt[NUM_OPT_O];
  868. #if ENABLE_HUSH_MODE_X
  869. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  870. #else
  871. # define G_x_mode 0
  872. #endif
  873. char opt_s;
  874. char opt_c;
  875. #if ENABLE_HUSH_INTERACTIVE
  876. smallint promptmode; /* 0: PS1, 1: PS2 */
  877. #endif
  878. smallint flag_SIGINT;
  879. #if ENABLE_HUSH_LOOPS
  880. smallint flag_break_continue;
  881. #endif
  882. #if ENABLE_HUSH_FUNCTIONS
  883. /* 0: outside of a function (or sourced file)
  884. * -1: inside of a function, ok to use return builtin
  885. * 1: return is invoked, skip all till end of func
  886. */
  887. smallint flag_return_in_progress;
  888. # define G_flag_return_in_progress (G.flag_return_in_progress)
  889. #else
  890. # define G_flag_return_in_progress 0
  891. #endif
  892. smallint exiting; /* used to prevent EXIT trap recursion */
  893. /* These support $? */
  894. smalluint last_exitcode;
  895. smalluint expand_exitcode;
  896. smalluint last_bg_pid_exitcode;
  897. #if ENABLE_HUSH_SET
  898. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  899. smalluint global_args_malloced;
  900. # define G_global_args_malloced (G.global_args_malloced)
  901. #else
  902. # define G_global_args_malloced 0
  903. #endif
  904. #if ENABLE_HUSH_BASH_COMPAT
  905. int dead_job_exitcode; /* for "wait -n" */
  906. #endif
  907. /* how many non-NULL argv's we have. NB: $# + 1 */
  908. int global_argc;
  909. char **global_argv;
  910. #if !BB_MMU
  911. char *argv0_for_re_execing;
  912. #endif
  913. #if ENABLE_HUSH_LOOPS
  914. unsigned depth_break_continue;
  915. unsigned depth_of_loop;
  916. #endif
  917. #if ENABLE_HUSH_GETOPTS
  918. unsigned getopt_count;
  919. #endif
  920. const char *ifs;
  921. char *ifs_whitespace; /* = G.ifs or malloced */
  922. const char *cwd;
  923. struct variable *top_var;
  924. char **expanded_assignments;
  925. struct variable **shadowed_vars_pp;
  926. unsigned var_nest_level;
  927. #if ENABLE_HUSH_FUNCTIONS
  928. # if ENABLE_HUSH_LOCAL
  929. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  930. # endif
  931. struct function *top_func;
  932. #endif
  933. /* Signal and trap handling */
  934. #if ENABLE_HUSH_FAST
  935. unsigned count_SIGCHLD;
  936. unsigned handled_SIGCHLD;
  937. smallint we_have_children;
  938. #endif
  939. #if ENABLE_HUSH_LINENO_VAR
  940. unsigned parse_lineno;
  941. unsigned execute_lineno;
  942. #endif
  943. HFILE *HFILE_list;
  944. HFILE *HFILE_stdin;
  945. /* Which signals have non-DFL handler (even with no traps set)?
  946. * Set at the start to:
  947. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  948. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  949. * The rest is cleared right before execv syscalls.
  950. * Other than these two times, never modified.
  951. */
  952. unsigned special_sig_mask;
  953. #if ENABLE_HUSH_JOB
  954. unsigned fatal_sig_mask;
  955. # define G_fatal_sig_mask (G.fatal_sig_mask)
  956. #else
  957. # define G_fatal_sig_mask 0
  958. #endif
  959. #if ENABLE_HUSH_TRAP
  960. int pre_trap_exitcode;
  961. # if ENABLE_HUSH_FUNCTIONS
  962. int return_exitcode;
  963. # endif
  964. char **traps; /* char *traps[NSIG] */
  965. # define G_traps G.traps
  966. #else
  967. # define G_traps ((char**)NULL)
  968. #endif
  969. sigset_t pending_set;
  970. #if ENABLE_HUSH_MEMLEAK
  971. unsigned long memleak_value;
  972. #endif
  973. #if ENABLE_HUSH_MODE_X
  974. unsigned x_mode_depth;
  975. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  976. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  977. * for all subsequent output.
  978. */
  979. int x_mode_fd;
  980. o_string x_mode_buf;
  981. #endif
  982. #if HUSH_DEBUG >= 2
  983. int debug_indent;
  984. #endif
  985. struct sigaction sa;
  986. char optstring_buf[sizeof("eixcs")];
  987. #if BASH_EPOCH_VARS
  988. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  989. #endif
  990. #if ENABLE_FEATURE_EDITING
  991. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  992. #endif
  993. };
  994. #define G (*ptr_to_globals)
  995. /* Not #defining name to G.name - this quickly gets unwieldy
  996. * (too many defines). Also, I actually prefer to see when a variable
  997. * is global, thus "G." prefix is a useful hint */
  998. #define INIT_G() do { \
  999. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1000. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1001. sigfillset(&G.sa.sa_mask); \
  1002. G.sa.sa_flags = SA_RESTART; \
  1003. } while (0)
  1004. /* Function prototypes for builtins */
  1005. static int builtin_cd(char **argv) FAST_FUNC;
  1006. #if ENABLE_HUSH_ECHO
  1007. static int builtin_echo(char **argv) FAST_FUNC;
  1008. #endif
  1009. static int builtin_eval(char **argv) FAST_FUNC;
  1010. static int builtin_exec(char **argv) FAST_FUNC;
  1011. static int builtin_exit(char **argv) FAST_FUNC;
  1012. #if ENABLE_HUSH_EXPORT
  1013. static int builtin_export(char **argv) FAST_FUNC;
  1014. #endif
  1015. #if ENABLE_HUSH_READONLY
  1016. static int builtin_readonly(char **argv) FAST_FUNC;
  1017. #endif
  1018. #if ENABLE_HUSH_JOB
  1019. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1020. static int builtin_jobs(char **argv) FAST_FUNC;
  1021. #endif
  1022. #if ENABLE_HUSH_GETOPTS
  1023. static int builtin_getopts(char **argv) FAST_FUNC;
  1024. #endif
  1025. #if ENABLE_HUSH_HELP
  1026. static int builtin_help(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1029. static int builtin_history(char **argv) FAST_FUNC;
  1030. #endif
  1031. #if ENABLE_HUSH_LOCAL
  1032. static int builtin_local(char **argv) FAST_FUNC;
  1033. #endif
  1034. #if ENABLE_HUSH_MEMLEAK
  1035. static int builtin_memleak(char **argv) FAST_FUNC;
  1036. #endif
  1037. #if ENABLE_HUSH_PRINTF
  1038. static int builtin_printf(char **argv) FAST_FUNC;
  1039. #endif
  1040. static int builtin_pwd(char **argv) FAST_FUNC;
  1041. #if ENABLE_HUSH_READ
  1042. static int builtin_read(char **argv) FAST_FUNC;
  1043. #endif
  1044. #if ENABLE_HUSH_SET
  1045. static int builtin_set(char **argv) FAST_FUNC;
  1046. #endif
  1047. static int builtin_shift(char **argv) FAST_FUNC;
  1048. static int builtin_source(char **argv) FAST_FUNC;
  1049. #if ENABLE_HUSH_TEST || BASH_TEST2
  1050. static int builtin_test(char **argv) FAST_FUNC;
  1051. #endif
  1052. #if ENABLE_HUSH_TRAP
  1053. static int builtin_trap(char **argv) FAST_FUNC;
  1054. #endif
  1055. #if ENABLE_HUSH_TYPE
  1056. static int builtin_type(char **argv) FAST_FUNC;
  1057. #endif
  1058. #if ENABLE_HUSH_TIMES
  1059. static int builtin_times(char **argv) FAST_FUNC;
  1060. #endif
  1061. static int builtin_true(char **argv) FAST_FUNC;
  1062. #if ENABLE_HUSH_UMASK
  1063. static int builtin_umask(char **argv) FAST_FUNC;
  1064. #endif
  1065. #if ENABLE_HUSH_UNSET
  1066. static int builtin_unset(char **argv) FAST_FUNC;
  1067. #endif
  1068. #if ENABLE_HUSH_KILL
  1069. static int builtin_kill(char **argv) FAST_FUNC;
  1070. #endif
  1071. #if ENABLE_HUSH_WAIT
  1072. static int builtin_wait(char **argv) FAST_FUNC;
  1073. #endif
  1074. #if ENABLE_HUSH_LOOPS
  1075. static int builtin_break(char **argv) FAST_FUNC;
  1076. static int builtin_continue(char **argv) FAST_FUNC;
  1077. #endif
  1078. #if ENABLE_HUSH_FUNCTIONS
  1079. static int builtin_return(char **argv) FAST_FUNC;
  1080. #endif
  1081. /* Table of built-in functions. They can be forked or not, depending on
  1082. * context: within pipes, they fork. As simple commands, they do not.
  1083. * When used in non-forking context, they can change global variables
  1084. * in the parent shell process. If forked, of course they cannot.
  1085. * For example, 'unset foo | whatever' will parse and run, but foo will
  1086. * still be set at the end. */
  1087. struct built_in_command {
  1088. const char *b_cmd;
  1089. int (*b_function)(char **argv) FAST_FUNC;
  1090. #if ENABLE_HUSH_HELP
  1091. const char *b_descr;
  1092. # define BLTIN(cmd, func, help) { cmd, func, help }
  1093. #else
  1094. # define BLTIN(cmd, func, help) { cmd, func }
  1095. #endif
  1096. };
  1097. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1098. BLTIN("." , builtin_source , "Run commands in file"),
  1099. BLTIN(":" , builtin_true , NULL),
  1100. #if ENABLE_HUSH_JOB
  1101. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1102. #endif
  1103. #if ENABLE_HUSH_LOOPS
  1104. BLTIN("break" , builtin_break , "Exit loop"),
  1105. #endif
  1106. BLTIN("cd" , builtin_cd , "Change directory"),
  1107. #if ENABLE_HUSH_LOOPS
  1108. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1109. #endif
  1110. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1111. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1112. BLTIN("exit" , builtin_exit , NULL),
  1113. #if ENABLE_HUSH_EXPORT
  1114. BLTIN("export" , builtin_export , "Set environment variables"),
  1115. #endif
  1116. #if ENABLE_HUSH_JOB
  1117. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1118. #endif
  1119. #if ENABLE_HUSH_GETOPTS
  1120. BLTIN("getopts" , builtin_getopts , NULL),
  1121. #endif
  1122. #if ENABLE_HUSH_HELP
  1123. BLTIN("help" , builtin_help , NULL),
  1124. #endif
  1125. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1126. BLTIN("history" , builtin_history , "Show history"),
  1127. #endif
  1128. #if ENABLE_HUSH_JOB
  1129. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1130. #endif
  1131. #if ENABLE_HUSH_KILL
  1132. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1133. #endif
  1134. #if ENABLE_HUSH_LOCAL
  1135. BLTIN("local" , builtin_local , "Set local variables"),
  1136. #endif
  1137. #if ENABLE_HUSH_MEMLEAK
  1138. BLTIN("memleak" , builtin_memleak , NULL),
  1139. #endif
  1140. #if ENABLE_HUSH_READ
  1141. BLTIN("read" , builtin_read , "Input into variable"),
  1142. #endif
  1143. #if ENABLE_HUSH_READONLY
  1144. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1145. #endif
  1146. #if ENABLE_HUSH_FUNCTIONS
  1147. BLTIN("return" , builtin_return , "Return from function"),
  1148. #endif
  1149. #if ENABLE_HUSH_SET
  1150. BLTIN("set" , builtin_set , "Set positional parameters"),
  1151. #endif
  1152. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1153. #if BASH_SOURCE
  1154. BLTIN("source" , builtin_source , NULL),
  1155. #endif
  1156. #if ENABLE_HUSH_TIMES
  1157. BLTIN("times" , builtin_times , NULL),
  1158. #endif
  1159. #if ENABLE_HUSH_TRAP
  1160. BLTIN("trap" , builtin_trap , "Trap signals"),
  1161. #endif
  1162. BLTIN("true" , builtin_true , NULL),
  1163. #if ENABLE_HUSH_TYPE
  1164. BLTIN("type" , builtin_type , "Show command type"),
  1165. #endif
  1166. #if ENABLE_HUSH_ULIMIT
  1167. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1168. #endif
  1169. #if ENABLE_HUSH_UMASK
  1170. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1171. #endif
  1172. #if ENABLE_HUSH_UNSET
  1173. BLTIN("unset" , builtin_unset , "Unset variables"),
  1174. #endif
  1175. #if ENABLE_HUSH_WAIT
  1176. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1177. #endif
  1178. };
  1179. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1180. * (it's cheaper to run an external program in this case):
  1181. */
  1182. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1183. #if ENABLE_HUSH_TEST
  1184. BLTIN("[" , builtin_test , NULL),
  1185. #endif
  1186. #if BASH_TEST2
  1187. BLTIN("[[" , builtin_test , NULL),
  1188. #endif
  1189. #if ENABLE_HUSH_ECHO
  1190. BLTIN("echo" , builtin_echo , NULL),
  1191. #endif
  1192. #if ENABLE_HUSH_PRINTF
  1193. BLTIN("printf" , builtin_printf , NULL),
  1194. #endif
  1195. BLTIN("pwd" , builtin_pwd , NULL),
  1196. #if ENABLE_HUSH_TEST
  1197. BLTIN("test" , builtin_test , NULL),
  1198. #endif
  1199. };
  1200. /* Debug printouts.
  1201. */
  1202. #if HUSH_DEBUG >= 2
  1203. /* prevent disasters with G.debug_indent < 0 */
  1204. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1205. # define debug_enter() (G.debug_indent++)
  1206. # define debug_leave() (G.debug_indent--)
  1207. #else
  1208. # define indent() ((void)0)
  1209. # define debug_enter() ((void)0)
  1210. # define debug_leave() ((void)0)
  1211. #endif
  1212. #ifndef debug_printf
  1213. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1214. #endif
  1215. #ifndef debug_printf_parse
  1216. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. #endif
  1218. #ifndef debug_printf_heredoc
  1219. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1220. #endif
  1221. #ifndef debug_printf_exec
  1222. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. #endif
  1224. #ifndef debug_printf_env
  1225. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. #endif
  1227. #ifndef debug_printf_jobs
  1228. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. # define DEBUG_JOBS 1
  1230. #else
  1231. # define DEBUG_JOBS 0
  1232. #endif
  1233. #ifndef debug_printf_expand
  1234. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1235. # define DEBUG_EXPAND 1
  1236. #else
  1237. # define DEBUG_EXPAND 0
  1238. #endif
  1239. #ifndef debug_printf_varexp
  1240. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1241. #endif
  1242. #ifndef debug_printf_glob
  1243. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1244. # define DEBUG_GLOB 1
  1245. #else
  1246. # define DEBUG_GLOB 0
  1247. #endif
  1248. #ifndef debug_printf_redir
  1249. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1250. #endif
  1251. #ifndef debug_printf_list
  1252. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1253. #endif
  1254. #ifndef debug_printf_subst
  1255. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1256. #endif
  1257. #ifndef debug_printf_prompt
  1258. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1259. #endif
  1260. #ifndef debug_printf_clean
  1261. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1262. # define DEBUG_CLEAN 1
  1263. #else
  1264. # define DEBUG_CLEAN 0
  1265. #endif
  1266. #if DEBUG_EXPAND
  1267. static void debug_print_strings(const char *prefix, char **vv)
  1268. {
  1269. indent();
  1270. fdprintf(2, "%s:\n", prefix);
  1271. while (*vv)
  1272. fdprintf(2, " '%s'\n", *vv++);
  1273. }
  1274. #else
  1275. # define debug_print_strings(prefix, vv) ((void)0)
  1276. #endif
  1277. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1278. */
  1279. #if LEAK_HUNTING
  1280. static void *xxmalloc(int lineno, size_t size)
  1281. {
  1282. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1283. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1284. return ptr;
  1285. }
  1286. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1287. {
  1288. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1289. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1290. return ptr;
  1291. }
  1292. static char *xxstrdup(int lineno, const char *str)
  1293. {
  1294. char *ptr = xstrdup(str);
  1295. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1296. return ptr;
  1297. }
  1298. static void xxfree(void *ptr)
  1299. {
  1300. fdprintf(2, "free %p\n", ptr);
  1301. free(ptr);
  1302. }
  1303. # define xmalloc(s) xxmalloc(__LINE__, s)
  1304. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1305. # define xstrdup(s) xxstrdup(__LINE__, s)
  1306. # define free(p) xxfree(p)
  1307. #endif
  1308. /* Syntax and runtime errors. They always abort scripts.
  1309. * In interactive use they usually discard unparsed and/or unexecuted commands
  1310. * and return to the prompt.
  1311. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1312. */
  1313. #if HUSH_DEBUG < 2
  1314. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1315. # define syntax_error(lineno, msg) syntax_error(msg)
  1316. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1317. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1318. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1319. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1320. #endif
  1321. static void die_if_script(void)
  1322. {
  1323. if (!G_interactive_fd) {
  1324. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1325. xfunc_error_retval = G.last_exitcode;
  1326. xfunc_die();
  1327. }
  1328. }
  1329. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1330. {
  1331. va_list p;
  1332. #if HUSH_DEBUG >= 2
  1333. bb_error_msg("hush.c:%u", lineno);
  1334. #endif
  1335. va_start(p, fmt);
  1336. bb_verror_msg(fmt, p, NULL);
  1337. va_end(p);
  1338. die_if_script();
  1339. }
  1340. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1341. {
  1342. if (msg)
  1343. bb_error_msg("syntax error: %s", msg);
  1344. else
  1345. bb_simple_error_msg("syntax error");
  1346. die_if_script();
  1347. }
  1348. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1349. {
  1350. bb_error_msg("syntax error at '%s'", msg);
  1351. die_if_script();
  1352. }
  1353. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1354. {
  1355. bb_error_msg("syntax error: unterminated %s", s);
  1356. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1357. // die_if_script();
  1358. }
  1359. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1360. {
  1361. char msg[2] = { ch, '\0' };
  1362. syntax_error_unterm_str(lineno, msg);
  1363. }
  1364. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1365. {
  1366. char msg[2];
  1367. msg[0] = ch;
  1368. msg[1] = '\0';
  1369. #if HUSH_DEBUG >= 2
  1370. bb_error_msg("hush.c:%u", lineno);
  1371. #endif
  1372. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1373. die_if_script();
  1374. }
  1375. #if HUSH_DEBUG < 2
  1376. # undef msg_and_die_if_script
  1377. # undef syntax_error
  1378. # undef syntax_error_at
  1379. # undef syntax_error_unterm_ch
  1380. # undef syntax_error_unterm_str
  1381. # undef syntax_error_unexpected_ch
  1382. #else
  1383. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1384. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1385. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1386. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1387. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1388. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1389. #endif
  1390. /* Utility functions
  1391. */
  1392. /* Replace each \x with x in place, return ptr past NUL. */
  1393. static char *unbackslash(char *src)
  1394. {
  1395. char *dst = src = strchrnul(src, '\\');
  1396. while (1) {
  1397. if (*src == '\\') {
  1398. src++;
  1399. if (*src != '\0') {
  1400. /* \x -> x */
  1401. *dst++ = *src++;
  1402. continue;
  1403. }
  1404. /* else: "\<nul>". Do not delete this backslash.
  1405. * Testcase: eval 'echo ok\'
  1406. */
  1407. *dst++ = '\\';
  1408. /* fallthrough */
  1409. }
  1410. if ((*dst++ = *src++) == '\0')
  1411. break;
  1412. }
  1413. return dst;
  1414. }
  1415. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1416. {
  1417. int i;
  1418. unsigned count1;
  1419. unsigned count2;
  1420. char **v;
  1421. v = strings;
  1422. count1 = 0;
  1423. if (v) {
  1424. while (*v) {
  1425. count1++;
  1426. v++;
  1427. }
  1428. }
  1429. count2 = 0;
  1430. v = add;
  1431. while (*v) {
  1432. count2++;
  1433. v++;
  1434. }
  1435. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1436. v[count1 + count2] = NULL;
  1437. i = count2;
  1438. while (--i >= 0)
  1439. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1440. return v;
  1441. }
  1442. #if LEAK_HUNTING
  1443. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1444. {
  1445. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1446. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1447. return ptr;
  1448. }
  1449. #define add_strings_to_strings(strings, add, need_to_dup) \
  1450. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1451. #endif
  1452. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1453. static char **add_string_to_strings(char **strings, char *add)
  1454. {
  1455. char *v[2];
  1456. v[0] = add;
  1457. v[1] = NULL;
  1458. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1459. }
  1460. #if LEAK_HUNTING
  1461. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1462. {
  1463. char **ptr = add_string_to_strings(strings, add);
  1464. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1465. return ptr;
  1466. }
  1467. #define add_string_to_strings(strings, add) \
  1468. xx_add_string_to_strings(__LINE__, strings, add)
  1469. #endif
  1470. static void free_strings(char **strings)
  1471. {
  1472. char **v;
  1473. if (!strings)
  1474. return;
  1475. v = strings;
  1476. while (*v) {
  1477. free(*v);
  1478. v++;
  1479. }
  1480. free(strings);
  1481. }
  1482. static int dup_CLOEXEC(int fd, int avoid_fd)
  1483. {
  1484. int newfd;
  1485. repeat:
  1486. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1487. if (newfd >= 0) {
  1488. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1489. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1490. } else { /* newfd < 0 */
  1491. if (errno == EBUSY)
  1492. goto repeat;
  1493. if (errno == EINTR)
  1494. goto repeat;
  1495. }
  1496. return newfd;
  1497. }
  1498. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1499. {
  1500. int newfd;
  1501. repeat:
  1502. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1503. if (newfd < 0) {
  1504. if (errno == EBUSY)
  1505. goto repeat;
  1506. if (errno == EINTR)
  1507. goto repeat;
  1508. /* fd was not open? */
  1509. if (errno == EBADF)
  1510. return fd;
  1511. xfunc_die();
  1512. }
  1513. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1514. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1515. close(fd);
  1516. return newfd;
  1517. }
  1518. /* Manipulating HFILEs */
  1519. static HFILE *hfopen(const char *name)
  1520. {
  1521. HFILE *fp;
  1522. int fd;
  1523. fd = STDIN_FILENO;
  1524. if (name) {
  1525. fd = open(name, O_RDONLY | O_CLOEXEC);
  1526. if (fd < 0)
  1527. return NULL;
  1528. if (O_CLOEXEC == 0) /* ancient libc */
  1529. close_on_exec_on(fd);
  1530. }
  1531. fp = xmalloc(sizeof(*fp));
  1532. if (name == NULL)
  1533. G.HFILE_stdin = fp;
  1534. fp->fd = fd;
  1535. fp->cur = fp->end = fp->buf;
  1536. fp->next_hfile = G.HFILE_list;
  1537. G.HFILE_list = fp;
  1538. return fp;
  1539. }
  1540. static void hfclose(HFILE *fp)
  1541. {
  1542. HFILE **pp = &G.HFILE_list;
  1543. while (*pp) {
  1544. HFILE *cur = *pp;
  1545. if (cur == fp) {
  1546. *pp = cur->next_hfile;
  1547. break;
  1548. }
  1549. pp = &cur->next_hfile;
  1550. }
  1551. if (fp->fd >= 0)
  1552. close(fp->fd);
  1553. free(fp);
  1554. }
  1555. static int refill_HFILE_and_getc(HFILE *fp)
  1556. {
  1557. int n;
  1558. if (fp->fd < 0) {
  1559. /* Already saw EOF */
  1560. return EOF;
  1561. }
  1562. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1563. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1564. * IOW: ^C will not immediately stop line input.
  1565. * But poll() is different: it does NOT restart after signals.
  1566. */
  1567. if (fp == G.HFILE_stdin) {
  1568. struct pollfd pfd[1];
  1569. pfd[0].fd = fp->fd;
  1570. pfd[0].events = POLLIN;
  1571. n = poll(pfd, 1, -1);
  1572. if (n < 0
  1573. /*&& errno == EINTR - assumed true */
  1574. && sigismember(&G.pending_set, SIGINT)
  1575. ) {
  1576. return '\0';
  1577. }
  1578. }
  1579. #else
  1580. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1581. #endif
  1582. /* Try to buffer more input */
  1583. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1584. if (n < 0) {
  1585. bb_simple_perror_msg("read error");
  1586. n = 0;
  1587. }
  1588. fp->cur = fp->buf;
  1589. fp->end = fp->buf + n;
  1590. if (n == 0) {
  1591. /* EOF/error */
  1592. close(fp->fd);
  1593. fp->fd = -1;
  1594. return EOF;
  1595. }
  1596. return (unsigned char)(*fp->cur++);
  1597. }
  1598. /* Inlined for common case of non-empty buffer.
  1599. */
  1600. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1601. {
  1602. if (fp->cur < fp->end)
  1603. return (unsigned char)(*fp->cur++);
  1604. /* Buffer empty */
  1605. return refill_HFILE_and_getc(fp);
  1606. }
  1607. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1608. {
  1609. HFILE *fl = G.HFILE_list;
  1610. while (fl) {
  1611. if (fd == fl->fd) {
  1612. /* We use it only on script files, they are all CLOEXEC */
  1613. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1614. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1615. return 1; /* "found and moved" */
  1616. }
  1617. fl = fl->next_hfile;
  1618. }
  1619. #if ENABLE_HUSH_MODE_X
  1620. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1621. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1622. return 1; /* "found and moved" */
  1623. }
  1624. #endif
  1625. return 0; /* "not in the list" */
  1626. }
  1627. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1628. static void close_all_HFILE_list(void)
  1629. {
  1630. HFILE *fl = G.HFILE_list;
  1631. while (fl) {
  1632. /* hfclose would also free HFILE object.
  1633. * It is disastrous if we share memory with a vforked parent.
  1634. * I'm not sure we never come here after vfork.
  1635. * Therefore just close fd, nothing more.
  1636. *
  1637. * ">" instead of ">=": we don't close fd#0,
  1638. * interactive shell uses hfopen(NULL) as stdin input
  1639. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1640. * If we'd close it here, then e.g. interactive "set | sort"
  1641. * with NOFORKed sort, would have sort's input fd closed.
  1642. */
  1643. if (fl->fd > 0)
  1644. /*hfclose(fl); - unsafe */
  1645. close(fl->fd);
  1646. fl = fl->next_hfile;
  1647. }
  1648. }
  1649. #endif
  1650. static int fd_in_HFILEs(int fd)
  1651. {
  1652. HFILE *fl = G.HFILE_list;
  1653. while (fl) {
  1654. if (fl->fd == fd)
  1655. return 1;
  1656. fl = fl->next_hfile;
  1657. }
  1658. return 0;
  1659. }
  1660. /* Helpers for setting new $n and restoring them back
  1661. */
  1662. typedef struct save_arg_t {
  1663. char *sv_argv0;
  1664. char **sv_g_argv;
  1665. int sv_g_argc;
  1666. IF_HUSH_SET(smallint sv_g_malloced;)
  1667. } save_arg_t;
  1668. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1669. {
  1670. sv->sv_argv0 = argv[0];
  1671. sv->sv_g_argv = G.global_argv;
  1672. sv->sv_g_argc = G.global_argc;
  1673. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1674. argv[0] = G.global_argv[0]; /* retain $0 */
  1675. G.global_argv = argv;
  1676. IF_HUSH_SET(G.global_args_malloced = 0;)
  1677. G.global_argc = 1 + string_array_len(argv + 1);
  1678. }
  1679. static void restore_G_args(save_arg_t *sv, char **argv)
  1680. {
  1681. #if ENABLE_HUSH_SET
  1682. if (G.global_args_malloced) {
  1683. /* someone ran "set -- arg1 arg2 ...", undo */
  1684. char **pp = G.global_argv;
  1685. while (*++pp) /* note: does not free $0 */
  1686. free(*pp);
  1687. free(G.global_argv);
  1688. }
  1689. #endif
  1690. argv[0] = sv->sv_argv0;
  1691. G.global_argv = sv->sv_g_argv;
  1692. G.global_argc = sv->sv_g_argc;
  1693. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1694. }
  1695. /* Basic theory of signal handling in shell
  1696. * ========================================
  1697. * This does not describe what hush does, rather, it is current understanding
  1698. * what it _should_ do. If it doesn't, it's a bug.
  1699. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1700. *
  1701. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1702. * is finished or backgrounded. It is the same in interactive and
  1703. * non-interactive shells, and is the same regardless of whether
  1704. * a user trap handler is installed or a shell special one is in effect.
  1705. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1706. * backgrounds (i.e. stops) or kills all members of currently running
  1707. * pipe.
  1708. *
  1709. * Wait builtin is interruptible by signals for which user trap is set
  1710. * or by SIGINT in interactive shell.
  1711. *
  1712. * Trap handlers will execute even within trap handlers. (right?)
  1713. *
  1714. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1715. * except for handlers set to '' (empty string).
  1716. *
  1717. * If job control is off, backgrounded commands ("cmd &")
  1718. * have SIGINT, SIGQUIT set to SIG_IGN.
  1719. *
  1720. * Commands which are run in command substitution ("`cmd`")
  1721. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1722. *
  1723. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1724. * by the shell from its parent.
  1725. *
  1726. * Signals which differ from SIG_DFL action
  1727. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1728. *
  1729. * SIGQUIT: ignore
  1730. * SIGTERM (interactive): ignore
  1731. * SIGHUP (interactive):
  1732. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1733. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1734. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1735. * that all pipe members are stopped. Try this in bash:
  1736. * while :; do :; done - ^Z does not background it
  1737. * (while :; do :; done) - ^Z backgrounds it
  1738. * SIGINT (interactive): wait for last pipe, ignore the rest
  1739. * of the command line, show prompt. NB: ^C does not send SIGINT
  1740. * to interactive shell while shell is waiting for a pipe,
  1741. * since shell is bg'ed (is not in foreground process group).
  1742. * Example 1: this waits 5 sec, but does not execute ls:
  1743. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1744. * Example 2: this does not wait and does not execute ls:
  1745. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1746. * Example 3: this does not wait 5 sec, but executes ls:
  1747. * "sleep 5; ls -l" + press ^C
  1748. * Example 4: this does not wait and does not execute ls:
  1749. * "sleep 5 & wait; ls -l" + press ^C
  1750. *
  1751. * (What happens to signals which are IGN on shell start?)
  1752. * (What happens with signal mask on shell start?)
  1753. *
  1754. * Old implementation
  1755. * ==================
  1756. * We use in-kernel pending signal mask to determine which signals were sent.
  1757. * We block all signals which we don't want to take action immediately,
  1758. * i.e. we block all signals which need to have special handling as described
  1759. * above, and all signals which have traps set.
  1760. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1761. * and act on them.
  1762. *
  1763. * unsigned special_sig_mask: a mask of such "special" signals
  1764. * sigset_t blocked_set: current blocked signal set
  1765. *
  1766. * "trap - SIGxxx":
  1767. * clear bit in blocked_set unless it is also in special_sig_mask
  1768. * "trap 'cmd' SIGxxx":
  1769. * set bit in blocked_set (even if 'cmd' is '')
  1770. * after [v]fork, if we plan to be a shell:
  1771. * unblock signals with special interactive handling
  1772. * (child shell is not interactive),
  1773. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1774. * after [v]fork, if we plan to exec:
  1775. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1776. * Restore blocked signal set to one inherited by shell just prior to exec.
  1777. *
  1778. * Note: as a result, we do not use signal handlers much. The only uses
  1779. * are to count SIGCHLDs
  1780. * and to restore tty pgrp on signal-induced exit.
  1781. *
  1782. * Note 2 (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. * Problem: the above approach makes it unwieldy to catch signals while
  1788. * we are in read builtin, or while we read commands from stdin:
  1789. * masked signals are not visible!
  1790. *
  1791. * New implementation
  1792. * ==================
  1793. * We record each signal we are interested in by installing signal handler
  1794. * for them - a bit like emulating kernel pending signal mask in userspace.
  1795. * We are interested in: signals which need to have special handling
  1796. * as described above, and all signals which have traps set.
  1797. * Signals are recorded in pending_set.
  1798. * After each pipe execution, we extract any pending signals
  1799. * and act on them.
  1800. *
  1801. * unsigned special_sig_mask: a mask of shell-special signals.
  1802. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1803. * char *traps[sig] if trap for sig is set (even if it's '').
  1804. * sigset_t pending_set: set of sigs we received.
  1805. *
  1806. * "trap - SIGxxx":
  1807. * if sig is in special_sig_mask, set handler back to:
  1808. * record_pending_signo, or to IGN if it's a tty stop signal
  1809. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1810. * else: set handler back to SIG_DFL
  1811. * "trap 'cmd' SIGxxx":
  1812. * set handler to record_pending_signo.
  1813. * "trap '' SIGxxx":
  1814. * set handler to SIG_IGN.
  1815. * after [v]fork, if we plan to be a shell:
  1816. * set signals with special interactive handling to SIG_DFL
  1817. * (because child shell is not interactive),
  1818. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1819. * after [v]fork, if we plan to exec:
  1820. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1821. *
  1822. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1823. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1824. *
  1825. * Note (compat):
  1826. * Standard says "When a subshell is entered, traps that are not being ignored
  1827. * are set to the default actions". bash interprets it so that traps which
  1828. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1829. */
  1830. enum {
  1831. SPECIAL_INTERACTIVE_SIGS = 0
  1832. | (1 << SIGTERM)
  1833. | (1 << SIGINT)
  1834. | (1 << SIGHUP)
  1835. ,
  1836. SPECIAL_JOBSTOP_SIGS = 0
  1837. #if ENABLE_HUSH_JOB
  1838. | (1 << SIGTTIN)
  1839. | (1 << SIGTTOU)
  1840. | (1 << SIGTSTP)
  1841. #endif
  1842. ,
  1843. };
  1844. static void record_pending_signo(int sig)
  1845. {
  1846. sigaddset(&G.pending_set, sig);
  1847. #if ENABLE_HUSH_FAST
  1848. if (sig == SIGCHLD) {
  1849. G.count_SIGCHLD++;
  1850. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1851. }
  1852. #endif
  1853. }
  1854. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1855. {
  1856. struct sigaction old_sa;
  1857. /* We could use signal() to install handlers... almost:
  1858. * except that we need to mask ALL signals while handlers run.
  1859. * I saw signal nesting in strace, race window isn't small.
  1860. * SA_RESTART is also needed, but in Linux, signal()
  1861. * sets SA_RESTART too.
  1862. */
  1863. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1864. /* sigfillset(&G.sa.sa_mask); - already done */
  1865. /* G.sa.sa_flags = SA_RESTART; - already done */
  1866. G.sa.sa_handler = handler;
  1867. sigaction(sig, &G.sa, &old_sa);
  1868. return old_sa.sa_handler;
  1869. }
  1870. static void hush_exit(int exitcode) NORETURN;
  1871. static void restore_ttypgrp_and__exit(void) NORETURN;
  1872. static void restore_ttypgrp_and__exit(void)
  1873. {
  1874. /* xfunc has failed! die die die */
  1875. /* no EXIT traps, this is an escape hatch! */
  1876. G.exiting = 1;
  1877. hush_exit(xfunc_error_retval);
  1878. }
  1879. #if ENABLE_HUSH_JOB
  1880. /* Needed only on some libc:
  1881. * It was observed that on exit(), fgetc'ed buffered data
  1882. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1883. * With the net effect that even after fork(), not vfork(),
  1884. * exit() in NOEXECed applet in "sh SCRIPT":
  1885. * noexec_applet_here
  1886. * echo END_OF_SCRIPT
  1887. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1888. * This makes "echo END_OF_SCRIPT" executed twice.
  1889. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1890. * and in `cmd` handling.
  1891. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1892. */
  1893. static void fflush_and__exit(void) NORETURN;
  1894. static void fflush_and__exit(void)
  1895. {
  1896. fflush_all();
  1897. _exit(xfunc_error_retval);
  1898. }
  1899. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1900. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1901. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1902. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1903. /* Restores tty foreground process group, and exits.
  1904. * May be called as signal handler for fatal signal
  1905. * (will resend signal to itself, producing correct exit state)
  1906. * or called directly with -EXITCODE.
  1907. * We also call it if xfunc is exiting.
  1908. */
  1909. static void sigexit(int sig) NORETURN;
  1910. static void sigexit(int sig)
  1911. {
  1912. /* Careful: we can end up here after [v]fork. Do not restore
  1913. * tty pgrp then, only top-level shell process does that */
  1914. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1915. /* Disable all signals: job control, SIGPIPE, etc.
  1916. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1917. */
  1918. sigprocmask_allsigs(SIG_BLOCK);
  1919. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1920. }
  1921. /* Not a signal, just exit */
  1922. if (sig <= 0)
  1923. _exit(- sig);
  1924. kill_myself_with_sig(sig); /* does not return */
  1925. }
  1926. #else
  1927. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1928. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1929. #endif
  1930. static sighandler_t pick_sighandler(unsigned sig)
  1931. {
  1932. sighandler_t handler = SIG_DFL;
  1933. if (sig < sizeof(unsigned)*8) {
  1934. unsigned sigmask = (1 << sig);
  1935. #if ENABLE_HUSH_JOB
  1936. /* is sig fatal? */
  1937. if (G_fatal_sig_mask & sigmask)
  1938. handler = sigexit;
  1939. else
  1940. #endif
  1941. /* sig has special handling? */
  1942. if (G.special_sig_mask & sigmask) {
  1943. handler = record_pending_signo;
  1944. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1945. * in order to ignore them: they will be raised
  1946. * in an endless loop when we try to do some
  1947. * terminal ioctls! We do have to _ignore_ these.
  1948. */
  1949. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1950. handler = SIG_IGN;
  1951. }
  1952. }
  1953. return handler;
  1954. }
  1955. /* Restores tty foreground process group, and exits. */
  1956. static void hush_exit(int exitcode)
  1957. {
  1958. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1959. save_history(G.line_input_state); /* may be NULL */
  1960. #endif
  1961. fflush_all();
  1962. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1963. char *argv[3];
  1964. /* argv[0] is unused */
  1965. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1966. argv[2] = NULL;
  1967. G.exiting = 1; /* prevent EXIT trap recursion */
  1968. /* Note: G_traps[0] is not cleared!
  1969. * "trap" will still show it, if executed
  1970. * in the handler */
  1971. builtin_eval(argv);
  1972. }
  1973. #if ENABLE_FEATURE_CLEAN_UP
  1974. {
  1975. struct variable *cur_var;
  1976. if (G.cwd != bb_msg_unknown)
  1977. free((char*)G.cwd);
  1978. cur_var = G.top_var;
  1979. while (cur_var) {
  1980. struct variable *tmp = cur_var;
  1981. if (!cur_var->max_len)
  1982. free(cur_var->varstr);
  1983. cur_var = cur_var->next;
  1984. free(tmp);
  1985. }
  1986. }
  1987. #endif
  1988. fflush_all();
  1989. #if ENABLE_HUSH_JOB
  1990. sigexit(- (exitcode & 0xff));
  1991. #else
  1992. _exit(exitcode);
  1993. #endif
  1994. }
  1995. //TODO: return a mask of ALL handled sigs?
  1996. static int check_and_run_traps(void)
  1997. {
  1998. int last_sig = 0;
  1999. while (1) {
  2000. int sig;
  2001. if (sigisemptyset(&G.pending_set))
  2002. break;
  2003. sig = 0;
  2004. do {
  2005. sig++;
  2006. if (sigismember(&G.pending_set, sig)) {
  2007. sigdelset(&G.pending_set, sig);
  2008. goto got_sig;
  2009. }
  2010. } while (sig < NSIG);
  2011. break;
  2012. got_sig:
  2013. #if ENABLE_HUSH_TRAP
  2014. if (G_traps && G_traps[sig]) {
  2015. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2016. if (G_traps[sig][0]) {
  2017. /* We have user-defined handler */
  2018. smalluint save_rcode;
  2019. int save_pre;
  2020. char *argv[3];
  2021. /* argv[0] is unused */
  2022. argv[1] = xstrdup(G_traps[sig]);
  2023. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2024. argv[2] = NULL;
  2025. save_pre = G.pre_trap_exitcode;
  2026. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2027. builtin_eval(argv);
  2028. free(argv[1]);
  2029. G.pre_trap_exitcode = save_pre;
  2030. G.last_exitcode = save_rcode;
  2031. # if ENABLE_HUSH_FUNCTIONS
  2032. if (G.return_exitcode >= 0) {
  2033. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2034. G.last_exitcode = G.return_exitcode;
  2035. }
  2036. # endif
  2037. last_sig = sig;
  2038. } /* else: "" trap, ignoring signal */
  2039. continue;
  2040. }
  2041. #endif
  2042. /* not a trap: special action */
  2043. switch (sig) {
  2044. case SIGINT:
  2045. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2046. G.flag_SIGINT = 1;
  2047. last_sig = sig;
  2048. break;
  2049. #if ENABLE_HUSH_JOB
  2050. case SIGHUP: {
  2051. //TODO: why are we doing this? ash and dash don't do this,
  2052. //they have no handler for SIGHUP at all,
  2053. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2054. struct pipe *job;
  2055. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2056. /* bash is observed to signal whole process groups,
  2057. * not individual processes */
  2058. for (job = G.job_list; job; job = job->next) {
  2059. if (job->pgrp <= 0)
  2060. continue;
  2061. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2062. if (kill(- job->pgrp, SIGHUP) == 0)
  2063. kill(- job->pgrp, SIGCONT);
  2064. }
  2065. sigexit(SIGHUP);
  2066. }
  2067. #endif
  2068. #if ENABLE_HUSH_FAST
  2069. case SIGCHLD:
  2070. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2071. G.count_SIGCHLD++;
  2072. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2073. /* Note:
  2074. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2075. * This simplifies wait builtin a bit.
  2076. */
  2077. break;
  2078. #endif
  2079. default: /* ignored: */
  2080. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2081. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2082. /* Note:
  2083. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2084. * Example: wait is not interrupted by TERM
  2085. * in interactive shell, because TERM is ignored.
  2086. */
  2087. break;
  2088. }
  2089. }
  2090. return last_sig;
  2091. }
  2092. static const char *get_cwd(int force)
  2093. {
  2094. if (force || G.cwd == NULL) {
  2095. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2096. * we must not try to free(bb_msg_unknown) */
  2097. if (G.cwd == bb_msg_unknown)
  2098. G.cwd = NULL;
  2099. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2100. if (!G.cwd)
  2101. G.cwd = bb_msg_unknown;
  2102. }
  2103. return G.cwd;
  2104. }
  2105. /*
  2106. * Shell and environment variable support
  2107. */
  2108. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2109. {
  2110. struct variable **pp;
  2111. struct variable *cur;
  2112. pp = &G.top_var;
  2113. while ((cur = *pp) != NULL) {
  2114. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2115. return pp;
  2116. pp = &cur->next;
  2117. }
  2118. return NULL;
  2119. }
  2120. static const char* FAST_FUNC get_local_var_value(const char *name)
  2121. {
  2122. struct variable **vpp;
  2123. unsigned len = strlen(name);
  2124. if (G.expanded_assignments) {
  2125. char **cpp = G.expanded_assignments;
  2126. while (*cpp) {
  2127. char *cp = *cpp;
  2128. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2129. return cp + len + 1;
  2130. cpp++;
  2131. }
  2132. }
  2133. vpp = get_ptr_to_local_var(name, len);
  2134. if (vpp)
  2135. return (*vpp)->varstr + len + 1;
  2136. if (strcmp(name, "PPID") == 0)
  2137. return utoa(G.root_ppid);
  2138. // bash compat: UID? EUID?
  2139. #if ENABLE_HUSH_RANDOM_SUPPORT
  2140. if (strcmp(name, "RANDOM") == 0)
  2141. return utoa(next_random(&G.random_gen));
  2142. #endif
  2143. #if ENABLE_HUSH_LINENO_VAR
  2144. if (strcmp(name, "LINENO") == 0)
  2145. return utoa(G.execute_lineno);
  2146. #endif
  2147. #if BASH_EPOCH_VARS
  2148. {
  2149. const char *fmt = NULL;
  2150. if (strcmp(name, "EPOCHSECONDS") == 0)
  2151. fmt = "%llu";
  2152. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2153. fmt = "%llu.%06u";
  2154. if (fmt) {
  2155. struct timeval tv;
  2156. xgettimeofday(&tv);
  2157. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2158. (unsigned)tv.tv_usec);
  2159. return G.epoch_buf;
  2160. }
  2161. }
  2162. #endif
  2163. return NULL;
  2164. }
  2165. #if ENABLE_HUSH_GETOPTS
  2166. static void handle_changed_special_names(const char *name, unsigned name_len)
  2167. {
  2168. if (name_len == 6) {
  2169. if (strncmp(name, "OPTIND", 6) == 0) {
  2170. G.getopt_count = 0;
  2171. return;
  2172. }
  2173. }
  2174. }
  2175. #else
  2176. /* Do not even bother evaluating arguments */
  2177. # define handle_changed_special_names(...) ((void)0)
  2178. #endif
  2179. /* str holds "NAME=VAL" and is expected to be malloced.
  2180. * We take ownership of it.
  2181. */
  2182. #define SETFLAG_EXPORT (1 << 0)
  2183. #define SETFLAG_UNEXPORT (1 << 1)
  2184. #define SETFLAG_MAKE_RO (1 << 2)
  2185. #define SETFLAG_VARLVL_SHIFT 3
  2186. static int set_local_var(char *str, unsigned flags)
  2187. {
  2188. struct variable **cur_pp;
  2189. struct variable *cur;
  2190. char *free_me = NULL;
  2191. char *eq_sign;
  2192. int name_len;
  2193. int retval;
  2194. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2195. eq_sign = strchr(str, '=');
  2196. if (HUSH_DEBUG && !eq_sign)
  2197. bb_simple_error_msg_and_die("BUG in setvar");
  2198. name_len = eq_sign - str + 1; /* including '=' */
  2199. cur_pp = &G.top_var;
  2200. while ((cur = *cur_pp) != NULL) {
  2201. if (strncmp(cur->varstr, str, name_len) != 0) {
  2202. cur_pp = &cur->next;
  2203. continue;
  2204. }
  2205. /* We found an existing var with this name */
  2206. if (cur->flg_read_only) {
  2207. bb_error_msg("%s: readonly variable", str);
  2208. free(str);
  2209. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2210. //but export per se succeeds (does put the var in env). We don't mimic that.
  2211. return -1;
  2212. }
  2213. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2214. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2215. *eq_sign = '\0';
  2216. unsetenv(str);
  2217. *eq_sign = '=';
  2218. }
  2219. if (cur->var_nest_level < local_lvl) {
  2220. /* bash 3.2.33(1) and exported vars:
  2221. * # export z=z
  2222. * # f() { local z=a; env | grep ^z; }
  2223. * # f
  2224. * z=a
  2225. * # env | grep ^z
  2226. * z=z
  2227. */
  2228. if (cur->flg_export)
  2229. flags |= SETFLAG_EXPORT;
  2230. /* New variable is local ("local VAR=VAL" or
  2231. * "VAR=VAL cmd")
  2232. * and existing one is global, or local
  2233. * on a lower level that new one.
  2234. * Remove it from global variable list:
  2235. */
  2236. *cur_pp = cur->next;
  2237. if (G.shadowed_vars_pp) {
  2238. /* Save in "shadowed" list */
  2239. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2240. cur->flg_export ? "exported " : "",
  2241. cur->varstr, cur->var_nest_level, str, local_lvl
  2242. );
  2243. cur->next = *G.shadowed_vars_pp;
  2244. *G.shadowed_vars_pp = cur;
  2245. } else {
  2246. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2247. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2248. cur->flg_export ? "exported " : "",
  2249. cur->varstr, cur->var_nest_level, str, local_lvl
  2250. );
  2251. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2252. free_me = cur->varstr; /* then free it later */
  2253. free(cur);
  2254. }
  2255. break;
  2256. }
  2257. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2258. debug_printf_env("assignement '%s' does not change anything\n", str);
  2259. free_and_exp:
  2260. free(str);
  2261. goto exp;
  2262. }
  2263. /* Replace the value in the found "struct variable" */
  2264. if (cur->max_len != 0) {
  2265. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2266. /* This one is from startup env, reuse space */
  2267. debug_printf_env("reusing startup env for '%s'\n", str);
  2268. strcpy(cur->varstr, str);
  2269. goto free_and_exp;
  2270. }
  2271. /* Can't reuse */
  2272. cur->max_len = 0;
  2273. goto set_str_and_exp;
  2274. }
  2275. /* max_len == 0 signifies "malloced" var, which we can
  2276. * (and have to) free. But we can't free(cur->varstr) here:
  2277. * if cur->flg_export is 1, it is in the environment.
  2278. * We should either unsetenv+free, or wait until putenv,
  2279. * then putenv(new)+free(old).
  2280. */
  2281. free_me = cur->varstr;
  2282. goto set_str_and_exp;
  2283. }
  2284. /* Not found or shadowed - create new variable struct */
  2285. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2286. cur = xzalloc(sizeof(*cur));
  2287. cur->var_nest_level = local_lvl;
  2288. cur->next = *cur_pp;
  2289. *cur_pp = cur;
  2290. set_str_and_exp:
  2291. cur->varstr = str;
  2292. exp:
  2293. #if !BB_MMU || ENABLE_HUSH_READONLY
  2294. if (flags & SETFLAG_MAKE_RO) {
  2295. cur->flg_read_only = 1;
  2296. }
  2297. #endif
  2298. if (flags & SETFLAG_EXPORT)
  2299. cur->flg_export = 1;
  2300. retval = 0;
  2301. if (cur->flg_export) {
  2302. if (flags & SETFLAG_UNEXPORT) {
  2303. cur->flg_export = 0;
  2304. /* unsetenv was already done */
  2305. } else {
  2306. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2307. retval = putenv(cur->varstr);
  2308. /* fall through to "free(free_me)" -
  2309. * only now we can free old exported malloced string
  2310. */
  2311. }
  2312. }
  2313. free(free_me);
  2314. handle_changed_special_names(cur->varstr, name_len - 1);
  2315. return retval;
  2316. }
  2317. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2318. {
  2319. char *var = xasprintf("%s=%s", name, val);
  2320. set_local_var(var, /*flag:*/ 0);
  2321. }
  2322. /* Used at startup and after each cd */
  2323. static void set_pwd_var(unsigned flag)
  2324. {
  2325. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2326. }
  2327. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2328. static int unset_local_var_len(const char *name, int name_len)
  2329. {
  2330. struct variable *cur;
  2331. struct variable **cur_pp;
  2332. cur_pp = &G.top_var;
  2333. while ((cur = *cur_pp) != NULL) {
  2334. if (strncmp(cur->varstr, name, name_len) == 0
  2335. && cur->varstr[name_len] == '='
  2336. ) {
  2337. if (cur->flg_read_only) {
  2338. bb_error_msg("%s: readonly variable", name);
  2339. return EXIT_FAILURE;
  2340. }
  2341. *cur_pp = cur->next;
  2342. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2343. bb_unsetenv(cur->varstr);
  2344. if (!cur->max_len)
  2345. free(cur->varstr);
  2346. free(cur);
  2347. break;
  2348. }
  2349. cur_pp = &cur->next;
  2350. }
  2351. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2352. handle_changed_special_names(name, name_len);
  2353. return EXIT_SUCCESS;
  2354. }
  2355. static int unset_local_var(const char *name)
  2356. {
  2357. return unset_local_var_len(name, strlen(name));
  2358. }
  2359. #endif
  2360. /*
  2361. * Helpers for "var1=val1 var2=val2 cmd" feature
  2362. */
  2363. static void add_vars(struct variable *var)
  2364. {
  2365. struct variable *next;
  2366. while (var) {
  2367. next = var->next;
  2368. var->next = G.top_var;
  2369. G.top_var = var;
  2370. if (var->flg_export) {
  2371. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2372. putenv(var->varstr);
  2373. } else {
  2374. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2375. }
  2376. var = next;
  2377. }
  2378. }
  2379. /* We put strings[i] into variable table and possibly putenv them.
  2380. * If variable is read only, we can free the strings[i]
  2381. * which attempts to overwrite it.
  2382. * The strings[] vector itself is freed.
  2383. */
  2384. static void set_vars_and_save_old(char **strings)
  2385. {
  2386. char **s;
  2387. if (!strings)
  2388. return;
  2389. s = strings;
  2390. while (*s) {
  2391. struct variable *var_p;
  2392. struct variable **var_pp;
  2393. char *eq;
  2394. eq = strchr(*s, '=');
  2395. if (HUSH_DEBUG && !eq)
  2396. bb_simple_error_msg_and_die("BUG in varexp4");
  2397. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2398. if (var_pp) {
  2399. var_p = *var_pp;
  2400. if (var_p->flg_read_only) {
  2401. char **p;
  2402. bb_error_msg("%s: readonly variable", *s);
  2403. /*
  2404. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2405. * If VAR is readonly, leaving it in the list
  2406. * after asssignment error (msg above)
  2407. * causes doubled error message later, on unset.
  2408. */
  2409. debug_printf_env("removing/freeing '%s' element\n", *s);
  2410. free(*s);
  2411. p = s;
  2412. do { *p = p[1]; p++; } while (*p);
  2413. goto next;
  2414. }
  2415. /* below, set_local_var() with nest level will
  2416. * "shadow" (remove) this variable from
  2417. * global linked list.
  2418. */
  2419. }
  2420. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2421. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2422. s++;
  2423. next: ;
  2424. }
  2425. free(strings);
  2426. }
  2427. /*
  2428. * Unicode helper
  2429. */
  2430. static void reinit_unicode_for_hush(void)
  2431. {
  2432. /* Unicode support should be activated even if LANG is set
  2433. * _during_ shell execution, not only if it was set when
  2434. * shell was started. Therefore, re-check LANG every time:
  2435. */
  2436. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2437. || ENABLE_UNICODE_USING_LOCALE
  2438. ) {
  2439. const char *s = get_local_var_value("LC_ALL");
  2440. if (!s) s = get_local_var_value("LC_CTYPE");
  2441. if (!s) s = get_local_var_value("LANG");
  2442. reinit_unicode(s);
  2443. }
  2444. }
  2445. /*
  2446. * in_str support (strings, and "strings" read from files).
  2447. */
  2448. #if ENABLE_HUSH_INTERACTIVE
  2449. /* To test correct lineedit/interactive behavior, type from command line:
  2450. * echo $P\
  2451. * \
  2452. * AT\
  2453. * H\
  2454. * \
  2455. * It exercises a lot of corner cases.
  2456. */
  2457. static const char *setup_prompt_string(void)
  2458. {
  2459. const char *prompt_str;
  2460. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2461. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2462. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2463. if (!prompt_str)
  2464. prompt_str = "";
  2465. # else
  2466. prompt_str = "> "; /* if PS2, else... */
  2467. if (G.promptmode == 0) { /* PS1 */
  2468. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2469. free(G.PS1);
  2470. /* bash uses $PWD value, even if it is set by user.
  2471. * It uses current dir only if PWD is unset.
  2472. * We always use current dir. */
  2473. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2474. }
  2475. # endif
  2476. debug_printf("prompt_str '%s'\n", prompt_str);
  2477. return prompt_str;
  2478. }
  2479. static int get_user_input(struct in_str *i)
  2480. {
  2481. # if ENABLE_FEATURE_EDITING
  2482. /* In EDITING case, this function reads next input line,
  2483. * saves it in i->p, then returns 1st char of it.
  2484. */
  2485. int r;
  2486. const char *prompt_str;
  2487. prompt_str = setup_prompt_string();
  2488. for (;;) {
  2489. reinit_unicode_for_hush();
  2490. G.flag_SIGINT = 0;
  2491. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2492. * only after <Enter>. (^C works immediately) */
  2493. r = read_line_input(G.line_input_state, prompt_str,
  2494. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2495. );
  2496. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2497. if (r == 0) {
  2498. raise(SIGINT);
  2499. }
  2500. check_and_run_traps();
  2501. if (r != 0 && !G.flag_SIGINT)
  2502. break;
  2503. /* ^C or SIGINT: repeat */
  2504. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2505. write(STDOUT_FILENO, "^C\n", 3);
  2506. G.last_exitcode = 128 | SIGINT;
  2507. }
  2508. if (r < 0) {
  2509. /* EOF/error detected */
  2510. /* ^D on interactive input goes to next line before exiting: */
  2511. write(STDOUT_FILENO, "\n", 1);
  2512. i->p = NULL;
  2513. i->peek_buf[0] = r = EOF;
  2514. return r;
  2515. }
  2516. i->p = G.user_input_buf;
  2517. return (unsigned char)*i->p++;
  2518. # else
  2519. /* In !EDITING case, this function gets called for every char.
  2520. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2521. */
  2522. int r;
  2523. for (;;) {
  2524. G.flag_SIGINT = 0;
  2525. if (i->last_char == '\0' || i->last_char == '\n') {
  2526. const char *prompt_str = setup_prompt_string();
  2527. /* Why check_and_run_traps here? Try this interactively:
  2528. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2529. * $ <[enter], repeatedly...>
  2530. * Without check_and_run_traps, handler never runs.
  2531. */
  2532. check_and_run_traps();
  2533. fputs_stdout(prompt_str);
  2534. fflush_all();
  2535. }
  2536. r = hfgetc(i->file);
  2537. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2538. * no ^C masking happens during fgetc, no special code for ^C:
  2539. * it generates SIGINT as usual.
  2540. */
  2541. check_and_run_traps();
  2542. if (r != '\0' && !G.flag_SIGINT)
  2543. break;
  2544. if (G.flag_SIGINT) {
  2545. /* ^C or SIGINT: repeat */
  2546. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2547. /* kernel prints "^C" itself, just print newline: */
  2548. write(STDOUT_FILENO, "\n", 1);
  2549. G.last_exitcode = 128 | SIGINT;
  2550. }
  2551. }
  2552. return r;
  2553. # endif
  2554. }
  2555. /* This is the magic location that prints prompts
  2556. * and gets data back from the user */
  2557. static int fgetc_interactive(struct in_str *i)
  2558. {
  2559. int ch;
  2560. /* If it's interactive stdin, get new line. */
  2561. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2562. /* Returns first char (or EOF), the rest is in i->p[] */
  2563. ch = get_user_input(i);
  2564. G.promptmode = 1; /* PS2 */
  2565. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2566. } else {
  2567. /* Not stdin: script file, sourced file, etc */
  2568. do ch = hfgetc(i->file); while (ch == '\0');
  2569. }
  2570. return ch;
  2571. }
  2572. #else /* !INTERACTIVE */
  2573. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2574. {
  2575. int ch;
  2576. do ch = hfgetc(i->file); while (ch == '\0');
  2577. return ch;
  2578. }
  2579. #endif /* !INTERACTIVE */
  2580. static int i_getch(struct in_str *i)
  2581. {
  2582. int ch;
  2583. if (!i->file) {
  2584. /* string-based in_str */
  2585. ch = (unsigned char)*i->p;
  2586. if (ch != '\0') {
  2587. i->p++;
  2588. i->last_char = ch;
  2589. #if ENABLE_HUSH_LINENO_VAR
  2590. if (ch == '\n') {
  2591. G.parse_lineno++;
  2592. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2593. }
  2594. #endif
  2595. return ch;
  2596. }
  2597. return EOF;
  2598. }
  2599. /* FILE-based in_str */
  2600. #if ENABLE_FEATURE_EDITING
  2601. /* This can be stdin, check line editing char[] buffer */
  2602. if (i->p && *i->p != '\0') {
  2603. ch = (unsigned char)*i->p++;
  2604. goto out;
  2605. }
  2606. #endif
  2607. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2608. ch = i->peek_buf[0];
  2609. if (ch != 0) {
  2610. int ch2 = i->peek_buf[1];
  2611. i->peek_buf[0] = ch2;
  2612. if (ch2 == 0) /* very likely, avoid redundant write */
  2613. goto out;
  2614. i->peek_buf[1] = 0;
  2615. goto out;
  2616. }
  2617. ch = fgetc_interactive(i);
  2618. out:
  2619. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2620. i->last_char = ch;
  2621. #if ENABLE_HUSH_LINENO_VAR
  2622. if (ch == '\n') {
  2623. G.parse_lineno++;
  2624. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2625. }
  2626. #endif
  2627. return ch;
  2628. }
  2629. static int i_peek(struct in_str *i)
  2630. {
  2631. int ch;
  2632. if (!i->file) {
  2633. /* string-based in_str */
  2634. /* Doesn't report EOF on NUL. None of the callers care. */
  2635. return (unsigned char)*i->p;
  2636. }
  2637. /* FILE-based in_str */
  2638. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2639. /* This can be stdin, check line editing char[] buffer */
  2640. if (i->p && *i->p != '\0')
  2641. return (unsigned char)*i->p;
  2642. #endif
  2643. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2644. ch = i->peek_buf[0];
  2645. if (ch != 0)
  2646. return ch;
  2647. /* Need to get a new char */
  2648. ch = fgetc_interactive(i);
  2649. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2650. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2651. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2652. if (i->p) {
  2653. i->p -= 1;
  2654. return ch;
  2655. }
  2656. #endif
  2657. i->peek_buf[0] = ch;
  2658. /*i->peek_buf[1] = 0; - already is */
  2659. return ch;
  2660. }
  2661. /* Only ever called if i_peek() was called, and did not return EOF.
  2662. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2663. * not end-of-line. Therefore we never need to read a new editing line here.
  2664. */
  2665. static int i_peek2(struct in_str *i)
  2666. {
  2667. int ch;
  2668. /* There are two cases when i->p[] buffer exists.
  2669. * (1) it's a string in_str.
  2670. * (2) It's a file, and we have a saved line editing buffer.
  2671. * In both cases, we know that i->p[0] exists and not NUL, and
  2672. * the peek2 result is in i->p[1].
  2673. */
  2674. if (i->p)
  2675. return (unsigned char)i->p[1];
  2676. /* Now we know it is a file-based in_str. */
  2677. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2678. /* Is there 2nd char? */
  2679. ch = i->peek_buf[1];
  2680. if (ch == 0) {
  2681. /* We did not read it yet, get it now */
  2682. do ch = hfgetc(i->file); while (ch == '\0');
  2683. i->peek_buf[1] = ch;
  2684. }
  2685. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2686. return ch;
  2687. }
  2688. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2689. {
  2690. for (;;) {
  2691. int ch, ch2;
  2692. ch = i_getch(input);
  2693. if (ch != '\\')
  2694. return ch;
  2695. ch2 = i_peek(input);
  2696. if (ch2 != '\n')
  2697. return ch;
  2698. /* backslash+newline, skip it */
  2699. i_getch(input);
  2700. }
  2701. }
  2702. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2703. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2704. */
  2705. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2706. {
  2707. for (;;) {
  2708. int ch, ch2;
  2709. ch = i_peek(input);
  2710. if (ch != '\\')
  2711. return ch;
  2712. ch2 = i_peek2(input);
  2713. if (ch2 != '\n')
  2714. return ch;
  2715. /* backslash+newline, skip it */
  2716. i_getch(input);
  2717. i_getch(input);
  2718. }
  2719. }
  2720. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2721. {
  2722. memset(i, 0, sizeof(*i));
  2723. i->file = fp;
  2724. /* i->p = NULL; */
  2725. }
  2726. static void setup_string_in_str(struct in_str *i, const char *s)
  2727. {
  2728. memset(i, 0, sizeof(*i));
  2729. /*i->file = NULL */;
  2730. i->p = s;
  2731. }
  2732. /*
  2733. * o_string support
  2734. */
  2735. #define B_CHUNK (32 * sizeof(char*))
  2736. static void o_reset_to_empty_unquoted(o_string *o)
  2737. {
  2738. o->length = 0;
  2739. o->has_quoted_part = 0;
  2740. if (o->data)
  2741. o->data[0] = '\0';
  2742. }
  2743. static void o_free_and_set_NULL(o_string *o)
  2744. {
  2745. free(o->data);
  2746. memset(o, 0, sizeof(*o));
  2747. }
  2748. static ALWAYS_INLINE void o_free(o_string *o)
  2749. {
  2750. free(o->data);
  2751. }
  2752. static void o_grow_by(o_string *o, int len)
  2753. {
  2754. if (o->length + len > o->maxlen) {
  2755. o->maxlen += (2 * len) | (B_CHUNK-1);
  2756. o->data = xrealloc(o->data, 1 + o->maxlen);
  2757. }
  2758. }
  2759. static void o_addchr(o_string *o, int ch)
  2760. {
  2761. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2762. if (o->length < o->maxlen) {
  2763. /* likely. avoid o_grow_by() call */
  2764. add:
  2765. o->data[o->length] = ch;
  2766. o->length++;
  2767. o->data[o->length] = '\0';
  2768. return;
  2769. }
  2770. o_grow_by(o, 1);
  2771. goto add;
  2772. }
  2773. #if 0
  2774. /* Valid only if we know o_string is not empty */
  2775. static void o_delchr(o_string *o)
  2776. {
  2777. o->length--;
  2778. o->data[o->length] = '\0';
  2779. }
  2780. #endif
  2781. static void o_addblock(o_string *o, const char *str, int len)
  2782. {
  2783. o_grow_by(o, len);
  2784. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2785. o->length += len;
  2786. }
  2787. static void o_addstr(o_string *o, const char *str)
  2788. {
  2789. o_addblock(o, str, strlen(str));
  2790. }
  2791. static void o_addstr_with_NUL(o_string *o, const char *str)
  2792. {
  2793. o_addblock(o, str, strlen(str) + 1);
  2794. }
  2795. #if !BB_MMU
  2796. static void nommu_addchr(o_string *o, int ch)
  2797. {
  2798. if (o)
  2799. o_addchr(o, ch);
  2800. }
  2801. #else
  2802. # define nommu_addchr(o, str) ((void)0)
  2803. #endif
  2804. #if ENABLE_HUSH_MODE_X
  2805. static void x_mode_addchr(int ch)
  2806. {
  2807. o_addchr(&G.x_mode_buf, ch);
  2808. }
  2809. static void x_mode_addstr(const char *str)
  2810. {
  2811. o_addstr(&G.x_mode_buf, str);
  2812. }
  2813. static void x_mode_addblock(const char *str, int len)
  2814. {
  2815. o_addblock(&G.x_mode_buf, str, len);
  2816. }
  2817. static void x_mode_prefix(void)
  2818. {
  2819. int n = G.x_mode_depth;
  2820. do x_mode_addchr('+'); while (--n >= 0);
  2821. }
  2822. static void x_mode_flush(void)
  2823. {
  2824. int len = G.x_mode_buf.length;
  2825. if (len <= 0)
  2826. return;
  2827. if (G.x_mode_fd > 0) {
  2828. G.x_mode_buf.data[len] = '\n';
  2829. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2830. }
  2831. G.x_mode_buf.length = 0;
  2832. }
  2833. #endif
  2834. /*
  2835. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2836. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2837. * Apparently, on unquoted $v bash still does globbing
  2838. * ("v='*.txt'; echo $v" prints all .txt files),
  2839. * but NOT brace expansion! Thus, there should be TWO independent
  2840. * quoting mechanisms on $v expansion side: one protects
  2841. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2842. * We have only second one.
  2843. */
  2844. #if ENABLE_HUSH_BRACE_EXPANSION
  2845. # define MAYBE_BRACES "{}"
  2846. #else
  2847. # define MAYBE_BRACES ""
  2848. #endif
  2849. /* My analysis of quoting semantics tells me that state information
  2850. * is associated with a destination, not a source.
  2851. */
  2852. static void o_addqchr(o_string *o, int ch)
  2853. {
  2854. int sz = 1;
  2855. /* '-' is included because of this case:
  2856. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2857. */
  2858. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2859. if (found)
  2860. sz++;
  2861. o_grow_by(o, sz);
  2862. if (found) {
  2863. o->data[o->length] = '\\';
  2864. o->length++;
  2865. }
  2866. o->data[o->length] = ch;
  2867. o->length++;
  2868. o->data[o->length] = '\0';
  2869. }
  2870. static void o_addQchr(o_string *o, int ch)
  2871. {
  2872. int sz = 1;
  2873. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2874. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2875. ) {
  2876. sz++;
  2877. o->data[o->length] = '\\';
  2878. o->length++;
  2879. }
  2880. o_grow_by(o, sz);
  2881. o->data[o->length] = ch;
  2882. o->length++;
  2883. o->data[o->length] = '\0';
  2884. }
  2885. static void o_addqblock(o_string *o, const char *str, int len)
  2886. {
  2887. while (len) {
  2888. char ch;
  2889. int sz;
  2890. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2891. if (ordinary_cnt > len) /* paranoia */
  2892. ordinary_cnt = len;
  2893. o_addblock(o, str, ordinary_cnt);
  2894. if (ordinary_cnt == len)
  2895. return; /* NUL is already added by o_addblock */
  2896. str += ordinary_cnt;
  2897. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2898. ch = *str++;
  2899. sz = 1;
  2900. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2901. sz++;
  2902. o->data[o->length] = '\\';
  2903. o->length++;
  2904. }
  2905. o_grow_by(o, sz);
  2906. o->data[o->length] = ch;
  2907. o->length++;
  2908. }
  2909. o->data[o->length] = '\0';
  2910. }
  2911. static void o_addQblock(o_string *o, const char *str, int len)
  2912. {
  2913. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2914. o_addblock(o, str, len);
  2915. return;
  2916. }
  2917. o_addqblock(o, str, len);
  2918. }
  2919. static void o_addQstr(o_string *o, const char *str)
  2920. {
  2921. o_addQblock(o, str, strlen(str));
  2922. }
  2923. /* A special kind of o_string for $VAR and `cmd` expansion.
  2924. * It contains char* list[] at the beginning, which is grown in 16 element
  2925. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2926. * list[i] contains an INDEX (int!) into this string data.
  2927. * It means that if list[] needs to grow, data needs to be moved higher up
  2928. * but list[i]'s need not be modified.
  2929. * NB: remembering how many list[i]'s you have there is crucial.
  2930. * o_finalize_list() operation post-processes this structure - calculates
  2931. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2932. */
  2933. #if DEBUG_EXPAND || DEBUG_GLOB
  2934. static void debug_print_list(const char *prefix, o_string *o, int n)
  2935. {
  2936. char **list = (char**)o->data;
  2937. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2938. int i = 0;
  2939. indent();
  2940. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2941. prefix, list, n, string_start, o->length, o->maxlen,
  2942. !!(o->o_expflags & EXP_FLAG_GLOB),
  2943. o->has_quoted_part,
  2944. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2945. while (i < n) {
  2946. indent();
  2947. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2948. o->data + (int)(uintptr_t)list[i] + string_start,
  2949. o->data + (int)(uintptr_t)list[i] + string_start);
  2950. i++;
  2951. }
  2952. if (n) {
  2953. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2954. indent();
  2955. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2956. }
  2957. }
  2958. #else
  2959. # define debug_print_list(prefix, o, n) ((void)0)
  2960. #endif
  2961. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2962. * in list[n] so that it points past last stored byte so far.
  2963. * It returns n+1. */
  2964. static int o_save_ptr_helper(o_string *o, int n)
  2965. {
  2966. char **list = (char**)o->data;
  2967. int string_start;
  2968. int string_len;
  2969. if (!o->has_empty_slot) {
  2970. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2971. string_len = o->length - string_start;
  2972. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2973. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2974. /* list[n] points to string_start, make space for 16 more pointers */
  2975. o->maxlen += 0x10 * sizeof(list[0]);
  2976. o->data = xrealloc(o->data, o->maxlen + 1);
  2977. list = (char**)o->data;
  2978. memmove(list + n + 0x10, list + n, string_len);
  2979. /*
  2980. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2981. * check. (grep for -prev-ifs-check-).
  2982. * Ensure that argv[-1][last] is not garbage
  2983. * but zero bytes, to save index check there.
  2984. */
  2985. list[n + 0x10 - 1] = 0;
  2986. o->length += 0x10 * sizeof(list[0]);
  2987. } else {
  2988. debug_printf_list("list[%d]=%d string_start=%d\n",
  2989. n, string_len, string_start);
  2990. }
  2991. } else {
  2992. /* We have empty slot at list[n], reuse without growth */
  2993. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2994. string_len = o->length - string_start;
  2995. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2996. n, string_len, string_start);
  2997. o->has_empty_slot = 0;
  2998. }
  2999. o->has_quoted_part = 0;
  3000. list[n] = (char*)(uintptr_t)string_len;
  3001. return n + 1;
  3002. }
  3003. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  3004. static int o_get_last_ptr(o_string *o, int n)
  3005. {
  3006. char **list = (char**)o->data;
  3007. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3008. return ((int)(uintptr_t)list[n-1]) + string_start;
  3009. }
  3010. /*
  3011. * Globbing routines.
  3012. *
  3013. * Most words in commands need to be globbed, even ones which are
  3014. * (single or double) quoted. This stems from the possiblity of
  3015. * constructs like "abc"* and 'abc'* - these should be globbed.
  3016. * Having a different code path for fully-quoted strings ("abc",
  3017. * 'abc') would only help performance-wise, but we still need
  3018. * code for partially-quoted strings.
  3019. *
  3020. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3021. * the logic can't be "shell-syntax argument is first transformed
  3022. * to a string, then globbed, and if globbing does not match anything,
  3023. * it is used verbatim". Here are two examples where it fails:
  3024. *
  3025. * echo 'b\*'?
  3026. *
  3027. * The globbing can't be avoided (because of '?' at the end).
  3028. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3029. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3030. * - IOW: they "unbackslash" the glob pattern.
  3031. * Now, look at this:
  3032. *
  3033. * v='\\\*'; echo b$v?
  3034. *
  3035. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3036. * should be used as glob pattern with no changes. However, if glob
  3037. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3038. *
  3039. * ash implements this by having an encoded representation of the word
  3040. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3041. * Glob pattern is derived from it. If glob fails, the decision what result
  3042. * should be is made using that encoded representation. Not glob pattern.
  3043. */
  3044. #if ENABLE_HUSH_BRACE_EXPANSION
  3045. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3046. * first, it processes even {a} (no commas), second,
  3047. * I didn't manage to make it return strings when they don't match
  3048. * existing files. Need to re-implement it.
  3049. */
  3050. /* Helper */
  3051. static int glob_needed(const char *s)
  3052. {
  3053. while (*s) {
  3054. if (*s == '\\') {
  3055. if (!s[1])
  3056. return 0;
  3057. s += 2;
  3058. continue;
  3059. }
  3060. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3061. return 1;
  3062. s++;
  3063. }
  3064. return 0;
  3065. }
  3066. /* Return pointer to next closing brace or to comma */
  3067. static const char *next_brace_sub(const char *cp)
  3068. {
  3069. unsigned depth = 0;
  3070. cp++;
  3071. while (*cp != '\0') {
  3072. if (*cp == '\\') {
  3073. if (*++cp == '\0')
  3074. break;
  3075. cp++;
  3076. continue;
  3077. }
  3078. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3079. break;
  3080. if (*cp++ == '{')
  3081. depth++;
  3082. }
  3083. return *cp != '\0' ? cp : NULL;
  3084. }
  3085. /* Recursive brace globber. Note: may garble pattern[]. */
  3086. static int glob_brace(char *pattern, o_string *o, int n)
  3087. {
  3088. char *new_pattern_buf;
  3089. const char *begin;
  3090. const char *next;
  3091. const char *rest;
  3092. const char *p;
  3093. size_t rest_len;
  3094. debug_printf_glob("glob_brace('%s')\n", pattern);
  3095. begin = pattern;
  3096. while (1) {
  3097. if (*begin == '\0')
  3098. goto simple_glob;
  3099. if (*begin == '{') {
  3100. /* Find the first sub-pattern and at the same time
  3101. * find the rest after the closing brace */
  3102. next = next_brace_sub(begin);
  3103. if (next == NULL) {
  3104. /* An illegal expression */
  3105. goto simple_glob;
  3106. }
  3107. if (*next == '}') {
  3108. /* "{abc}" with no commas - illegal
  3109. * brace expr, disregard and skip it */
  3110. begin = next + 1;
  3111. continue;
  3112. }
  3113. break;
  3114. }
  3115. if (*begin == '\\' && begin[1] != '\0')
  3116. begin++;
  3117. begin++;
  3118. }
  3119. debug_printf_glob("begin:%s\n", begin);
  3120. debug_printf_glob("next:%s\n", next);
  3121. /* Now find the end of the whole brace expression */
  3122. rest = next;
  3123. while (*rest != '}') {
  3124. rest = next_brace_sub(rest);
  3125. if (rest == NULL) {
  3126. /* An illegal expression */
  3127. goto simple_glob;
  3128. }
  3129. debug_printf_glob("rest:%s\n", rest);
  3130. }
  3131. rest_len = strlen(++rest) + 1;
  3132. /* We are sure the brace expression is well-formed */
  3133. /* Allocate working buffer large enough for our work */
  3134. new_pattern_buf = xmalloc(strlen(pattern));
  3135. /* We have a brace expression. BEGIN points to the opening {,
  3136. * NEXT points past the terminator of the first element, and REST
  3137. * points past the final }. We will accumulate result names from
  3138. * recursive runs for each brace alternative in the buffer using
  3139. * GLOB_APPEND. */
  3140. p = begin + 1;
  3141. while (1) {
  3142. /* Construct the new glob expression */
  3143. memcpy(
  3144. mempcpy(
  3145. mempcpy(new_pattern_buf,
  3146. /* We know the prefix for all sub-patterns */
  3147. pattern, begin - pattern),
  3148. p, next - p),
  3149. rest, rest_len);
  3150. /* Note: glob_brace() may garble new_pattern_buf[].
  3151. * That's why we re-copy prefix every time (1st memcpy above).
  3152. */
  3153. n = glob_brace(new_pattern_buf, o, n);
  3154. if (*next == '}') {
  3155. /* We saw the last entry */
  3156. break;
  3157. }
  3158. p = next + 1;
  3159. next = next_brace_sub(next);
  3160. }
  3161. free(new_pattern_buf);
  3162. return n;
  3163. simple_glob:
  3164. {
  3165. int gr;
  3166. glob_t globdata;
  3167. memset(&globdata, 0, sizeof(globdata));
  3168. gr = glob(pattern, 0, NULL, &globdata);
  3169. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3170. if (gr != 0) {
  3171. if (gr == GLOB_NOMATCH) {
  3172. globfree(&globdata);
  3173. /* NB: garbles parameter */
  3174. unbackslash(pattern);
  3175. o_addstr_with_NUL(o, pattern);
  3176. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3177. return o_save_ptr_helper(o, n);
  3178. }
  3179. if (gr == GLOB_NOSPACE)
  3180. bb_die_memory_exhausted();
  3181. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3182. * but we didn't specify it. Paranoia again. */
  3183. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3184. }
  3185. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3186. char **argv = globdata.gl_pathv;
  3187. while (1) {
  3188. o_addstr_with_NUL(o, *argv);
  3189. n = o_save_ptr_helper(o, n);
  3190. argv++;
  3191. if (!*argv)
  3192. break;
  3193. }
  3194. }
  3195. globfree(&globdata);
  3196. }
  3197. return n;
  3198. }
  3199. /* Performs globbing on last list[],
  3200. * saving each result as a new list[].
  3201. */
  3202. static int perform_glob(o_string *o, int n)
  3203. {
  3204. char *pattern, *copy;
  3205. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3206. if (!o->data)
  3207. return o_save_ptr_helper(o, n);
  3208. pattern = o->data + o_get_last_ptr(o, n);
  3209. debug_printf_glob("glob pattern '%s'\n", pattern);
  3210. if (!glob_needed(pattern)) {
  3211. /* unbackslash last string in o in place, fix length */
  3212. o->length = unbackslash(pattern) - o->data;
  3213. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3214. return o_save_ptr_helper(o, n);
  3215. }
  3216. copy = xstrdup(pattern);
  3217. /* "forget" pattern in o */
  3218. o->length = pattern - o->data;
  3219. n = glob_brace(copy, o, n);
  3220. free(copy);
  3221. if (DEBUG_GLOB)
  3222. debug_print_list("perform_glob returning", o, n);
  3223. return n;
  3224. }
  3225. #else /* !HUSH_BRACE_EXPANSION */
  3226. /* Helper */
  3227. static int glob_needed(const char *s)
  3228. {
  3229. while (*s) {
  3230. if (*s == '\\') {
  3231. if (!s[1])
  3232. return 0;
  3233. s += 2;
  3234. continue;
  3235. }
  3236. if (*s == '*' || *s == '[' || *s == '?')
  3237. return 1;
  3238. s++;
  3239. }
  3240. return 0;
  3241. }
  3242. /* Performs globbing on last list[],
  3243. * saving each result as a new list[].
  3244. */
  3245. static int perform_glob(o_string *o, int n)
  3246. {
  3247. glob_t globdata;
  3248. int gr;
  3249. char *pattern;
  3250. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3251. if (!o->data)
  3252. return o_save_ptr_helper(o, n);
  3253. pattern = o->data + o_get_last_ptr(o, n);
  3254. debug_printf_glob("glob pattern '%s'\n", pattern);
  3255. if (!glob_needed(pattern)) {
  3256. literal:
  3257. /* unbackslash last string in o in place, fix length */
  3258. o->length = unbackslash(pattern) - o->data;
  3259. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3260. return o_save_ptr_helper(o, n);
  3261. }
  3262. memset(&globdata, 0, sizeof(globdata));
  3263. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3264. * If we glob "*.\*" and don't find anything, we need
  3265. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3266. * will return "*.\*"!
  3267. */
  3268. gr = glob(pattern, 0, NULL, &globdata);
  3269. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3270. if (gr != 0) {
  3271. if (gr == GLOB_NOMATCH) {
  3272. globfree(&globdata);
  3273. goto literal;
  3274. }
  3275. if (gr == GLOB_NOSPACE)
  3276. bb_die_memory_exhausted();
  3277. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3278. * but we didn't specify it. Paranoia again. */
  3279. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3280. }
  3281. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3282. char **argv = globdata.gl_pathv;
  3283. /* "forget" pattern in o */
  3284. o->length = pattern - o->data;
  3285. while (1) {
  3286. o_addstr_with_NUL(o, *argv);
  3287. n = o_save_ptr_helper(o, n);
  3288. argv++;
  3289. if (!*argv)
  3290. break;
  3291. }
  3292. }
  3293. globfree(&globdata);
  3294. if (DEBUG_GLOB)
  3295. debug_print_list("perform_glob returning", o, n);
  3296. return n;
  3297. }
  3298. #endif /* !HUSH_BRACE_EXPANSION */
  3299. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3300. * Otherwise, just finish current list[] and start new */
  3301. static int o_save_ptr(o_string *o, int n)
  3302. {
  3303. if (o->o_expflags & EXP_FLAG_GLOB) {
  3304. /* If o->has_empty_slot, list[n] was already globbed
  3305. * (if it was requested back then when it was filled)
  3306. * so don't do that again! */
  3307. if (!o->has_empty_slot)
  3308. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3309. }
  3310. return o_save_ptr_helper(o, n);
  3311. }
  3312. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3313. static char **o_finalize_list(o_string *o, int n)
  3314. {
  3315. char **list;
  3316. int string_start;
  3317. if (DEBUG_EXPAND)
  3318. debug_print_list("finalized", o, n);
  3319. debug_printf_expand("finalized n:%d\n", n);
  3320. list = (char**)o->data;
  3321. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3322. list[--n] = NULL;
  3323. while (n) {
  3324. n--;
  3325. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3326. }
  3327. return list;
  3328. }
  3329. static void free_pipe_list(struct pipe *pi);
  3330. /* Returns pi->next - next pipe in the list */
  3331. static struct pipe *free_pipe(struct pipe *pi)
  3332. {
  3333. struct pipe *next;
  3334. int i;
  3335. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3336. for (i = 0; i < pi->num_cmds; i++) {
  3337. struct command *command;
  3338. struct redir_struct *r, *rnext;
  3339. command = &pi->cmds[i];
  3340. debug_printf_clean(" command %d:\n", i);
  3341. if (command->argv) {
  3342. if (DEBUG_CLEAN) {
  3343. int a;
  3344. char **p;
  3345. for (a = 0, p = command->argv; *p; a++, p++) {
  3346. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3347. }
  3348. }
  3349. free_strings(command->argv);
  3350. //command->argv = NULL;
  3351. }
  3352. /* not "else if": on syntax error, we may have both! */
  3353. if (command->group) {
  3354. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3355. command->cmd_type);
  3356. free_pipe_list(command->group);
  3357. debug_printf_clean(" end group\n");
  3358. //command->group = NULL;
  3359. }
  3360. /* else is crucial here.
  3361. * If group != NULL, child_func is meaningless */
  3362. #if ENABLE_HUSH_FUNCTIONS
  3363. else if (command->child_func) {
  3364. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3365. command->child_func->parent_cmd = NULL;
  3366. }
  3367. #endif
  3368. #if !BB_MMU
  3369. free(command->group_as_string);
  3370. //command->group_as_string = NULL;
  3371. #endif
  3372. for (r = command->redirects; r; r = rnext) {
  3373. debug_printf_clean(" redirect %d%s",
  3374. r->rd_fd, redir_table[r->rd_type].descrip);
  3375. /* guard against the case >$FOO, where foo is unset or blank */
  3376. if (r->rd_filename) {
  3377. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3378. free(r->rd_filename);
  3379. //r->rd_filename = NULL;
  3380. }
  3381. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3382. rnext = r->next;
  3383. free(r);
  3384. }
  3385. //command->redirects = NULL;
  3386. }
  3387. free(pi->cmds); /* children are an array, they get freed all at once */
  3388. //pi->cmds = NULL;
  3389. #if ENABLE_HUSH_JOB
  3390. free(pi->cmdtext);
  3391. //pi->cmdtext = NULL;
  3392. #endif
  3393. next = pi->next;
  3394. free(pi);
  3395. return next;
  3396. }
  3397. static void free_pipe_list(struct pipe *pi)
  3398. {
  3399. while (pi) {
  3400. #if HAS_KEYWORDS
  3401. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3402. #endif
  3403. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3404. pi = free_pipe(pi);
  3405. }
  3406. }
  3407. /*** Parsing routines ***/
  3408. #ifndef debug_print_tree
  3409. static void debug_print_tree(struct pipe *pi, int lvl)
  3410. {
  3411. static const char *const PIPE[] = {
  3412. [PIPE_SEQ] = "SEQ",
  3413. [PIPE_AND] = "AND",
  3414. [PIPE_OR ] = "OR" ,
  3415. [PIPE_BG ] = "BG" ,
  3416. };
  3417. static const char *RES[] = {
  3418. [RES_NONE ] = "NONE" ,
  3419. # if ENABLE_HUSH_IF
  3420. [RES_IF ] = "IF" ,
  3421. [RES_THEN ] = "THEN" ,
  3422. [RES_ELIF ] = "ELIF" ,
  3423. [RES_ELSE ] = "ELSE" ,
  3424. [RES_FI ] = "FI" ,
  3425. # endif
  3426. # if ENABLE_HUSH_LOOPS
  3427. [RES_FOR ] = "FOR" ,
  3428. [RES_WHILE] = "WHILE",
  3429. [RES_UNTIL] = "UNTIL",
  3430. [RES_DO ] = "DO" ,
  3431. [RES_DONE ] = "DONE" ,
  3432. # endif
  3433. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3434. [RES_IN ] = "IN" ,
  3435. # endif
  3436. # if ENABLE_HUSH_CASE
  3437. [RES_CASE ] = "CASE" ,
  3438. [RES_CASE_IN ] = "CASE_IN" ,
  3439. [RES_MATCH] = "MATCH",
  3440. [RES_CASE_BODY] = "CASE_BODY",
  3441. [RES_ESAC ] = "ESAC" ,
  3442. # endif
  3443. [RES_XXXX ] = "XXXX" ,
  3444. [RES_SNTX ] = "SNTX" ,
  3445. };
  3446. static const char *const CMDTYPE[] = {
  3447. "{}",
  3448. "()",
  3449. "[noglob]",
  3450. # if ENABLE_HUSH_FUNCTIONS
  3451. "func()",
  3452. # endif
  3453. };
  3454. int pin, prn;
  3455. pin = 0;
  3456. while (pi) {
  3457. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3458. lvl*2, "",
  3459. pin,
  3460. pi->num_cmds,
  3461. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3462. RES[pi->res_word],
  3463. pi->followup, PIPE[pi->followup]
  3464. );
  3465. prn = 0;
  3466. while (prn < pi->num_cmds) {
  3467. struct command *command = &pi->cmds[prn];
  3468. char **argv = command->argv;
  3469. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3470. lvl*2, "", prn,
  3471. command->assignment_cnt);
  3472. # if ENABLE_HUSH_LINENO_VAR
  3473. fdprintf(2, " LINENO:%u", command->lineno);
  3474. # endif
  3475. if (command->group) {
  3476. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3477. CMDTYPE[command->cmd_type],
  3478. argv
  3479. # if !BB_MMU
  3480. , " group_as_string:", command->group_as_string
  3481. # else
  3482. , "", ""
  3483. # endif
  3484. );
  3485. debug_print_tree(command->group, lvl+1);
  3486. prn++;
  3487. continue;
  3488. }
  3489. if (argv) while (*argv) {
  3490. fdprintf(2, " '%s'", *argv);
  3491. argv++;
  3492. }
  3493. if (command->redirects)
  3494. fdprintf(2, " {redir}");
  3495. fdprintf(2, "\n");
  3496. prn++;
  3497. }
  3498. pi = pi->next;
  3499. pin++;
  3500. }
  3501. }
  3502. #endif /* debug_print_tree */
  3503. static struct pipe *new_pipe(void)
  3504. {
  3505. struct pipe *pi;
  3506. pi = xzalloc(sizeof(struct pipe));
  3507. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3508. return pi;
  3509. }
  3510. /* Command (member of a pipe) is complete, or we start a new pipe
  3511. * if ctx->command is NULL.
  3512. * No errors possible here.
  3513. */
  3514. static int done_command(struct parse_context *ctx)
  3515. {
  3516. /* The command is really already in the pipe structure, so
  3517. * advance the pipe counter and make a new, null command. */
  3518. struct pipe *pi = ctx->pipe;
  3519. struct command *command = ctx->command;
  3520. #if 0 /* Instead we emit error message at run time */
  3521. if (ctx->pending_redirect) {
  3522. /* For example, "cmd >" (no filename to redirect to) */
  3523. syntax_error("invalid redirect");
  3524. ctx->pending_redirect = NULL;
  3525. }
  3526. #endif
  3527. if (command) {
  3528. if (IS_NULL_CMD(command)) {
  3529. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3530. goto clear_and_ret;
  3531. }
  3532. pi->num_cmds++;
  3533. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3534. //debug_print_tree(ctx->list_head, 20);
  3535. } else {
  3536. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3537. }
  3538. /* Only real trickiness here is that the uncommitted
  3539. * command structure is not counted in pi->num_cmds. */
  3540. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3541. ctx->command = command = &pi->cmds[pi->num_cmds];
  3542. clear_and_ret:
  3543. memset(command, 0, sizeof(*command));
  3544. #if ENABLE_HUSH_LINENO_VAR
  3545. command->lineno = G.parse_lineno;
  3546. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3547. #endif
  3548. return pi->num_cmds; /* used only for 0/nonzero check */
  3549. }
  3550. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3551. {
  3552. int not_null;
  3553. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3554. /* Close previous command */
  3555. not_null = done_command(ctx);
  3556. #if HAS_KEYWORDS
  3557. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3558. ctx->ctx_inverted = 0;
  3559. ctx->pipe->res_word = ctx->ctx_res_w;
  3560. #endif
  3561. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3562. /* Necessary since && and || have precedence over &:
  3563. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3564. * in a backgrounded subshell.
  3565. */
  3566. struct pipe *pi;
  3567. struct command *command;
  3568. /* Is this actually this construct, all pipes end with && or ||? */
  3569. pi = ctx->list_head;
  3570. while (pi != ctx->pipe) {
  3571. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3572. goto no_conv;
  3573. pi = pi->next;
  3574. }
  3575. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3576. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3577. pi = xzalloc(sizeof(*pi));
  3578. pi->followup = PIPE_BG;
  3579. pi->num_cmds = 1;
  3580. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3581. command = &pi->cmds[0];
  3582. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3583. command->cmd_type = CMD_NORMAL;
  3584. command->group = ctx->list_head;
  3585. #if !BB_MMU
  3586. command->group_as_string = xstrndup(
  3587. ctx->as_string.data,
  3588. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3589. );
  3590. #endif
  3591. /* Replace all pipes in ctx with one newly created */
  3592. ctx->list_head = ctx->pipe = pi;
  3593. /* for cases like "cmd && &", do not be tricked by last command
  3594. * being null - the entire {...} & is NOT null! */
  3595. not_null = 1;
  3596. } else {
  3597. no_conv:
  3598. ctx->pipe->followup = type;
  3599. }
  3600. /* Without this check, even just <enter> on command line generates
  3601. * tree of three NOPs (!). Which is harmless but annoying.
  3602. * IOW: it is safe to do it unconditionally. */
  3603. if (not_null
  3604. #if ENABLE_HUSH_IF
  3605. || ctx->ctx_res_w == RES_FI
  3606. #endif
  3607. #if ENABLE_HUSH_LOOPS
  3608. || ctx->ctx_res_w == RES_DONE
  3609. || ctx->ctx_res_w == RES_FOR
  3610. || ctx->ctx_res_w == RES_IN
  3611. #endif
  3612. #if ENABLE_HUSH_CASE
  3613. || ctx->ctx_res_w == RES_ESAC
  3614. #endif
  3615. ) {
  3616. struct pipe *new_p;
  3617. debug_printf_parse("done_pipe: adding new pipe: "
  3618. "not_null:%d ctx->ctx_res_w:%d\n",
  3619. not_null, ctx->ctx_res_w);
  3620. new_p = new_pipe();
  3621. ctx->pipe->next = new_p;
  3622. ctx->pipe = new_p;
  3623. /* RES_THEN, RES_DO etc are "sticky" -
  3624. * they remain set for pipes inside if/while.
  3625. * This is used to control execution.
  3626. * RES_FOR and RES_IN are NOT sticky (needed to support
  3627. * cases where variable or value happens to match a keyword):
  3628. */
  3629. #if ENABLE_HUSH_LOOPS
  3630. if (ctx->ctx_res_w == RES_FOR
  3631. || ctx->ctx_res_w == RES_IN)
  3632. ctx->ctx_res_w = RES_NONE;
  3633. #endif
  3634. #if ENABLE_HUSH_CASE
  3635. if (ctx->ctx_res_w == RES_MATCH)
  3636. ctx->ctx_res_w = RES_CASE_BODY;
  3637. if (ctx->ctx_res_w == RES_CASE)
  3638. ctx->ctx_res_w = RES_CASE_IN;
  3639. #endif
  3640. ctx->command = NULL; /* trick done_command below */
  3641. /* Create the memory for command, roughly:
  3642. * ctx->pipe->cmds = new struct command;
  3643. * ctx->command = &ctx->pipe->cmds[0];
  3644. */
  3645. done_command(ctx);
  3646. //debug_print_tree(ctx->list_head, 10);
  3647. }
  3648. debug_printf_parse("done_pipe return\n");
  3649. }
  3650. static void initialize_context(struct parse_context *ctx)
  3651. {
  3652. memset(ctx, 0, sizeof(*ctx));
  3653. if (MAYBE_ASSIGNMENT != 0)
  3654. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3655. ctx->pipe = ctx->list_head = new_pipe();
  3656. /* Create the memory for command, roughly:
  3657. * ctx->pipe->cmds = new struct command;
  3658. * ctx->command = &ctx->pipe->cmds[0];
  3659. */
  3660. done_command(ctx);
  3661. }
  3662. /* If a reserved word is found and processed, parse context is modified
  3663. * and 1 is returned.
  3664. */
  3665. #if HAS_KEYWORDS
  3666. struct reserved_combo {
  3667. char literal[6];
  3668. unsigned char res;
  3669. unsigned char assignment_flag;
  3670. uint32_t flag;
  3671. };
  3672. enum {
  3673. FLAG_END = (1 << RES_NONE ),
  3674. # if ENABLE_HUSH_IF
  3675. FLAG_IF = (1 << RES_IF ),
  3676. FLAG_THEN = (1 << RES_THEN ),
  3677. FLAG_ELIF = (1 << RES_ELIF ),
  3678. FLAG_ELSE = (1 << RES_ELSE ),
  3679. FLAG_FI = (1 << RES_FI ),
  3680. # endif
  3681. # if ENABLE_HUSH_LOOPS
  3682. FLAG_FOR = (1 << RES_FOR ),
  3683. FLAG_WHILE = (1 << RES_WHILE),
  3684. FLAG_UNTIL = (1 << RES_UNTIL),
  3685. FLAG_DO = (1 << RES_DO ),
  3686. FLAG_DONE = (1 << RES_DONE ),
  3687. FLAG_IN = (1 << RES_IN ),
  3688. # endif
  3689. # if ENABLE_HUSH_CASE
  3690. FLAG_MATCH = (1 << RES_MATCH),
  3691. FLAG_ESAC = (1 << RES_ESAC ),
  3692. # endif
  3693. FLAG_START = (1 << RES_XXXX ),
  3694. };
  3695. static const struct reserved_combo* match_reserved_word(o_string *word)
  3696. {
  3697. /* Mostly a list of accepted follow-up reserved words.
  3698. * FLAG_END means we are done with the sequence, and are ready
  3699. * to turn the compound list into a command.
  3700. * FLAG_START means the word must start a new compound list.
  3701. */
  3702. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3703. # if ENABLE_HUSH_IF
  3704. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3705. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3706. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3707. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3708. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3709. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3710. # endif
  3711. # if ENABLE_HUSH_LOOPS
  3712. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3713. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3714. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3715. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3716. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3717. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3718. # endif
  3719. # if ENABLE_HUSH_CASE
  3720. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3721. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3722. # endif
  3723. };
  3724. const struct reserved_combo *r;
  3725. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3726. if (strcmp(word->data, r->literal) == 0)
  3727. return r;
  3728. }
  3729. return NULL;
  3730. }
  3731. /* Return NULL: not a keyword, else: keyword
  3732. */
  3733. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3734. {
  3735. # if ENABLE_HUSH_CASE
  3736. static const struct reserved_combo reserved_match = {
  3737. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3738. };
  3739. # endif
  3740. const struct reserved_combo *r;
  3741. if (ctx->word.has_quoted_part)
  3742. return 0;
  3743. r = match_reserved_word(&ctx->word);
  3744. if (!r)
  3745. return r; /* NULL */
  3746. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3747. # if ENABLE_HUSH_CASE
  3748. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3749. /* "case word IN ..." - IN part starts first MATCH part */
  3750. r = &reserved_match;
  3751. } else
  3752. # endif
  3753. if (r->flag == 0) { /* '!' */
  3754. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3755. syntax_error("! ! command");
  3756. ctx->ctx_res_w = RES_SNTX;
  3757. }
  3758. ctx->ctx_inverted = 1;
  3759. return r;
  3760. }
  3761. if (r->flag & FLAG_START) {
  3762. struct parse_context *old;
  3763. old = xmemdup(ctx, sizeof(*ctx));
  3764. debug_printf_parse("push stack %p\n", old);
  3765. initialize_context(ctx);
  3766. ctx->stack = old;
  3767. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3768. syntax_error_at(ctx->word.data);
  3769. ctx->ctx_res_w = RES_SNTX;
  3770. return r;
  3771. } else {
  3772. /* "{...} fi" is ok. "{...} if" is not
  3773. * Example:
  3774. * if { echo foo; } then { echo bar; } fi */
  3775. if (ctx->command->group)
  3776. done_pipe(ctx, PIPE_SEQ);
  3777. }
  3778. ctx->ctx_res_w = r->res;
  3779. ctx->old_flag = r->flag;
  3780. ctx->is_assignment = r->assignment_flag;
  3781. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3782. if (ctx->old_flag & FLAG_END) {
  3783. struct parse_context *old;
  3784. done_pipe(ctx, PIPE_SEQ);
  3785. debug_printf_parse("pop stack %p\n", ctx->stack);
  3786. old = ctx->stack;
  3787. old->command->group = ctx->list_head;
  3788. old->command->cmd_type = CMD_NORMAL;
  3789. # if !BB_MMU
  3790. /* At this point, the compound command's string is in
  3791. * ctx->as_string... except for the leading keyword!
  3792. * Consider this example: "echo a | if true; then echo a; fi"
  3793. * ctx->as_string will contain "true; then echo a; fi",
  3794. * with "if " remaining in old->as_string!
  3795. */
  3796. {
  3797. char *str;
  3798. int len = old->as_string.length;
  3799. /* Concatenate halves */
  3800. o_addstr(&old->as_string, ctx->as_string.data);
  3801. o_free(&ctx->as_string);
  3802. /* Find where leading keyword starts in first half */
  3803. str = old->as_string.data + len;
  3804. if (str > old->as_string.data)
  3805. str--; /* skip whitespace after keyword */
  3806. while (str > old->as_string.data && isalpha(str[-1]))
  3807. str--;
  3808. /* Ugh, we're done with this horrid hack */
  3809. old->command->group_as_string = xstrdup(str);
  3810. debug_printf_parse("pop, remembering as:'%s'\n",
  3811. old->command->group_as_string);
  3812. }
  3813. # endif
  3814. *ctx = *old; /* physical copy */
  3815. free(old);
  3816. }
  3817. return r;
  3818. }
  3819. #endif /* HAS_KEYWORDS */
  3820. /* Word is complete, look at it and update parsing context.
  3821. * Normal return is 0. Syntax errors return 1.
  3822. * Note: on return, word is reset, but not o_free'd!
  3823. */
  3824. static int done_word(struct parse_context *ctx)
  3825. {
  3826. struct command *command = ctx->command;
  3827. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3828. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3829. debug_printf_parse("done_word return 0: true null, ignored\n");
  3830. return 0;
  3831. }
  3832. if (ctx->pending_redirect) {
  3833. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3834. * only if run as "bash", not "sh" */
  3835. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3836. * "2.7 Redirection
  3837. * If the redirection operator is "<<" or "<<-", the word
  3838. * that follows the redirection operator shall be
  3839. * subjected to quote removal; it is unspecified whether
  3840. * any of the other expansions occur. For the other
  3841. * redirection operators, the word that follows the
  3842. * redirection operator shall be subjected to tilde
  3843. * expansion, parameter expansion, command substitution,
  3844. * arithmetic expansion, and quote removal.
  3845. * Pathname expansion shall not be performed
  3846. * on the word by a non-interactive shell; an interactive
  3847. * shell may perform it, but shall do so only when
  3848. * the expansion would result in one word."
  3849. */
  3850. //bash does not do parameter/command substitution or arithmetic expansion
  3851. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3852. // as written:
  3853. // <<EOF$t
  3854. // <<EOF$((1))
  3855. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3856. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3857. /* Cater for >\file case:
  3858. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3859. * Same with heredocs:
  3860. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3861. */
  3862. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3863. unbackslash(ctx->pending_redirect->rd_filename);
  3864. /* Is it <<"HEREDOC"? */
  3865. if (ctx->word.has_quoted_part) {
  3866. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3867. }
  3868. }
  3869. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3870. ctx->pending_redirect = NULL;
  3871. } else {
  3872. #if HAS_KEYWORDS
  3873. # if ENABLE_HUSH_CASE
  3874. if (ctx->ctx_dsemicolon
  3875. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3876. ) {
  3877. /* already done when ctx_dsemicolon was set to 1: */
  3878. /* ctx->ctx_res_w = RES_MATCH; */
  3879. ctx->ctx_dsemicolon = 0;
  3880. } else
  3881. # endif
  3882. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3883. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3884. && strcmp(ctx->word.data, "]]") == 0
  3885. ) {
  3886. /* allow "[[ ]] >file" etc */
  3887. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3888. } else
  3889. # endif
  3890. if (!command->argv /* if it's the first word... */
  3891. # if ENABLE_HUSH_LOOPS
  3892. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3893. && ctx->ctx_res_w != RES_IN
  3894. # endif
  3895. # if ENABLE_HUSH_CASE
  3896. && ctx->ctx_res_w != RES_CASE
  3897. # endif
  3898. ) {
  3899. const struct reserved_combo *reserved;
  3900. reserved = reserved_word(ctx);
  3901. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3902. if (reserved) {
  3903. # if ENABLE_HUSH_LINENO_VAR
  3904. /* Case:
  3905. * "while ...; do
  3906. * cmd ..."
  3907. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3908. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3909. */
  3910. if (0
  3911. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3912. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3913. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3914. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3915. ) {
  3916. done_pipe(ctx, PIPE_SEQ);
  3917. }
  3918. # endif
  3919. o_reset_to_empty_unquoted(&ctx->word);
  3920. debug_printf_parse("done_word return %d\n",
  3921. (ctx->ctx_res_w == RES_SNTX));
  3922. return (ctx->ctx_res_w == RES_SNTX);
  3923. }
  3924. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3925. if (strcmp(ctx->word.data, "[[") == 0) {
  3926. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3927. } else
  3928. # endif
  3929. # if defined(CMD_SINGLEWORD_NOGLOB)
  3930. if (0
  3931. /* In bash, local/export/readonly are special, args
  3932. * are assignments and therefore expansion of them
  3933. * should be "one-word" expansion:
  3934. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3935. * compare with:
  3936. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3937. * ls: cannot access i=a: No such file or directory
  3938. * ls: cannot access b: No such file or directory
  3939. * Note: bash 3.2.33(1) does this only if export word
  3940. * itself is not quoted:
  3941. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3942. * aaa bbb
  3943. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3944. * aaa
  3945. */
  3946. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3947. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3948. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3949. ) {
  3950. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3951. }
  3952. # else
  3953. { /* empty block to pair "if ... else" */ }
  3954. # endif
  3955. }
  3956. #endif /* HAS_KEYWORDS */
  3957. if (command->group) {
  3958. /* "{ echo foo; } echo bar" - bad */
  3959. syntax_error_at(ctx->word.data);
  3960. debug_printf_parse("done_word return 1: syntax error, "
  3961. "groups and arglists don't mix\n");
  3962. return 1;
  3963. }
  3964. /* If this word wasn't an assignment, next ones definitely
  3965. * can't be assignments. Even if they look like ones. */
  3966. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3967. && ctx->is_assignment != WORD_IS_KEYWORD
  3968. ) {
  3969. ctx->is_assignment = NOT_ASSIGNMENT;
  3970. } else {
  3971. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3972. command->assignment_cnt++;
  3973. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3974. }
  3975. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3976. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3977. }
  3978. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3979. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3980. debug_print_strings("word appended to argv", command->argv);
  3981. }
  3982. #if ENABLE_HUSH_LOOPS
  3983. if (ctx->ctx_res_w == RES_FOR) {
  3984. if (ctx->word.has_quoted_part
  3985. || endofname(command->argv[0])[0] != '\0'
  3986. ) {
  3987. /* bash says just "not a valid identifier" */
  3988. syntax_error("bad variable name in for");
  3989. return 1;
  3990. }
  3991. /* Force FOR to have just one word (variable name) */
  3992. /* NB: basically, this makes hush see "for v in ..."
  3993. * syntax as if it is "for v; in ...". FOR and IN become
  3994. * two pipe structs in parse tree. */
  3995. done_pipe(ctx, PIPE_SEQ);
  3996. }
  3997. #endif
  3998. #if ENABLE_HUSH_CASE
  3999. /* Force CASE to have just one word */
  4000. if (ctx->ctx_res_w == RES_CASE) {
  4001. done_pipe(ctx, PIPE_SEQ);
  4002. }
  4003. #endif
  4004. o_reset_to_empty_unquoted(&ctx->word);
  4005. debug_printf_parse("done_word return 0\n");
  4006. return 0;
  4007. }
  4008. /* Peek ahead in the input to find out if we have a "&n" construct,
  4009. * as in "2>&1", that represents duplicating a file descriptor.
  4010. * Return:
  4011. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4012. * REDIRFD_SYNTAX_ERR if syntax error,
  4013. * REDIRFD_TO_FILE if no & was seen,
  4014. * or the number found.
  4015. */
  4016. #if BB_MMU
  4017. #define parse_redir_right_fd(as_string, input) \
  4018. parse_redir_right_fd(input)
  4019. #endif
  4020. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4021. {
  4022. int ch, d, ok;
  4023. ch = i_peek(input);
  4024. if (ch != '&')
  4025. return REDIRFD_TO_FILE;
  4026. ch = i_getch(input); /* get the & */
  4027. nommu_addchr(as_string, ch);
  4028. ch = i_peek(input);
  4029. if (ch == '-') {
  4030. ch = i_getch(input);
  4031. nommu_addchr(as_string, ch);
  4032. return REDIRFD_CLOSE;
  4033. }
  4034. d = 0;
  4035. ok = 0;
  4036. while (ch != EOF && isdigit(ch)) {
  4037. d = d*10 + (ch-'0');
  4038. ok = 1;
  4039. ch = i_getch(input);
  4040. nommu_addchr(as_string, ch);
  4041. ch = i_peek(input);
  4042. }
  4043. if (ok) return d;
  4044. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4045. bb_simple_error_msg("ambiguous redirect");
  4046. return REDIRFD_SYNTAX_ERR;
  4047. }
  4048. /* Return code is 0 normal, 1 if a syntax error is detected
  4049. */
  4050. static int parse_redirect(struct parse_context *ctx,
  4051. int fd,
  4052. redir_type style,
  4053. struct in_str *input)
  4054. {
  4055. struct command *command = ctx->command;
  4056. struct redir_struct *redir;
  4057. struct redir_struct **redirp;
  4058. int dup_num;
  4059. dup_num = REDIRFD_TO_FILE;
  4060. if (style != REDIRECT_HEREDOC) {
  4061. /* Check for a '>&1' type redirect */
  4062. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4063. if (dup_num == REDIRFD_SYNTAX_ERR)
  4064. return 1;
  4065. } else {
  4066. int ch = i_peek_and_eat_bkslash_nl(input);
  4067. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4068. if (dup_num) { /* <<-... */
  4069. ch = i_getch(input);
  4070. nommu_addchr(&ctx->as_string, ch);
  4071. ch = i_peek(input);
  4072. }
  4073. }
  4074. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4075. int ch = i_peek_and_eat_bkslash_nl(input);
  4076. if (ch == '|') {
  4077. /* >|FILE redirect ("clobbering" >).
  4078. * Since we do not support "set -o noclobber" yet,
  4079. * >| and > are the same for now. Just eat |.
  4080. */
  4081. ch = i_getch(input);
  4082. nommu_addchr(&ctx->as_string, ch);
  4083. }
  4084. }
  4085. /* Create a new redir_struct and append it to the linked list */
  4086. redirp = &command->redirects;
  4087. while ((redir = *redirp) != NULL) {
  4088. redirp = &(redir->next);
  4089. }
  4090. *redirp = redir = xzalloc(sizeof(*redir));
  4091. /* redir->next = NULL; */
  4092. /* redir->rd_filename = NULL; */
  4093. redir->rd_type = style;
  4094. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4095. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4096. redir_table[style].descrip);
  4097. redir->rd_dup = dup_num;
  4098. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4099. /* Erik had a check here that the file descriptor in question
  4100. * is legit; I postpone that to "run time"
  4101. * A "-" representation of "close me" shows up as a -3 here */
  4102. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4103. redir->rd_fd, redir->rd_dup);
  4104. } else {
  4105. #if 0 /* Instead we emit error message at run time */
  4106. if (ctx->pending_redirect) {
  4107. /* For example, "cmd > <file" */
  4108. syntax_error("invalid redirect");
  4109. }
  4110. #endif
  4111. /* Set ctx->pending_redirect, so we know what to do at the
  4112. * end of the next parsed word. */
  4113. ctx->pending_redirect = redir;
  4114. }
  4115. return 0;
  4116. }
  4117. /* If a redirect is immediately preceded by a number, that number is
  4118. * supposed to tell which file descriptor to redirect. This routine
  4119. * looks for such preceding numbers. In an ideal world this routine
  4120. * needs to handle all the following classes of redirects...
  4121. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4122. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4123. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4124. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4125. *
  4126. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4127. * "2.7 Redirection
  4128. * ... If n is quoted, the number shall not be recognized as part of
  4129. * the redirection expression. For example:
  4130. * echo \2>a
  4131. * writes the character 2 into file a"
  4132. * We are getting it right by setting ->has_quoted_part on any \<char>
  4133. *
  4134. * A -1 return means no valid number was found,
  4135. * the caller should use the appropriate default for this redirection.
  4136. */
  4137. static int redirect_opt_num(o_string *o)
  4138. {
  4139. int num;
  4140. if (o->data == NULL)
  4141. return -1;
  4142. num = bb_strtou(o->data, NULL, 10);
  4143. if (errno || num < 0)
  4144. return -1;
  4145. o_reset_to_empty_unquoted(o);
  4146. return num;
  4147. }
  4148. #if BB_MMU
  4149. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4150. fetch_till_str(input, word, skip_tabs)
  4151. #endif
  4152. static char *fetch_till_str(o_string *as_string,
  4153. struct in_str *input,
  4154. const char *word,
  4155. int heredoc_flags)
  4156. {
  4157. o_string heredoc = NULL_O_STRING;
  4158. unsigned past_EOL;
  4159. int prev = 0; /* not \ */
  4160. int ch;
  4161. /* Starting with "" is necessary for this case:
  4162. * cat <<EOF
  4163. *
  4164. * xxx
  4165. * EOF
  4166. */
  4167. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4168. goto jump_in;
  4169. while (1) {
  4170. ch = i_getch(input);
  4171. if (ch != EOF)
  4172. nommu_addchr(as_string, ch);
  4173. if (ch == '\n' || ch == EOF) {
  4174. check_heredoc_end:
  4175. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4176. /* End-of-line, and not a line continuation */
  4177. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4178. heredoc.data[past_EOL] = '\0';
  4179. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4180. return heredoc.data;
  4181. }
  4182. if (ch == '\n') {
  4183. /* This is a new line.
  4184. * Remember position and backslash-escaping status.
  4185. */
  4186. o_addchr(&heredoc, ch);
  4187. prev = ch;
  4188. jump_in:
  4189. past_EOL = heredoc.length;
  4190. /* Get 1st char of next line, possibly skipping leading tabs */
  4191. do {
  4192. ch = i_getch(input);
  4193. if (ch != EOF)
  4194. nommu_addchr(as_string, ch);
  4195. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4196. /* If this immediately ended the line,
  4197. * go back to end-of-line checks.
  4198. */
  4199. if (ch == '\n')
  4200. goto check_heredoc_end;
  4201. }
  4202. } else {
  4203. /* Backslash-line continuation in an unquoted
  4204. * heredoc. This does not need special handling
  4205. * for heredoc body (unquoted heredocs are
  4206. * expanded on "execution" and that would take
  4207. * care of this case too), but not the case
  4208. * of line continuation *in terminator*:
  4209. * cat <<EOF
  4210. * Ok1
  4211. * EO\
  4212. * F
  4213. */
  4214. heredoc.data[--heredoc.length] = '\0';
  4215. prev = 0; /* not '\' */
  4216. continue;
  4217. }
  4218. }
  4219. if (ch == EOF) {
  4220. o_free(&heredoc);
  4221. return NULL; /* error */
  4222. }
  4223. o_addchr(&heredoc, ch);
  4224. nommu_addchr(as_string, ch);
  4225. if (prev == '\\' && ch == '\\')
  4226. /* Correctly handle foo\\<eol> (not a line cont.) */
  4227. prev = 0; /* not '\' */
  4228. else
  4229. prev = ch;
  4230. }
  4231. }
  4232. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4233. * and load them all. There should be exactly heredoc_cnt of them.
  4234. */
  4235. #if BB_MMU
  4236. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4237. fetch_heredocs(pi, heredoc_cnt, input)
  4238. #endif
  4239. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4240. {
  4241. while (pi && heredoc_cnt) {
  4242. int i;
  4243. struct command *cmd = pi->cmds;
  4244. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4245. pi->num_cmds,
  4246. cmd->argv ? cmd->argv[0] : "NONE"
  4247. );
  4248. for (i = 0; i < pi->num_cmds; i++) {
  4249. struct redir_struct *redir = cmd->redirects;
  4250. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4251. i, cmd->argv ? cmd->argv[0] : "NONE");
  4252. while (redir) {
  4253. if (redir->rd_type == REDIRECT_HEREDOC) {
  4254. char *p;
  4255. redir->rd_type = REDIRECT_HEREDOC2;
  4256. /* redir->rd_dup is (ab)used to indicate <<- */
  4257. p = fetch_till_str(as_string, input,
  4258. redir->rd_filename, redir->rd_dup);
  4259. if (!p) {
  4260. syntax_error("unexpected EOF in here document");
  4261. return -1;
  4262. }
  4263. free(redir->rd_filename);
  4264. redir->rd_filename = p;
  4265. heredoc_cnt--;
  4266. }
  4267. redir = redir->next;
  4268. }
  4269. if (cmd->group) {
  4270. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4271. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4272. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4273. if (heredoc_cnt < 0)
  4274. return heredoc_cnt; /* error */
  4275. }
  4276. cmd++;
  4277. }
  4278. pi = pi->next;
  4279. }
  4280. return heredoc_cnt;
  4281. }
  4282. static int run_list(struct pipe *pi);
  4283. #if BB_MMU
  4284. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4285. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4286. #endif
  4287. static struct pipe *parse_stream(char **pstring,
  4288. int *heredoc_cnt_ptr,
  4289. struct in_str *input,
  4290. int end_trigger);
  4291. /* Returns number of heredocs not yet consumed,
  4292. * or -1 on error.
  4293. */
  4294. static int parse_group(struct parse_context *ctx,
  4295. struct in_str *input, int ch)
  4296. {
  4297. /* ctx->word contains characters seen prior to ( or {.
  4298. * Typically it's empty, but for function defs,
  4299. * it contains function name (without '()'). */
  4300. #if BB_MMU
  4301. # define as_string NULL
  4302. #else
  4303. char *as_string = NULL;
  4304. #endif
  4305. struct pipe *pipe_list;
  4306. int heredoc_cnt = 0;
  4307. int endch;
  4308. struct command *command = ctx->command;
  4309. debug_printf_parse("parse_group entered\n");
  4310. #if ENABLE_HUSH_FUNCTIONS
  4311. if (ch == '(' && !ctx->word.has_quoted_part) {
  4312. if (ctx->word.length)
  4313. if (done_word(ctx))
  4314. return -1;
  4315. if (!command->argv)
  4316. goto skip; /* (... */
  4317. if (command->argv[1]) { /* word word ... (... */
  4318. syntax_error_unexpected_ch('(');
  4319. return -1;
  4320. }
  4321. /* it is "word(..." or "word (..." */
  4322. do
  4323. ch = i_getch(input);
  4324. while (ch == ' ' || ch == '\t');
  4325. if (ch != ')') {
  4326. syntax_error_unexpected_ch(ch);
  4327. return -1;
  4328. }
  4329. nommu_addchr(&ctx->as_string, ch);
  4330. do
  4331. ch = i_getch(input);
  4332. while (ch == ' ' || ch == '\t' || ch == '\n');
  4333. if (ch != '{' && ch != '(') {
  4334. syntax_error_unexpected_ch(ch);
  4335. return -1;
  4336. }
  4337. nommu_addchr(&ctx->as_string, ch);
  4338. command->cmd_type = CMD_FUNCDEF;
  4339. goto skip;
  4340. }
  4341. #endif
  4342. #if 0 /* Prevented by caller */
  4343. if (command->argv /* word [word]{... */
  4344. || ctx->word.length /* word{... */
  4345. || ctx->word.has_quoted_part /* ""{... */
  4346. ) {
  4347. syntax_error(NULL);
  4348. debug_printf_parse("parse_group return -1: "
  4349. "syntax error, groups and arglists don't mix\n");
  4350. return -1;
  4351. }
  4352. #endif
  4353. IF_HUSH_FUNCTIONS(skip:)
  4354. endch = '}';
  4355. if (ch == '(') {
  4356. endch = ')';
  4357. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4358. command->cmd_type = CMD_SUBSHELL;
  4359. } else {
  4360. /* bash does not allow "{echo...", requires whitespace */
  4361. ch = i_peek(input);
  4362. if (ch != ' ' && ch != '\t' && ch != '\n'
  4363. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4364. ) {
  4365. syntax_error_unexpected_ch(ch);
  4366. return -1;
  4367. }
  4368. if (ch != '(') {
  4369. ch = i_getch(input);
  4370. nommu_addchr(&ctx->as_string, ch);
  4371. }
  4372. }
  4373. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4374. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4375. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4376. #if !BB_MMU
  4377. if (as_string)
  4378. o_addstr(&ctx->as_string, as_string);
  4379. #endif
  4380. /* empty ()/{} or parse error? */
  4381. if (!pipe_list || pipe_list == ERR_PTR) {
  4382. /* parse_stream already emitted error msg */
  4383. if (!BB_MMU)
  4384. free(as_string);
  4385. debug_printf_parse("parse_group return -1: "
  4386. "parse_stream returned %p\n", pipe_list);
  4387. return -1;
  4388. }
  4389. #if !BB_MMU
  4390. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4391. command->group_as_string = as_string;
  4392. debug_printf_parse("end of group, remembering as:'%s'\n",
  4393. command->group_as_string);
  4394. #endif
  4395. #if ENABLE_HUSH_FUNCTIONS
  4396. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4397. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4398. struct command *cmd2;
  4399. cmd2 = xzalloc(sizeof(*cmd2));
  4400. cmd2->cmd_type = CMD_SUBSHELL;
  4401. cmd2->group = pipe_list;
  4402. # if !BB_MMU
  4403. //UNTESTED!
  4404. cmd2->group_as_string = command->group_as_string;
  4405. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4406. # endif
  4407. pipe_list = new_pipe();
  4408. pipe_list->cmds = cmd2;
  4409. pipe_list->num_cmds = 1;
  4410. }
  4411. #endif
  4412. command->group = pipe_list;
  4413. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4414. return heredoc_cnt;
  4415. /* command remains "open", available for possible redirects */
  4416. #undef as_string
  4417. }
  4418. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4419. /* Subroutines for copying $(...) and `...` things */
  4420. /* '...' */
  4421. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4422. {
  4423. while (1) {
  4424. int ch = i_getch(input);
  4425. if (ch == EOF) {
  4426. syntax_error_unterm_ch('\'');
  4427. return 0;
  4428. }
  4429. if (ch == '\'')
  4430. return 1;
  4431. o_addchr(dest, ch);
  4432. }
  4433. }
  4434. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4435. {
  4436. while (1) {
  4437. int ch = i_getch(input);
  4438. if (ch == EOF) {
  4439. syntax_error_unterm_ch('\'');
  4440. return 0;
  4441. }
  4442. if (ch == '\'')
  4443. return 1;
  4444. o_addqchr(dest, ch);
  4445. }
  4446. }
  4447. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4448. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4449. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4450. {
  4451. while (1) {
  4452. int ch = i_getch(input);
  4453. if (ch == EOF) {
  4454. syntax_error_unterm_ch('"');
  4455. return 0;
  4456. }
  4457. if (ch == '"')
  4458. return 1;
  4459. if (ch == '\\') { /* \x. Copy both chars. */
  4460. o_addchr(dest, ch);
  4461. ch = i_getch(input);
  4462. }
  4463. o_addchr(dest, ch);
  4464. if (ch == '`') {
  4465. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4466. return 0;
  4467. o_addchr(dest, ch);
  4468. continue;
  4469. }
  4470. //if (ch == '$') ...
  4471. }
  4472. }
  4473. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4474. * \` quoting.
  4475. * "Within the backquoted style of command substitution, backslash
  4476. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4477. * The search for the matching backquote shall be satisfied by the first
  4478. * backquote found without a preceding backslash; during this search,
  4479. * if a non-escaped backquote is encountered within a shell comment,
  4480. * a here-document, an embedded command substitution of the $(command)
  4481. * form, or a quoted string, undefined results occur. A single-quoted
  4482. * or double-quoted string that begins, but does not end, within the
  4483. * "`...`" sequence produces undefined results."
  4484. * Example Output
  4485. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4486. */
  4487. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4488. {
  4489. while (1) {
  4490. int ch = i_getch(input);
  4491. if (ch == '`')
  4492. return 1;
  4493. if (ch == '\\') {
  4494. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4495. ch = i_getch(input);
  4496. if (ch != '`'
  4497. && ch != '$'
  4498. && ch != '\\'
  4499. && (!in_dquote || ch != '"')
  4500. ) {
  4501. o_addchr(dest, '\\');
  4502. }
  4503. }
  4504. if (ch == EOF) {
  4505. syntax_error_unterm_ch('`');
  4506. return 0;
  4507. }
  4508. o_addchr(dest, ch);
  4509. }
  4510. }
  4511. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4512. * quoting and nested ()s.
  4513. * "With the $(command) style of command substitution, all characters
  4514. * following the open parenthesis to the matching closing parenthesis
  4515. * constitute the command. Any valid shell script can be used for command,
  4516. * except a script consisting solely of redirections which produces
  4517. * unspecified results."
  4518. * Example Output
  4519. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4520. * echo $(echo 'TEST)' BEST) TEST) BEST
  4521. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4522. *
  4523. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4524. * can contain arbitrary constructs, just like $(cmd).
  4525. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4526. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4527. */
  4528. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4529. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4530. {
  4531. int ch;
  4532. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4533. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4534. char end_char2 = end_ch >> 8;
  4535. # endif
  4536. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4537. # if ENABLE_HUSH_INTERACTIVE
  4538. G.promptmode = 1; /* PS2 */
  4539. # endif
  4540. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4541. while (1) {
  4542. ch = i_getch(input);
  4543. if (ch == EOF) {
  4544. syntax_error_unterm_ch(end_ch);
  4545. return 0;
  4546. }
  4547. if (ch == end_ch
  4548. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4549. || ch == end_char2
  4550. # endif
  4551. ) {
  4552. if (!dbl)
  4553. break;
  4554. /* we look for closing )) of $((EXPR)) */
  4555. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4556. i_getch(input); /* eat second ')' */
  4557. break;
  4558. }
  4559. }
  4560. o_addchr(dest, ch);
  4561. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4562. if (ch == '(' || ch == '{') {
  4563. ch = (ch == '(' ? ')' : '}');
  4564. if (!add_till_closing_bracket(dest, input, ch))
  4565. return 0;
  4566. o_addchr(dest, ch);
  4567. continue;
  4568. }
  4569. if (ch == '\'') {
  4570. if (!add_till_single_quote(dest, input))
  4571. return 0;
  4572. o_addchr(dest, ch);
  4573. continue;
  4574. }
  4575. if (ch == '"') {
  4576. if (!add_till_double_quote(dest, input))
  4577. return 0;
  4578. o_addchr(dest, ch);
  4579. continue;
  4580. }
  4581. if (ch == '`') {
  4582. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4583. return 0;
  4584. o_addchr(dest, ch);
  4585. continue;
  4586. }
  4587. if (ch == '\\') {
  4588. /* \x. Copy verbatim. Important for \(, \) */
  4589. ch = i_getch(input);
  4590. if (ch == EOF) {
  4591. syntax_error_unterm_ch(end_ch);
  4592. return 0;
  4593. }
  4594. # if 0
  4595. if (ch == '\n') {
  4596. /* "backslash+newline", ignore both */
  4597. o_delchr(dest); /* undo insertion of '\' */
  4598. continue;
  4599. }
  4600. # endif
  4601. o_addchr(dest, ch);
  4602. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4603. continue;
  4604. }
  4605. }
  4606. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4607. return ch;
  4608. }
  4609. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4610. #if BASH_DOLLAR_SQUOTE
  4611. /* Return code: 1 for "found and parsed", 0 for "seen something else" */
  4612. # if BB_MMU
  4613. #define parse_dollar_squote(as_string, dest, input) \
  4614. parse_dollar_squote(dest, input)
  4615. #define as_string NULL
  4616. # endif
  4617. static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
  4618. {
  4619. int start;
  4620. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4621. debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
  4622. if (ch != '\'')
  4623. return 0;
  4624. dest->has_quoted_part = 1;
  4625. start = dest->length;
  4626. ch = i_getch(input); /* eat ' */
  4627. nommu_addchr(as_string, ch);
  4628. while (1) {
  4629. ch = i_getch(input);
  4630. nommu_addchr(as_string, ch);
  4631. if (ch == EOF) {
  4632. syntax_error_unterm_ch('\'');
  4633. return 0;
  4634. }
  4635. if (ch == '\'')
  4636. break;
  4637. if (ch == SPECIAL_VAR_SYMBOL) {
  4638. /* Convert raw ^C to corresponding special variable reference */
  4639. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4640. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4641. /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
  4642. } else if (ch == '\\') {
  4643. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  4644. ch = i_getch(input);
  4645. nommu_addchr(as_string, ch);
  4646. if (strchr(C_escapes, ch)) {
  4647. char buf[4];
  4648. char *p = buf;
  4649. int cnt = 2;
  4650. buf[0] = ch;
  4651. if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
  4652. do {
  4653. ch = i_peek(input);
  4654. if ((unsigned char)(ch - '0') > 7)
  4655. break;
  4656. *++p = ch = i_getch(input);
  4657. nommu_addchr(as_string, ch);
  4658. } while (--cnt != 0);
  4659. } else if (ch == 'x') { /* \xHH */
  4660. do {
  4661. ch = i_peek(input);
  4662. if (!isxdigit(ch))
  4663. break;
  4664. *++p = ch = i_getch(input);
  4665. nommu_addchr(as_string, ch);
  4666. } while (--cnt != 0);
  4667. if (cnt == 2) { /* \x but next char is "bad" */
  4668. ch = 'x';
  4669. goto unrecognized;
  4670. }
  4671. } /* else simple seq like \\ or \t */
  4672. *++p = '\0';
  4673. p = buf;
  4674. ch = bb_process_escape_sequence((void*)&p);
  4675. //bb_error_msg("buf:'%s' ch:%x", buf, ch);
  4676. if (ch == '\0')
  4677. continue; /* bash compat: $'...\0...' emits nothing */
  4678. } else { /* unrecognized "\z": encode both chars unless ' or " */
  4679. if (ch != '\'' && ch != '"') {
  4680. unrecognized:
  4681. o_addqchr(dest, '\\');
  4682. }
  4683. }
  4684. } /* if (\...) */
  4685. o_addqchr(dest, ch);
  4686. }
  4687. if (dest->length == start) {
  4688. /* $'', $'\0', $'\000\x00' and the like */
  4689. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4690. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4691. }
  4692. return 1;
  4693. # undef as_string
  4694. }
  4695. #else
  4696. # define parse_dollar_squote(as_string, dest, input) 0
  4697. #endif /* BASH_DOLLAR_SQUOTE */
  4698. /* Return code: 0 for OK, 1 for syntax error */
  4699. #if BB_MMU
  4700. #define parse_dollar(as_string, dest, input, quote_mask) \
  4701. parse_dollar(dest, input, quote_mask)
  4702. #define as_string NULL
  4703. #endif
  4704. static int parse_dollar(o_string *as_string,
  4705. o_string *dest,
  4706. struct in_str *input, unsigned char quote_mask)
  4707. {
  4708. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4709. debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
  4710. if (isalpha(ch)) {
  4711. make_var:
  4712. ch = i_getch(input);
  4713. nommu_addchr(as_string, ch);
  4714. /*make_var1:*/
  4715. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4716. while (1) {
  4717. debug_printf_parse(": '%c'\n", ch);
  4718. o_addchr(dest, ch | quote_mask);
  4719. quote_mask = 0;
  4720. ch = i_peek_and_eat_bkslash_nl(input);
  4721. if (!isalnum(ch) && ch != '_') {
  4722. /* End of variable name reached */
  4723. break;
  4724. }
  4725. ch = i_getch(input);
  4726. nommu_addchr(as_string, ch);
  4727. }
  4728. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4729. } else if (isdigit(ch)) {
  4730. make_one_char_var:
  4731. ch = i_getch(input);
  4732. nommu_addchr(as_string, ch);
  4733. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4734. debug_printf_parse(": '%c'\n", ch);
  4735. o_addchr(dest, ch | quote_mask);
  4736. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4737. } else switch (ch) {
  4738. case '$': /* pid */
  4739. case '!': /* last bg pid */
  4740. case '?': /* last exit code */
  4741. case '#': /* number of args */
  4742. case '*': /* args */
  4743. case '@': /* args */
  4744. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4745. goto make_one_char_var;
  4746. case '{': {
  4747. char len_single_ch;
  4748. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4749. ch = i_getch(input); /* eat '{' */
  4750. nommu_addchr(as_string, ch);
  4751. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4752. /* It should be ${?}, or ${#var},
  4753. * or even ${?+subst} - operator acting on a special variable,
  4754. * or the beginning of variable name.
  4755. */
  4756. if (ch == EOF
  4757. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4758. ) {
  4759. bad_dollar_syntax:
  4760. syntax_error_unterm_str("${name}");
  4761. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4762. return 0;
  4763. }
  4764. nommu_addchr(as_string, ch);
  4765. len_single_ch = ch;
  4766. ch |= quote_mask;
  4767. /* It's possible to just call add_till_closing_bracket() at this point.
  4768. * However, this regresses some of our testsuite cases
  4769. * which check invalid constructs like ${%}.
  4770. * Oh well... let's check that the var name part is fine... */
  4771. if (isdigit(len_single_ch)
  4772. || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
  4773. ) {
  4774. /* Execution engine uses plain xatoi_positive()
  4775. * to interpret ${NNN} and {#NNN},
  4776. * check syntax here in the parser.
  4777. * (bash does not support expressions in ${#NN},
  4778. * e.g. ${#$var} and {#1:+WORD} are not supported).
  4779. */
  4780. unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
  4781. while (1) {
  4782. o_addchr(dest, ch);
  4783. debug_printf_parse(": '%c'\n", ch);
  4784. ch = i_getch_and_eat_bkslash_nl(input);
  4785. nommu_addchr(as_string, ch);
  4786. if (ch == '}')
  4787. break;
  4788. if (--cnt == 0)
  4789. goto bad_dollar_syntax;
  4790. if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
  4791. /* ${NN<op>...} is valid */
  4792. goto eat_until_closing;
  4793. if (!isdigit(ch))
  4794. goto bad_dollar_syntax;
  4795. }
  4796. } else
  4797. while (1) {
  4798. unsigned pos;
  4799. o_addchr(dest, ch);
  4800. debug_printf_parse(": '%c'\n", ch);
  4801. ch = i_getch(input);
  4802. nommu_addchr(as_string, ch);
  4803. if (ch == '}')
  4804. break;
  4805. if (!isalnum(ch) && ch != '_') {
  4806. unsigned end_ch;
  4807. unsigned char last_ch;
  4808. /* handle parameter expansions
  4809. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4810. */
  4811. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4812. if (len_single_ch != '#'
  4813. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4814. || i_peek(input) != '}'
  4815. ) {
  4816. goto bad_dollar_syntax;
  4817. }
  4818. /* else: it's "length of C" ${#C} op,
  4819. * where C is a single char
  4820. * special var name, e.g. ${#!}.
  4821. */
  4822. }
  4823. eat_until_closing:
  4824. /* Eat everything until closing '}' (or ':') */
  4825. end_ch = '}';
  4826. if (BASH_SUBSTR
  4827. && ch == ':'
  4828. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4829. ) {
  4830. /* It's ${var:N[:M]} thing */
  4831. end_ch = '}' * 0x100 + ':';
  4832. }
  4833. if (BASH_PATTERN_SUBST
  4834. && ch == '/'
  4835. ) {
  4836. /* It's ${var/[/]pattern[/repl]} thing */
  4837. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4838. i_getch(input);
  4839. nommu_addchr(as_string, '/');
  4840. ch = '\\';
  4841. }
  4842. end_ch = '}' * 0x100 + '/';
  4843. }
  4844. o_addchr(dest, ch);
  4845. /* The pattern can't be empty.
  4846. * IOW: if the first char after "${v//" is a slash,
  4847. * it does not terminate the pattern - it's the first char of the pattern:
  4848. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4849. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4850. */
  4851. if (i_peek(input) == '/') {
  4852. o_addchr(dest, i_getch(input));
  4853. }
  4854. again:
  4855. if (!BB_MMU)
  4856. pos = dest->length;
  4857. #if ENABLE_HUSH_DOLLAR_OPS
  4858. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4859. if (last_ch == 0) /* error? */
  4860. return 0;
  4861. #else
  4862. # error Simple code to only allow ${var} is not implemented
  4863. #endif
  4864. if (as_string) {
  4865. o_addstr(as_string, dest->data + pos);
  4866. o_addchr(as_string, last_ch);
  4867. }
  4868. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4869. && (end_ch & 0xff00)
  4870. ) {
  4871. /* close the first block: */
  4872. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4873. /* while parsing N from ${var:N[:M]}
  4874. * or pattern from ${var/[/]pattern[/repl]} */
  4875. if ((end_ch & 0xff) == last_ch) {
  4876. /* got ':' or '/'- parse the rest */
  4877. end_ch = '}';
  4878. goto again;
  4879. }
  4880. /* got '}' */
  4881. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4882. /* it's ${var:N} - emulate :999999999 */
  4883. o_addstr(dest, "999999999");
  4884. } /* else: it's ${var/[/]pattern} */
  4885. }
  4886. break;
  4887. }
  4888. len_single_ch = 0; /* it can't be ${#C} op */
  4889. }
  4890. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4891. break;
  4892. }
  4893. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4894. case '(': {
  4895. unsigned pos;
  4896. ch = i_getch(input);
  4897. nommu_addchr(as_string, ch);
  4898. # if ENABLE_FEATURE_SH_MATH
  4899. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4900. ch = i_getch(input);
  4901. nommu_addchr(as_string, ch);
  4902. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4903. o_addchr(dest, quote_mask | '+');
  4904. if (!BB_MMU)
  4905. pos = dest->length;
  4906. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4907. return 0; /* error */
  4908. if (as_string) {
  4909. o_addstr(as_string, dest->data + pos);
  4910. o_addchr(as_string, ')');
  4911. o_addchr(as_string, ')');
  4912. }
  4913. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4914. break;
  4915. }
  4916. # endif
  4917. # if ENABLE_HUSH_TICK
  4918. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4919. o_addchr(dest, quote_mask | '`');
  4920. if (!BB_MMU)
  4921. pos = dest->length;
  4922. if (!add_till_closing_bracket(dest, input, ')'))
  4923. return 0; /* error */
  4924. if (as_string) {
  4925. o_addstr(as_string, dest->data + pos);
  4926. o_addchr(as_string, ')');
  4927. }
  4928. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4929. # endif
  4930. break;
  4931. }
  4932. #endif
  4933. case '_':
  4934. goto make_var;
  4935. #if 0
  4936. /* TODO: $_: */
  4937. /* $_ Shell or shell script name; or last argument of last command
  4938. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4939. * but in command's env, set to full pathname used to invoke it */
  4940. ch = i_getch(input);
  4941. nommu_addchr(as_string, ch);
  4942. ch = i_peek_and_eat_bkslash_nl(input);
  4943. if (isalnum(ch)) { /* it's $_name or $_123 */
  4944. ch = '_';
  4945. goto make_var1;
  4946. }
  4947. /* else: it's $_ */
  4948. #endif
  4949. default:
  4950. o_addQchr(dest, '$');
  4951. }
  4952. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4953. return 1;
  4954. #undef as_string
  4955. }
  4956. #if BB_MMU
  4957. #define encode_string(as_string, dest, input, dquote_end) \
  4958. encode_string(dest, input, dquote_end)
  4959. #define as_string NULL
  4960. #endif
  4961. static int encode_string(o_string *as_string,
  4962. o_string *dest,
  4963. struct in_str *input,
  4964. int dquote_end)
  4965. {
  4966. int ch;
  4967. int next;
  4968. again:
  4969. ch = i_getch(input);
  4970. if (ch != EOF)
  4971. nommu_addchr(as_string, ch);
  4972. if (ch == dquote_end) { /* may be only '"' or EOF */
  4973. debug_printf_parse("encode_string return 1 (ok)\n");
  4974. return 1;
  4975. }
  4976. /* note: can't move it above ch == dquote_end check! */
  4977. if (ch == EOF) {
  4978. syntax_error_unterm_ch('"');
  4979. return 0; /* error */
  4980. }
  4981. next = '\0';
  4982. if (ch != '\n') {
  4983. next = i_peek(input);
  4984. }
  4985. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4986. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4987. if (ch == '\\') {
  4988. if (next == EOF) {
  4989. /* Testcase: in interactive shell a file with
  4990. * echo "unterminated string\<eof>
  4991. * is sourced.
  4992. */
  4993. syntax_error_unterm_ch('"');
  4994. return 0; /* error */
  4995. }
  4996. /* bash:
  4997. * "The backslash retains its special meaning [in "..."]
  4998. * only when followed by one of the following characters:
  4999. * $, `, ", \, or <newline>. A double quote may be quoted
  5000. * within double quotes by preceding it with a backslash."
  5001. * NB: in (unquoted) heredoc, above does not apply to ",
  5002. * therefore we check for it by "next == dquote_end" cond.
  5003. */
  5004. if (next == dquote_end || strchr("$`\\\n", next)) {
  5005. ch = i_getch(input); /* eat next */
  5006. if (ch == '\n')
  5007. goto again; /* skip \<newline> */
  5008. } /* else: ch remains == '\\', and we double it below: */
  5009. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  5010. nommu_addchr(as_string, ch);
  5011. goto again;
  5012. }
  5013. if (ch == '$') {
  5014. //if (parse_dollar_squote(as_string, dest, input))
  5015. // goto again;
  5016. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  5017. debug_printf_parse("encode_string return 0: "
  5018. "parse_dollar returned 0 (error)\n");
  5019. return 0;
  5020. }
  5021. goto again;
  5022. }
  5023. #if ENABLE_HUSH_TICK
  5024. if (ch == '`') {
  5025. //unsigned pos = dest->length;
  5026. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5027. o_addchr(dest, 0x80 | '`');
  5028. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  5029. return 0; /* error */
  5030. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5031. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5032. goto again;
  5033. }
  5034. #endif
  5035. o_addQchr(dest, ch);
  5036. if (ch == SPECIAL_VAR_SYMBOL) {
  5037. /* Convert "^C" to corresponding special variable reference */
  5038. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  5039. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5040. }
  5041. goto again;
  5042. #undef as_string
  5043. }
  5044. /*
  5045. * Scan input until EOF or end_trigger char.
  5046. * Return a list of pipes to execute, or NULL on EOF
  5047. * or if end_trigger character is met.
  5048. * On syntax error, exit if shell is not interactive,
  5049. * reset parsing machinery and start parsing anew,
  5050. * or return ERR_PTR.
  5051. */
  5052. static struct pipe *parse_stream(char **pstring,
  5053. int *heredoc_cnt_ptr,
  5054. struct in_str *input,
  5055. int end_trigger)
  5056. {
  5057. struct parse_context ctx;
  5058. int heredoc_cnt;
  5059. /* Single-quote triggers a bypass of the main loop until its mate is
  5060. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  5061. */
  5062. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  5063. end_trigger ? end_trigger : 'X');
  5064. debug_enter();
  5065. initialize_context(&ctx);
  5066. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  5067. * Preventing this:
  5068. */
  5069. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  5070. /* We used to separate words on $IFS here. This was wrong.
  5071. * $IFS is used only for word splitting when $var is expanded,
  5072. * here we should use blank chars as separators, not $IFS
  5073. */
  5074. heredoc_cnt = 0;
  5075. while (1) {
  5076. const char *is_blank;
  5077. const char *is_special;
  5078. int ch;
  5079. int next;
  5080. int redir_fd;
  5081. redir_type redir_style;
  5082. ch = i_getch(input);
  5083. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5084. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5085. if (ch == EOF) {
  5086. struct pipe *pi;
  5087. if (heredoc_cnt) {
  5088. syntax_error_unterm_str("here document");
  5089. goto parse_error_exitcode1;
  5090. }
  5091. if (end_trigger == ')') {
  5092. syntax_error_unterm_ch('(');
  5093. goto parse_error_exitcode1;
  5094. }
  5095. if (end_trigger == '}') {
  5096. syntax_error_unterm_ch('{');
  5097. goto parse_error_exitcode1;
  5098. }
  5099. if (done_word(&ctx)) {
  5100. goto parse_error_exitcode1;
  5101. }
  5102. o_free_and_set_NULL(&ctx.word);
  5103. done_pipe(&ctx, PIPE_SEQ);
  5104. pi = ctx.list_head;
  5105. /* If we got nothing... */
  5106. /* (this makes bare "&" cmd a no-op.
  5107. * bash says: "syntax error near unexpected token '&'") */
  5108. if (pi->num_cmds == 0
  5109. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5110. ) {
  5111. free_pipe_list(pi);
  5112. pi = NULL;
  5113. }
  5114. #if !BB_MMU
  5115. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5116. if (pstring)
  5117. *pstring = ctx.as_string.data;
  5118. else
  5119. o_free(&ctx.as_string);
  5120. #endif
  5121. // heredoc_cnt must be 0 here anyway
  5122. //if (heredoc_cnt_ptr)
  5123. // *heredoc_cnt_ptr = heredoc_cnt;
  5124. debug_leave();
  5125. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5126. debug_printf_parse("parse_stream return %p\n", pi);
  5127. return pi;
  5128. }
  5129. /* Handle "'" and "\" first, as they won't play nice with
  5130. * i_peek_and_eat_bkslash_nl() anyway:
  5131. * echo z\\
  5132. * and
  5133. * echo '\
  5134. * '
  5135. * would break.
  5136. */
  5137. if (ch == '\\') {
  5138. ch = i_getch(input);
  5139. if (ch == '\n')
  5140. continue; /* drop \<newline>, get next char */
  5141. nommu_addchr(&ctx.as_string, '\\');
  5142. if (ch == SPECIAL_VAR_SYMBOL) {
  5143. nommu_addchr(&ctx.as_string, ch);
  5144. /* Convert \^C to corresponding special variable reference */
  5145. goto case_SPECIAL_VAR_SYMBOL;
  5146. }
  5147. o_addchr(&ctx.word, '\\');
  5148. if (ch == EOF) {
  5149. /* Testcase: eval 'echo Ok\' */
  5150. /* bash-4.3.43 was removing backslash,
  5151. * but 4.4.19 retains it, most other shells too
  5152. */
  5153. continue; /* get next char */
  5154. }
  5155. /* Example: echo Hello \2>file
  5156. * we need to know that word 2 is quoted
  5157. */
  5158. ctx.word.has_quoted_part = 1;
  5159. nommu_addchr(&ctx.as_string, ch);
  5160. o_addchr(&ctx.word, ch);
  5161. continue; /* get next char */
  5162. }
  5163. nommu_addchr(&ctx.as_string, ch);
  5164. if (ch == '\'') {
  5165. ctx.word.has_quoted_part = 1;
  5166. next = i_getch(input);
  5167. if (next == '\'' && !ctx.pending_redirect)
  5168. goto insert_empty_quoted_str_marker;
  5169. ch = next;
  5170. while (1) {
  5171. if (ch == EOF) {
  5172. syntax_error_unterm_ch('\'');
  5173. goto parse_error_exitcode1;
  5174. }
  5175. nommu_addchr(&ctx.as_string, ch);
  5176. if (ch == '\'')
  5177. break;
  5178. if (ch == SPECIAL_VAR_SYMBOL) {
  5179. /* Convert raw ^C to corresponding special variable reference */
  5180. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5181. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5182. }
  5183. o_addqchr(&ctx.word, ch);
  5184. ch = i_getch(input);
  5185. }
  5186. continue; /* get next char */
  5187. }
  5188. next = '\0';
  5189. if (ch != '\n')
  5190. next = i_peek_and_eat_bkslash_nl(input);
  5191. is_special = "{}<>&|();#" /* special outside of "str" */
  5192. "$\"" IF_HUSH_TICK("`") /* always special */
  5193. SPECIAL_VAR_SYMBOL_STR;
  5194. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5195. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5196. /* In [[ ]], {}<>&|() are not special */
  5197. is_special += 8;
  5198. } else
  5199. #endif
  5200. /* Are { and } special here? */
  5201. if (ctx.command->argv /* word [word]{... - non-special */
  5202. || ctx.word.length /* word{... - non-special */
  5203. || ctx.word.has_quoted_part /* ""{... - non-special */
  5204. || (next != ';' /* }; - special */
  5205. && next != ')' /* }) - special */
  5206. && next != '(' /* {( - special */
  5207. && next != '&' /* }& and }&& ... - special */
  5208. && next != '|' /* }|| ... - special */
  5209. && !strchr(defifs, next) /* {word - non-special */
  5210. )
  5211. ) {
  5212. /* They are not special, skip "{}" */
  5213. is_special += 2;
  5214. }
  5215. is_special = strchr(is_special, ch);
  5216. is_blank = strchr(defifs, ch);
  5217. if (!is_special && !is_blank) { /* ordinary char */
  5218. ordinary_char:
  5219. o_addQchr(&ctx.word, ch);
  5220. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5221. || ctx.is_assignment == WORD_IS_KEYWORD)
  5222. && ch == '='
  5223. && endofname(ctx.word.data)[0] == '='
  5224. ) {
  5225. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5226. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5227. }
  5228. continue;
  5229. }
  5230. if (is_blank) {
  5231. #if ENABLE_HUSH_LINENO_VAR
  5232. /* Case:
  5233. * "while ...; do<whitespace><newline>
  5234. * cmd ..."
  5235. * would think that "cmd" starts in <whitespace> -
  5236. * i.e., at the previous line.
  5237. * We need to skip all whitespace before newlines.
  5238. */
  5239. while (ch != '\n') {
  5240. next = i_peek(input);
  5241. if (next != ' ' && next != '\t' && next != '\n')
  5242. break; /* next char is not ws */
  5243. ch = i_getch(input);
  5244. }
  5245. /* ch == last eaten whitespace char */
  5246. #endif
  5247. if (done_word(&ctx)) {
  5248. goto parse_error_exitcode1;
  5249. }
  5250. if (ch == '\n') {
  5251. /* Is this a case when newline is simply ignored?
  5252. * Some examples:
  5253. * "cmd | <newline> cmd ..."
  5254. * "case ... in <newline> word) ..."
  5255. */
  5256. if (IS_NULL_CMD(ctx.command)
  5257. && ctx.word.length == 0
  5258. && !ctx.word.has_quoted_part
  5259. && heredoc_cnt == 0
  5260. ) {
  5261. /* This newline can be ignored. But...
  5262. * Without check #1, interactive shell
  5263. * ignores even bare <newline>,
  5264. * and shows the continuation prompt:
  5265. * ps1_prompt$ <enter>
  5266. * ps2> _ <=== wrong, should be ps1
  5267. * Without check #2, "cmd & <newline>"
  5268. * is similarly mistreated.
  5269. * (BTW, this makes "cmd & cmd"
  5270. * and "cmd && cmd" non-orthogonal.
  5271. * Really, ask yourself, why
  5272. * "cmd && <newline>" doesn't start
  5273. * cmd but waits for more input?
  5274. * The only reason is that it might be
  5275. * a "cmd1 && <nl> cmd2 &" construct,
  5276. * cmd1 may need to run in BG).
  5277. */
  5278. struct pipe *pi = ctx.list_head;
  5279. if (pi->num_cmds != 0 /* check #1 */
  5280. && pi->followup != PIPE_BG /* check #2 */
  5281. ) {
  5282. continue;
  5283. }
  5284. }
  5285. /* Treat newline as a command separator. */
  5286. done_pipe(&ctx, PIPE_SEQ);
  5287. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5288. if (heredoc_cnt) {
  5289. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5290. if (heredoc_cnt != 0)
  5291. goto parse_error_exitcode1;
  5292. }
  5293. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5294. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5295. ch = ';';
  5296. /* note: if (is_blank) continue;
  5297. * will still trigger for us */
  5298. }
  5299. }
  5300. /* "cmd}" or "cmd }..." without semicolon or &:
  5301. * } is an ordinary char in this case, even inside { cmd; }
  5302. * Pathological example: { ""}; } should exec "}" cmd
  5303. */
  5304. if (ch == '}') {
  5305. if (ctx.word.length != 0 /* word} */
  5306. || ctx.word.has_quoted_part /* ""} */
  5307. ) {
  5308. goto ordinary_char;
  5309. }
  5310. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5311. /* Generally, there should be semicolon: "cmd; }"
  5312. * However, bash allows to omit it if "cmd" is
  5313. * a group. Examples:
  5314. * { { echo 1; } }
  5315. * {(echo 1)}
  5316. * { echo 0 >&2 | { echo 1; } }
  5317. * { while false; do :; done }
  5318. * { case a in b) ;; esac }
  5319. */
  5320. if (ctx.command->group)
  5321. goto term_group;
  5322. goto ordinary_char;
  5323. }
  5324. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5325. /* Can't be an end of {cmd}, skip the check */
  5326. goto skip_end_trigger;
  5327. /* else: } does terminate a group */
  5328. }
  5329. term_group:
  5330. if (end_trigger && end_trigger == ch
  5331. && (ch != ';' || heredoc_cnt == 0)
  5332. #if ENABLE_HUSH_CASE
  5333. && (ch != ')'
  5334. || ctx.ctx_res_w != RES_MATCH
  5335. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5336. )
  5337. #endif
  5338. ) {
  5339. if (done_word(&ctx)) {
  5340. goto parse_error_exitcode1;
  5341. }
  5342. done_pipe(&ctx, PIPE_SEQ);
  5343. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5344. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5345. /* Do we sit outside of any if's, loops or case's? */
  5346. if (!HAS_KEYWORDS
  5347. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5348. ) {
  5349. o_free_and_set_NULL(&ctx.word);
  5350. #if !BB_MMU
  5351. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5352. if (pstring)
  5353. *pstring = ctx.as_string.data;
  5354. else
  5355. o_free(&ctx.as_string);
  5356. #endif
  5357. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5358. /* Example: bare "{ }", "()" */
  5359. G.last_exitcode = 2; /* bash compat */
  5360. syntax_error_unexpected_ch(ch);
  5361. goto parse_error;
  5362. }
  5363. if (heredoc_cnt_ptr)
  5364. *heredoc_cnt_ptr = heredoc_cnt;
  5365. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5366. debug_printf_parse("parse_stream return %p: "
  5367. "end_trigger char found\n",
  5368. ctx.list_head);
  5369. debug_leave();
  5370. return ctx.list_head;
  5371. }
  5372. }
  5373. if (is_blank)
  5374. continue;
  5375. /* Catch <, > before deciding whether this word is
  5376. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5377. switch (ch) {
  5378. case '>':
  5379. redir_fd = redirect_opt_num(&ctx.word);
  5380. if (done_word(&ctx)) {
  5381. goto parse_error_exitcode1;
  5382. }
  5383. redir_style = REDIRECT_OVERWRITE;
  5384. if (next == '>') {
  5385. redir_style = REDIRECT_APPEND;
  5386. ch = i_getch(input);
  5387. nommu_addchr(&ctx.as_string, ch);
  5388. }
  5389. #if 0
  5390. else if (next == '(') {
  5391. syntax_error(">(process) not supported");
  5392. goto parse_error_exitcode1;
  5393. }
  5394. #endif
  5395. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5396. goto parse_error_exitcode1;
  5397. continue; /* get next char */
  5398. case '<':
  5399. redir_fd = redirect_opt_num(&ctx.word);
  5400. if (done_word(&ctx)) {
  5401. goto parse_error_exitcode1;
  5402. }
  5403. redir_style = REDIRECT_INPUT;
  5404. if (next == '<') {
  5405. redir_style = REDIRECT_HEREDOC;
  5406. heredoc_cnt++;
  5407. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5408. ch = i_getch(input);
  5409. nommu_addchr(&ctx.as_string, ch);
  5410. } else if (next == '>') {
  5411. redir_style = REDIRECT_IO;
  5412. ch = i_getch(input);
  5413. nommu_addchr(&ctx.as_string, ch);
  5414. }
  5415. #if 0
  5416. else if (next == '(') {
  5417. syntax_error("<(process) not supported");
  5418. goto parse_error_exitcode1;
  5419. }
  5420. #endif
  5421. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5422. goto parse_error_exitcode1;
  5423. continue; /* get next char */
  5424. case '#':
  5425. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5426. /* skip "#comment" */
  5427. /* note: we do not add it to &ctx.as_string */
  5428. /* TODO: in bash:
  5429. * comment inside $() goes to the next \n, even inside quoted string (!):
  5430. * cmd "$(cmd2 #comment)" - syntax error
  5431. * cmd "`cmd2 #comment`" - ok
  5432. * We accept both (comment ends where command subst ends, in both cases).
  5433. */
  5434. while (1) {
  5435. ch = i_peek(input);
  5436. if (ch == '\n') {
  5437. nommu_addchr(&ctx.as_string, '\n');
  5438. break;
  5439. }
  5440. ch = i_getch(input);
  5441. if (ch == EOF)
  5442. break;
  5443. }
  5444. continue; /* get next char */
  5445. }
  5446. break;
  5447. }
  5448. skip_end_trigger:
  5449. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5450. /* check that we are not in word in "a=1 2>word b=1": */
  5451. && !ctx.pending_redirect
  5452. ) {
  5453. /* ch is a special char and thus this word
  5454. * cannot be an assignment */
  5455. ctx.is_assignment = NOT_ASSIGNMENT;
  5456. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5457. }
  5458. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5459. switch (ch) {
  5460. case_SPECIAL_VAR_SYMBOL:
  5461. case SPECIAL_VAR_SYMBOL:
  5462. /* Convert raw ^C to corresponding special variable reference */
  5463. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5464. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5465. /* fall through */
  5466. case '#':
  5467. /* non-comment #: "echo a#b" etc */
  5468. o_addchr(&ctx.word, ch);
  5469. continue; /* get next char */
  5470. case '$':
  5471. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5472. continue; /* get next char */
  5473. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5474. debug_printf_parse("parse_stream parse error: "
  5475. "parse_dollar returned 0 (error)\n");
  5476. goto parse_error_exitcode1;
  5477. }
  5478. continue; /* get next char */
  5479. case '"':
  5480. ctx.word.has_quoted_part = 1;
  5481. if (next == '"' && !ctx.pending_redirect) {
  5482. i_getch(input); /* eat second " */
  5483. insert_empty_quoted_str_marker:
  5484. nommu_addchr(&ctx.as_string, next);
  5485. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5486. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5487. continue; /* get next char */
  5488. }
  5489. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5490. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5491. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5492. goto parse_error_exitcode1;
  5493. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5494. continue; /* get next char */
  5495. #if ENABLE_HUSH_TICK
  5496. case '`': {
  5497. USE_FOR_NOMMU(unsigned pos;)
  5498. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5499. o_addchr(&ctx.word, '`');
  5500. USE_FOR_NOMMU(pos = ctx.word.length;)
  5501. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5502. goto parse_error_exitcode1;
  5503. # if !BB_MMU
  5504. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5505. o_addchr(&ctx.as_string, '`');
  5506. # endif
  5507. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5508. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5509. continue; /* get next char */
  5510. }
  5511. #endif
  5512. case ';':
  5513. #if ENABLE_HUSH_CASE
  5514. case_semi:
  5515. #endif
  5516. if (done_word(&ctx)) {
  5517. goto parse_error_exitcode1;
  5518. }
  5519. done_pipe(&ctx, PIPE_SEQ);
  5520. #if ENABLE_HUSH_CASE
  5521. /* Eat multiple semicolons, detect
  5522. * whether it means something special */
  5523. while (1) {
  5524. ch = i_peek_and_eat_bkslash_nl(input);
  5525. if (ch != ';')
  5526. break;
  5527. ch = i_getch(input);
  5528. nommu_addchr(&ctx.as_string, ch);
  5529. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5530. ctx.ctx_dsemicolon = 1;
  5531. ctx.ctx_res_w = RES_MATCH;
  5532. break;
  5533. }
  5534. }
  5535. #endif
  5536. new_cmd:
  5537. /* We just finished a cmd. New one may start
  5538. * with an assignment */
  5539. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5540. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5541. continue; /* get next char */
  5542. case '&':
  5543. if (done_word(&ctx)) {
  5544. goto parse_error_exitcode1;
  5545. }
  5546. if (next == '&') {
  5547. ch = i_getch(input);
  5548. nommu_addchr(&ctx.as_string, ch);
  5549. done_pipe(&ctx, PIPE_AND);
  5550. } else {
  5551. done_pipe(&ctx, PIPE_BG);
  5552. }
  5553. goto new_cmd;
  5554. case '|':
  5555. if (done_word(&ctx)) {
  5556. goto parse_error_exitcode1;
  5557. }
  5558. #if ENABLE_HUSH_CASE
  5559. if (ctx.ctx_res_w == RES_MATCH)
  5560. break; /* we are in case's "word | word)" */
  5561. #endif
  5562. if (next == '|') { /* || */
  5563. ch = i_getch(input);
  5564. nommu_addchr(&ctx.as_string, ch);
  5565. done_pipe(&ctx, PIPE_OR);
  5566. } else {
  5567. /* we could pick up a file descriptor choice here
  5568. * with redirect_opt_num(), but bash doesn't do it.
  5569. * "echo foo 2| cat" yields "foo 2". */
  5570. done_command(&ctx);
  5571. }
  5572. goto new_cmd;
  5573. case '(':
  5574. #if ENABLE_HUSH_CASE
  5575. /* "case... in [(]word)..." - skip '(' */
  5576. if (ctx.ctx_res_w == RES_MATCH
  5577. && ctx.command->argv == NULL /* not (word|(... */
  5578. && ctx.word.length == 0 /* not word(... */
  5579. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5580. ) {
  5581. continue; /* get next char */
  5582. }
  5583. #endif
  5584. /* fall through */
  5585. case '{': {
  5586. int n = parse_group(&ctx, input, ch);
  5587. if (n < 0) {
  5588. goto parse_error_exitcode1;
  5589. }
  5590. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5591. heredoc_cnt += n;
  5592. goto new_cmd;
  5593. }
  5594. case ')':
  5595. #if ENABLE_HUSH_CASE
  5596. if (ctx.ctx_res_w == RES_MATCH)
  5597. goto case_semi;
  5598. #endif
  5599. case '}':
  5600. /* proper use of this character is caught by end_trigger:
  5601. * if we see {, we call parse_group(..., end_trigger='}')
  5602. * and it will match } earlier (not here). */
  5603. G.last_exitcode = 2;
  5604. syntax_error_unexpected_ch(ch);
  5605. goto parse_error;
  5606. default:
  5607. if (HUSH_DEBUG)
  5608. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5609. }
  5610. } /* while (1) */
  5611. parse_error_exitcode1:
  5612. G.last_exitcode = 1;
  5613. parse_error:
  5614. {
  5615. struct parse_context *pctx;
  5616. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5617. /* Clean up allocated tree.
  5618. * Sample for finding leaks on syntax error recovery path.
  5619. * Run it from interactive shell, watch pmap `pidof hush`.
  5620. * while if false; then false; fi; do break; fi
  5621. * Samples to catch leaks at execution:
  5622. * while if (true | { true;}); then echo ok; fi; do break; done
  5623. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5624. */
  5625. pctx = &ctx;
  5626. do {
  5627. /* Update pipe/command counts,
  5628. * otherwise freeing may miss some */
  5629. done_pipe(pctx, PIPE_SEQ);
  5630. debug_printf_clean("freeing list %p from ctx %p\n",
  5631. pctx->list_head, pctx);
  5632. debug_print_tree(pctx->list_head, 0);
  5633. free_pipe_list(pctx->list_head);
  5634. debug_printf_clean("freed list %p\n", pctx->list_head);
  5635. #if !BB_MMU
  5636. o_free(&pctx->as_string);
  5637. #endif
  5638. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5639. if (pctx != &ctx) {
  5640. free(pctx);
  5641. }
  5642. IF_HAS_KEYWORDS(pctx = p2;)
  5643. } while (HAS_KEYWORDS && pctx);
  5644. o_free(&ctx.word);
  5645. #if !BB_MMU
  5646. if (pstring)
  5647. *pstring = NULL;
  5648. #endif
  5649. debug_leave();
  5650. return ERR_PTR;
  5651. }
  5652. }
  5653. /*** Execution routines ***/
  5654. /* Expansion can recurse, need forward decls: */
  5655. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5656. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5657. expand_string_to_string(str)
  5658. #endif
  5659. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5660. #if ENABLE_HUSH_TICK
  5661. static int process_command_subs(o_string *dest, const char *s);
  5662. #endif
  5663. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5664. /* expand_strvec_to_strvec() takes a list of strings, expands
  5665. * all variable references within and returns a pointer to
  5666. * a list of expanded strings, possibly with larger number
  5667. * of strings. (Think VAR="a b"; echo $VAR).
  5668. * This new list is allocated as a single malloc block.
  5669. * NULL-terminated list of char* pointers is at the beginning of it,
  5670. * followed by strings themselves.
  5671. * Caller can deallocate entire list by single free(list). */
  5672. /* A horde of its helpers come first: */
  5673. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5674. {
  5675. while (--len >= 0) {
  5676. char c = *str++;
  5677. #if ENABLE_HUSH_BRACE_EXPANSION
  5678. if (c == '{' || c == '}') {
  5679. /* { -> \{, } -> \} */
  5680. o_addchr(o, '\\');
  5681. /* And now we want to add { or } and continue:
  5682. * o_addchr(o, c);
  5683. * continue;
  5684. * luckily, just falling through achieves this.
  5685. */
  5686. }
  5687. #endif
  5688. o_addchr(o, c);
  5689. if (c == '\\') {
  5690. /* \z -> \\\z; \<eol> -> \\<eol> */
  5691. o_addchr(o, '\\');
  5692. if (len) {
  5693. len--;
  5694. o_addchr(o, '\\');
  5695. o_addchr(o, *str++);
  5696. }
  5697. }
  5698. }
  5699. }
  5700. /* Store given string, finalizing the word and starting new one whenever
  5701. * we encounter IFS char(s). This is used for expanding variable values.
  5702. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5703. * Return in output->ended_in_ifs:
  5704. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5705. */
  5706. static int expand_on_ifs(o_string *output, int n, const char *str)
  5707. {
  5708. int last_is_ifs = 0;
  5709. while (1) {
  5710. int word_len;
  5711. if (!*str) /* EOL - do not finalize word */
  5712. break;
  5713. word_len = strcspn(str, G.ifs);
  5714. if (word_len) {
  5715. /* We have WORD_LEN leading non-IFS chars */
  5716. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5717. o_addblock(output, str, word_len);
  5718. } else {
  5719. /* Protect backslashes against globbing up :)
  5720. * Example: "v='\*'; echo b$v" prints "b\*"
  5721. * (and does not try to glob on "*")
  5722. */
  5723. o_addblock_duplicate_backslash(output, str, word_len);
  5724. /*/ Why can't we do it easier? */
  5725. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5726. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5727. }
  5728. last_is_ifs = 0;
  5729. str += word_len;
  5730. if (!*str) /* EOL - do not finalize word */
  5731. break;
  5732. }
  5733. /* We know str here points to at least one IFS char */
  5734. last_is_ifs = 1;
  5735. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5736. if (!*str) /* EOL - do not finalize word */
  5737. break;
  5738. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5739. && strchr(G.ifs, *str) /* the second check would fail */
  5740. ) {
  5741. /* This is a non-whitespace $IFS char */
  5742. /* Skip it and IFS whitespace chars, start new word */
  5743. str++;
  5744. str += strspn(str, G.ifs_whitespace);
  5745. goto new_word;
  5746. }
  5747. /* Start new word... but not always! */
  5748. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5749. if (output->has_quoted_part
  5750. /*
  5751. * Case "v=' a'; echo $v":
  5752. * here nothing precedes the space in $v expansion,
  5753. * therefore we should not finish the word
  5754. * (IOW: if there *is* word to finalize, only then do it):
  5755. * It's okay if this accesses the byte before first argv[]:
  5756. * past call to o_save_ptr() cleared it to zero byte
  5757. * (grep for -prev-ifs-check-).
  5758. */
  5759. || output->data[output->length - 1]
  5760. ) {
  5761. new_word:
  5762. o_addchr(output, '\0');
  5763. debug_print_list("expand_on_ifs", output, n);
  5764. n = o_save_ptr(output, n);
  5765. }
  5766. }
  5767. output->ended_in_ifs = last_is_ifs;
  5768. debug_print_list("expand_on_ifs[1]", output, n);
  5769. return n;
  5770. }
  5771. /* Helper to expand $((...)) and heredoc body. These act as if
  5772. * they are in double quotes, with the exception that they are not :).
  5773. * Just the rules are similar: "expand only $var and `cmd`"
  5774. *
  5775. * Returns malloced string.
  5776. * As an optimization, we return NULL if expansion is not needed.
  5777. */
  5778. static char *encode_then_expand_string(const char *str)
  5779. {
  5780. char *exp_str;
  5781. struct in_str input;
  5782. o_string dest = NULL_O_STRING;
  5783. const char *cp;
  5784. cp = str;
  5785. for (;;) {
  5786. if (!*cp) return NULL; /* string has no special chars */
  5787. if (*cp == '$') break;
  5788. if (*cp == '\\') break;
  5789. #if ENABLE_HUSH_TICK
  5790. if (*cp == '`') break;
  5791. #endif
  5792. cp++;
  5793. }
  5794. /* We need to expand. Example:
  5795. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5796. */
  5797. setup_string_in_str(&input, str);
  5798. encode_string(NULL, &dest, &input, EOF);
  5799. //TODO: error check (encode_string returns 0 on error)?
  5800. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5801. exp_str = expand_string_to_string(dest.data,
  5802. EXP_FLAG_ESC_GLOB_CHARS,
  5803. /*unbackslash:*/ 1
  5804. );
  5805. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5806. o_free(&dest);
  5807. return exp_str;
  5808. }
  5809. static const char *first_special_char_in_vararg(const char *cp)
  5810. {
  5811. for (;;) {
  5812. if (!*cp) return NULL; /* string has no special chars */
  5813. if (*cp == '$') return cp;
  5814. if (*cp == '\\') return cp;
  5815. if (*cp == '\'') return cp;
  5816. if (*cp == '"') return cp;
  5817. #if ENABLE_HUSH_TICK
  5818. if (*cp == '`') return cp;
  5819. #endif
  5820. /* dquoted "${x:+ARG}" should not glob, therefore
  5821. * '*' et al require some non-literal processing: */
  5822. if (*cp == '*') return cp;
  5823. if (*cp == '?') return cp;
  5824. if (*cp == '[') return cp;
  5825. cp++;
  5826. }
  5827. }
  5828. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5829. * These can contain single- and double-quoted strings,
  5830. * and treated as if the ARG string is initially unquoted. IOW:
  5831. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5832. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5833. * (word splitting and globbing of the ${var...} result).
  5834. */
  5835. #if !BASH_PATTERN_SUBST
  5836. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5837. encode_then_expand_vararg(str, handle_squotes)
  5838. #endif
  5839. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5840. {
  5841. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5842. const int do_unbackslash = 0;
  5843. #endif
  5844. char *exp_str;
  5845. struct in_str input;
  5846. o_string dest = NULL_O_STRING;
  5847. if (!first_special_char_in_vararg(str)) {
  5848. /* string has no special chars */
  5849. return NULL;
  5850. }
  5851. setup_string_in_str(&input, str);
  5852. dest.data = xzalloc(1); /* start as "", not as NULL */
  5853. exp_str = NULL;
  5854. for (;;) {
  5855. int ch;
  5856. ch = i_getch(&input);
  5857. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5858. __func__, ch, ch, !!dest.o_expflags);
  5859. if (!dest.o_expflags) {
  5860. if (ch == EOF)
  5861. break;
  5862. if (handle_squotes && ch == '\'') {
  5863. if (!add_till_single_quote_dquoted(&dest, &input))
  5864. goto ret; /* error */
  5865. continue;
  5866. }
  5867. }
  5868. if (ch == EOF) {
  5869. syntax_error_unterm_ch('"');
  5870. goto ret; /* error */
  5871. }
  5872. if (ch == '"') {
  5873. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5874. continue;
  5875. }
  5876. if (ch == '\\') {
  5877. ch = i_getch(&input);
  5878. if (ch == EOF) {
  5879. //example? error message? syntax_error_unterm_ch('"');
  5880. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5881. goto ret;
  5882. }
  5883. o_addqchr(&dest, ch);
  5884. continue;
  5885. }
  5886. if (ch == '$') {
  5887. if (parse_dollar_squote(NULL, &dest, &input))
  5888. continue;
  5889. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5890. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5891. goto ret;
  5892. }
  5893. continue;
  5894. }
  5895. #if ENABLE_HUSH_TICK
  5896. if (ch == '`') {
  5897. //unsigned pos = dest->length;
  5898. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5899. o_addchr(&dest, 0x80 | '`');
  5900. if (!add_till_backquote(&dest, &input,
  5901. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5902. )
  5903. ) {
  5904. goto ret; /* error */
  5905. }
  5906. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5907. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5908. continue;
  5909. }
  5910. #endif
  5911. o_addQchr(&dest, ch);
  5912. } /* for (;;) */
  5913. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5914. exp_str = expand_string_to_string(dest.data,
  5915. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5916. do_unbackslash
  5917. );
  5918. ret:
  5919. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5920. o_free(&dest);
  5921. return exp_str;
  5922. }
  5923. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5924. */
  5925. static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
  5926. char *str, int dquoted)
  5927. {
  5928. struct in_str input;
  5929. o_string dest = NULL_O_STRING;
  5930. if (!first_special_char_in_vararg(str)
  5931. && '\0' == str[strcspn(str, G.ifs)]
  5932. ) {
  5933. /* string has no special chars
  5934. * && string has no $IFS chars
  5935. */
  5936. if (dquoted) {
  5937. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5938. * set -- "${notexist-}"; echo $#
  5939. */
  5940. output->has_quoted_part = 1;
  5941. }
  5942. return expand_vars_to_list(output, n, str);
  5943. }
  5944. setup_string_in_str(&input, str);
  5945. for (;;) {
  5946. int ch;
  5947. ch = i_getch(&input);
  5948. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5949. __func__, ch, ch, dest.o_expflags);
  5950. if (!dest.o_expflags) {
  5951. if (ch == EOF)
  5952. break;
  5953. if (!dquoted && strchr(G.ifs, ch)) {
  5954. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5955. * do not assume we are at the start of the word (PREFIX above).
  5956. */
  5957. if (dest.data) {
  5958. n = expand_vars_to_list(output, n, dest.data);
  5959. o_free_and_set_NULL(&dest);
  5960. o_addchr(output, '\0');
  5961. n = o_save_ptr(output, n); /* create next word */
  5962. } else
  5963. if (output->length != o_get_last_ptr(output, n)
  5964. || output->has_quoted_part
  5965. ) {
  5966. /* For these cases:
  5967. * f() { for i; do echo "|$i|"; done; }; x=x
  5968. * f a${x:+ }b # 1st condition
  5969. * |a|
  5970. * |b|
  5971. * f ""${x:+ }b # 2nd condition
  5972. * ||
  5973. * |b|
  5974. */
  5975. o_addchr(output, '\0');
  5976. n = o_save_ptr(output, n); /* create next word */
  5977. }
  5978. continue;
  5979. }
  5980. if (!dquoted && ch == '\'') {
  5981. if (!add_till_single_quote_dquoted(&dest, &input))
  5982. goto ret; /* error */
  5983. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5984. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5985. continue;
  5986. }
  5987. }
  5988. if (ch == EOF) {
  5989. syntax_error_unterm_ch('"');
  5990. goto ret; /* error */
  5991. }
  5992. if (ch == '"') {
  5993. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5994. if (dest.o_expflags) {
  5995. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5996. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5997. }
  5998. continue;
  5999. }
  6000. if (ch == '\\') {
  6001. ch = i_getch(&input);
  6002. if (ch == EOF) {
  6003. //example? error message? syntax_error_unterm_ch('"');
  6004. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  6005. goto ret;
  6006. }
  6007. o_addqchr(&dest, ch);
  6008. continue;
  6009. }
  6010. if (ch == '$') {
  6011. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6012. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6013. goto ret;
  6014. }
  6015. continue;
  6016. }
  6017. #if ENABLE_HUSH_TICK
  6018. if (ch == '`') {
  6019. //unsigned pos = dest->length;
  6020. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6021. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6022. if (!add_till_backquote(&dest, &input,
  6023. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6024. )
  6025. ) {
  6026. goto ret; /* error */
  6027. }
  6028. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6029. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6030. continue;
  6031. }
  6032. #endif
  6033. if (dquoted) {
  6034. /* Always glob-protect if in dquotes:
  6035. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6036. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6037. */
  6038. o_addqchr(&dest, ch);
  6039. } else {
  6040. /* Glob-protect only if char is quoted:
  6041. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6042. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6043. */
  6044. o_addQchr(&dest, ch);
  6045. }
  6046. } /* for (;;) */
  6047. if (dest.data) {
  6048. n = expand_vars_to_list(output, n, dest.data);
  6049. }
  6050. ret:
  6051. o_free(&dest);
  6052. return n;
  6053. }
  6054. #if ENABLE_FEATURE_SH_MATH
  6055. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6056. {
  6057. arith_state_t math_state;
  6058. arith_t res;
  6059. char *exp_str;
  6060. math_state.lookupvar = get_local_var_value;
  6061. math_state.setvar = set_local_var_from_halves;
  6062. //math_state.endofname = endofname;
  6063. exp_str = encode_then_expand_string(arg);
  6064. res = arith(&math_state, exp_str ? exp_str : arg);
  6065. free(exp_str);
  6066. if (errmsg_p)
  6067. *errmsg_p = math_state.errmsg;
  6068. if (math_state.errmsg)
  6069. msg_and_die_if_script(math_state.errmsg);
  6070. return res;
  6071. }
  6072. #endif
  6073. #if BASH_PATTERN_SUBST
  6074. /* ${var/[/]pattern[/repl]} helpers */
  6075. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6076. {
  6077. int first_escaped = (pattern[0] == '\\' && pattern[1]);
  6078. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6079. * as literal too (as it is semi-common, and easy to accomodate
  6080. * by just using str + 1).
  6081. */
  6082. int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
  6083. if ((pattern + first_escaped * 2)[sz] == '\0') {
  6084. /* Optimization for trivial patterns.
  6085. * Testcase for very slow replace (performs about 22k replaces):
  6086. * x=::::::::::::::::::::::
  6087. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6088. * echo "${x//:/|}"
  6089. */
  6090. *size = sz + first_escaped;
  6091. return strstr(val, pattern + first_escaped);
  6092. }
  6093. while (1) {
  6094. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6095. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6096. if (end) {
  6097. *size = end - val;
  6098. return val;
  6099. }
  6100. if (*val == '\0')
  6101. return NULL;
  6102. /* Optimization: if "*pat" did not match the start of "string",
  6103. * we know that "tring", "ring" etc will not match too:
  6104. */
  6105. if (pattern[0] == '*')
  6106. return NULL;
  6107. val++;
  6108. }
  6109. }
  6110. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6111. {
  6112. char *result = NULL;
  6113. unsigned res_len = 0;
  6114. unsigned repl_len = strlen(repl);
  6115. /* Null pattern never matches, including if "var" is empty */
  6116. if (!pattern[0])
  6117. return result; /* NULL, no replaces happened */
  6118. while (1) {
  6119. int size;
  6120. char *s = strstr_pattern(val, pattern, &size);
  6121. if (!s)
  6122. break;
  6123. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6124. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6125. res_len += (s - val) + repl_len;
  6126. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6127. val = s + size;
  6128. if (exp_op == '/')
  6129. break;
  6130. }
  6131. if (*val && result) {
  6132. result = xrealloc(result, res_len + strlen(val) + 1);
  6133. strcpy(result + res_len, val);
  6134. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6135. }
  6136. debug_printf_varexp("result:'%s'\n", result);
  6137. return result;
  6138. }
  6139. #endif /* BASH_PATTERN_SUBST */
  6140. static int append_str_maybe_ifs_split(o_string *output, int n,
  6141. int first_ch, const char *val)
  6142. {
  6143. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6144. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6145. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6146. if (val && val[0])
  6147. n = expand_on_ifs(output, n, val);
  6148. } else { /* quoted "$VAR" */
  6149. output->has_quoted_part = 1;
  6150. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6151. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6152. if (val && val[0])
  6153. o_addQstr(output, val);
  6154. }
  6155. return n;
  6156. }
  6157. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6158. */
  6159. static NOINLINE int expand_one_var(o_string *output, int n,
  6160. int first_ch, char *arg, char **pp)
  6161. {
  6162. const char *val;
  6163. char *to_be_freed;
  6164. char *p;
  6165. char *var;
  6166. char exp_op;
  6167. char exp_save = exp_save; /* for compiler */
  6168. char *exp_saveptr; /* points to expansion operator */
  6169. char *exp_word = exp_word; /* for compiler */
  6170. char arg0;
  6171. val = NULL;
  6172. to_be_freed = NULL;
  6173. p = *pp;
  6174. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6175. var = arg;
  6176. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6177. arg0 = arg[0];
  6178. arg[0] = (arg0 & 0x7f);
  6179. exp_op = 0;
  6180. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6181. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6182. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6183. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6184. ) {
  6185. /* It must be length operator: ${#var} */
  6186. var++;
  6187. exp_op = 'L';
  6188. } else {
  6189. /* Maybe handle parameter expansion */
  6190. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6191. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6192. ) {
  6193. /* ${?:0}, ${#[:]%0} etc */
  6194. exp_saveptr = var + 1;
  6195. } else {
  6196. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6197. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6198. }
  6199. exp_op = exp_save = *exp_saveptr;
  6200. if (exp_op) {
  6201. exp_word = exp_saveptr + 1;
  6202. if (exp_op == ':') {
  6203. exp_op = *exp_word++;
  6204. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6205. if (BASH_SUBSTR
  6206. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6207. ) {
  6208. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6209. exp_op = ':';
  6210. exp_word--;
  6211. }
  6212. }
  6213. *exp_saveptr = '\0';
  6214. } /* else: it's not an expansion op, but bare ${var} */
  6215. }
  6216. /* Look up the variable in question */
  6217. if (isdigit(var[0])) {
  6218. /* parse_dollar should have vetted var for us */
  6219. int nn = xatoi_positive(var);
  6220. if (nn < G.global_argc)
  6221. val = G.global_argv[nn];
  6222. /* else val remains NULL: $N with too big N */
  6223. } else {
  6224. switch (var[0]) {
  6225. case '$': /* pid */
  6226. val = utoa(G.root_pid);
  6227. break;
  6228. case '!': /* bg pid */
  6229. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6230. break;
  6231. case '?': /* exitcode */
  6232. val = utoa(G.last_exitcode);
  6233. break;
  6234. case '#': /* argc */
  6235. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6236. break;
  6237. case '-': { /* active options */
  6238. /* Check set_mode() to see what option chars we support */
  6239. char *cp;
  6240. val = cp = G.optstring_buf;
  6241. if (G.o_opt[OPT_O_ERREXIT])
  6242. *cp++ = 'e';
  6243. if (G_interactive_fd)
  6244. *cp++ = 'i';
  6245. if (G_x_mode)
  6246. *cp++ = 'x';
  6247. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6248. * commands read but are not executed,
  6249. * so $- can not execute too, 'n' is never seen in $-.
  6250. */
  6251. if (G.opt_c)
  6252. *cp++ = 'c';
  6253. if (G.opt_s)
  6254. *cp++ = 's';
  6255. *cp = '\0';
  6256. break;
  6257. }
  6258. default:
  6259. val = get_local_var_value(var);
  6260. }
  6261. }
  6262. /* Handle any expansions */
  6263. if (exp_op == 'L') {
  6264. reinit_unicode_for_hush();
  6265. debug_printf_expand("expand: length(%s)=", val);
  6266. val = utoa(val ? unicode_strlen(val) : 0);
  6267. debug_printf_expand("%s\n", val);
  6268. } else if (exp_op) {
  6269. if (exp_op == '%' || exp_op == '#') {
  6270. /* Standard-mandated substring removal ops:
  6271. * ${parameter%word} - remove smallest suffix pattern
  6272. * ${parameter%%word} - remove largest suffix pattern
  6273. * ${parameter#word} - remove smallest prefix pattern
  6274. * ${parameter##word} - remove largest prefix pattern
  6275. *
  6276. * Word is expanded to produce a glob pattern.
  6277. * Then var's value is matched to it and matching part removed.
  6278. */
  6279. /* bash compat: if x is "" and no shrinking of it is possible,
  6280. * inner ${...} is not evaluated. Example:
  6281. * unset b; : ${a%${b=B}}; echo $b
  6282. * assignment b=B only happens if $a is not "".
  6283. */
  6284. if (val && val[0]) {
  6285. char *t;
  6286. char *exp_exp_word;
  6287. char *loc;
  6288. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6289. if (exp_op == *exp_word) /* ## or %% */
  6290. exp_word++;
  6291. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6292. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6293. if (exp_exp_word)
  6294. exp_word = exp_exp_word;
  6295. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6296. /*
  6297. * HACK ALERT. We depend here on the fact that
  6298. * G.global_argv and results of utoa and get_local_var_value
  6299. * are actually in writable memory:
  6300. * scan_and_match momentarily stores NULs there.
  6301. */
  6302. t = (char*)val;
  6303. loc = scan_and_match(t, exp_word, scan_flags);
  6304. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6305. free(exp_exp_word);
  6306. if (loc) { /* match was found */
  6307. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6308. val = loc; /* take right part */
  6309. else /* %[%] */
  6310. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6311. }
  6312. }
  6313. }
  6314. #if BASH_PATTERN_SUBST
  6315. else if (exp_op == '/' || exp_op == '\\') {
  6316. /* It's ${var/[/]pattern[/repl]} thing.
  6317. * Note that in encoded form it has TWO parts:
  6318. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6319. * and if // is used, it is encoded as \:
  6320. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6321. */
  6322. /* bash compat: if var is "", both pattern and repl
  6323. * are still evaluated, if it is unset, then not:
  6324. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6325. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6326. */
  6327. if (val /*&& val[0]*/) {
  6328. /* pattern uses non-standard expansion.
  6329. * repl should be unbackslashed and globbed
  6330. * by the usual expansion rules:
  6331. * >az >bz
  6332. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6333. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6334. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6335. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6336. * (note that a*z _pattern_ is never globbed!)
  6337. */
  6338. char *pattern, *repl, *t;
  6339. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6340. if (!pattern)
  6341. pattern = xstrdup(exp_word);
  6342. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6343. *p++ = SPECIAL_VAR_SYMBOL;
  6344. exp_word = p;
  6345. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6346. *p = '\0';
  6347. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6348. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6349. /* HACK ALERT. We depend here on the fact that
  6350. * G.global_argv and results of utoa and get_local_var_value
  6351. * are actually in writable memory:
  6352. * replace_pattern momentarily stores NULs there. */
  6353. t = (char*)val;
  6354. to_be_freed = replace_pattern(t,
  6355. pattern,
  6356. (repl ? repl : exp_word),
  6357. exp_op);
  6358. if (to_be_freed) /* at least one replace happened */
  6359. val = to_be_freed;
  6360. free(pattern);
  6361. free(repl);
  6362. } else {
  6363. /* Unset variable always gives nothing */
  6364. // a=; echo ${a/*/w} # "w"
  6365. // unset a; echo ${a/*/w} # ""
  6366. /* Just skip "replace" part */
  6367. *p++ = SPECIAL_VAR_SYMBOL;
  6368. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6369. *p = '\0';
  6370. }
  6371. }
  6372. #endif /* BASH_PATTERN_SUBST */
  6373. else if (exp_op == ':') {
  6374. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6375. /* It's ${var:N[:M]} bashism.
  6376. * Note that in encoded form it has TWO parts:
  6377. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6378. */
  6379. arith_t beg, len;
  6380. unsigned vallen;
  6381. const char *errmsg;
  6382. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6383. if (errmsg)
  6384. goto empty_result;
  6385. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6386. *p++ = SPECIAL_VAR_SYMBOL;
  6387. exp_word = p;
  6388. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6389. *p = '\0';
  6390. vallen = val ? strlen(val) : 0;
  6391. if (beg < 0) {
  6392. /* negative beg counts from the end */
  6393. beg = (arith_t)vallen + beg;
  6394. }
  6395. /* If expansion will be empty, do not even evaluate len */
  6396. if (!val || beg < 0 || beg > vallen) {
  6397. /* Why > vallen, not >=? bash:
  6398. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6399. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6400. */
  6401. goto empty_result;
  6402. }
  6403. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6404. if (errmsg)
  6405. goto empty_result;
  6406. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6407. debug_printf_varexp("from val:'%s'\n", val);
  6408. if (len < 0) {
  6409. /* in bash, len=-n means strlen()-n */
  6410. len = (arith_t)vallen - beg + len;
  6411. if (len < 0) /* bash compat */
  6412. msg_and_die_if_script("%s: substring expression < 0", var);
  6413. }
  6414. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6415. empty_result:
  6416. val = NULL;
  6417. } else {
  6418. /* Paranoia. What if user entered 9999999999999
  6419. * which fits in arith_t but not int? */
  6420. if (len > INT_MAX)
  6421. len = INT_MAX;
  6422. val = to_be_freed = xstrndup(val + beg, len);
  6423. }
  6424. debug_printf_varexp("val:'%s'\n", val);
  6425. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6426. msg_and_die_if_script("malformed ${%s:...}", var);
  6427. val = NULL;
  6428. #endif
  6429. } else { /* one of "-=+?" */
  6430. /* Standard-mandated substitution ops:
  6431. * ${var?word} - indicate error if unset
  6432. * If var is unset, word (or a message indicating it is unset
  6433. * if word is null) is written to standard error
  6434. * and the shell exits with a non-zero exit status.
  6435. * Otherwise, the value of var is substituted.
  6436. * ${var-word} - use default value
  6437. * If var is unset, word is substituted.
  6438. * ${var=word} - assign and use default value
  6439. * If var is unset, word is assigned to var.
  6440. * In all cases, final value of var is substituted.
  6441. * ${var+word} - use alternative value
  6442. * If var is unset, null is substituted.
  6443. * Otherwise, word is substituted.
  6444. *
  6445. * Word is subjected to tilde expansion, parameter expansion,
  6446. * command substitution, and arithmetic expansion.
  6447. * If word is not needed, it is not expanded.
  6448. *
  6449. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6450. * but also treat null var as if it is unset.
  6451. *
  6452. * Word-splitting and single quote behavior:
  6453. *
  6454. * $ f() { for i; do echo "|$i|"; done; }
  6455. *
  6456. * $ x=; f ${x:?'x y' z}; echo $?
  6457. * bash: x: x y z # neither f nor "echo $?" executes
  6458. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6459. * $ x=; f "${x:?'x y' z}"
  6460. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6461. *
  6462. * $ x=; f ${x:='x y' z}
  6463. * |x|
  6464. * |y|
  6465. * |z|
  6466. * $ x=; f "${x:='x y' z}"
  6467. * |'x y' z|
  6468. *
  6469. * $ x=x; f ${x:+'x y' z}
  6470. * |x y|
  6471. * |z|
  6472. * $ x=x; f "${x:+'x y' z}"
  6473. * |'x y' z|
  6474. *
  6475. * $ x=; f ${x:-'x y' z}
  6476. * |x y|
  6477. * |z|
  6478. * $ x=; f "${x:-'x y' z}"
  6479. * |'x y' z|
  6480. */
  6481. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6482. if (exp_op == '+')
  6483. use_word = !use_word;
  6484. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6485. (exp_save == ':') ? "true" : "false", use_word);
  6486. if (use_word) {
  6487. if (exp_op == '+' || exp_op == '-') {
  6488. /* ${var+word} - use alternative value */
  6489. /* ${var-word} - use default value */
  6490. n = encode_then_append_var_plusminus(output, n, exp_word,
  6491. /*dquoted:*/ (arg0 & 0x80)
  6492. );
  6493. val = NULL;
  6494. } else {
  6495. /* ${var?word} - indicate error if unset */
  6496. /* ${var=word} - assign and use default value */
  6497. to_be_freed = encode_then_expand_vararg(exp_word,
  6498. /*handle_squotes:*/ !(arg0 & 0x80),
  6499. /*unbackslash:*/ 0
  6500. );
  6501. if (to_be_freed)
  6502. exp_word = to_be_freed;
  6503. if (exp_op == '?') {
  6504. /* mimic bash message */
  6505. msg_and_die_if_script("%s: %s",
  6506. var,
  6507. exp_word[0]
  6508. ? exp_word
  6509. : "parameter null or not set"
  6510. /* ash has more specific messages, a-la: */
  6511. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6512. );
  6513. //TODO: how interactive bash aborts expansion mid-command?
  6514. //It aborts the entire line, returns to prompt:
  6515. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6516. // bash: x: x y z
  6517. // $
  6518. // ("echo YO" is not executed, neither the f function call)
  6519. } else {
  6520. val = exp_word;
  6521. }
  6522. if (exp_op == '=') {
  6523. /* ${var=[word]} or ${var:=[word]} */
  6524. if (isdigit(var[0]) || var[0] == '#') {
  6525. /* mimic bash message */
  6526. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6527. val = NULL;
  6528. } else {
  6529. char *new_var = xasprintf("%s=%s", var, val);
  6530. set_local_var(new_var, /*flag:*/ 0);
  6531. }
  6532. }
  6533. }
  6534. }
  6535. } /* one of "-=+?" */
  6536. *exp_saveptr = exp_save;
  6537. } /* if (exp_op) */
  6538. arg[0] = arg0;
  6539. *pp = p;
  6540. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6541. free(to_be_freed);
  6542. return n;
  6543. }
  6544. /* Expand all variable references in given string, adding words to list[]
  6545. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6546. * to be filled). This routine is extremely tricky: has to deal with
  6547. * variables/parameters with whitespace, $* and $@, and constructs like
  6548. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6549. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6550. {
  6551. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6552. * expansion of right-hand side of assignment == 1-element expand.
  6553. */
  6554. char cant_be_null = 0; /* only bit 0x80 matters */
  6555. char *p;
  6556. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6557. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6558. debug_print_list("expand_vars_to_list[0]", output, n);
  6559. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6560. char first_ch;
  6561. #if ENABLE_FEATURE_SH_MATH
  6562. char arith_buf[sizeof(arith_t)*3 + 2];
  6563. #endif
  6564. if (output->ended_in_ifs) {
  6565. o_addchr(output, '\0');
  6566. n = o_save_ptr(output, n);
  6567. output->ended_in_ifs = 0;
  6568. }
  6569. o_addblock(output, arg, p - arg);
  6570. debug_print_list("expand_vars_to_list[1]", output, n);
  6571. arg = ++p;
  6572. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6573. /* Fetch special var name (if it is indeed one of them)
  6574. * and quote bit, force the bit on if singleword expansion -
  6575. * important for not getting v=$@ expand to many words. */
  6576. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6577. /* Is this variable quoted and thus expansion can't be null?
  6578. * "$@" is special. Even if quoted, it can still
  6579. * expand to nothing (not even an empty string),
  6580. * thus it is excluded. */
  6581. if ((first_ch & 0x7f) != '@')
  6582. cant_be_null |= first_ch;
  6583. switch (first_ch & 0x7f) {
  6584. /* Highest bit in first_ch indicates that var is double-quoted */
  6585. case '*':
  6586. case '@': {
  6587. int i;
  6588. if (!G.global_argv[1])
  6589. break;
  6590. i = 1;
  6591. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6592. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6593. while (G.global_argv[i]) {
  6594. n = expand_on_ifs(output, n, G.global_argv[i]);
  6595. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6596. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6597. /* this argv[] is not empty and not last:
  6598. * put terminating NUL, start new word */
  6599. o_addchr(output, '\0');
  6600. debug_print_list("expand_vars_to_list[2]", output, n);
  6601. n = o_save_ptr(output, n);
  6602. debug_print_list("expand_vars_to_list[3]", output, n);
  6603. }
  6604. }
  6605. } else
  6606. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6607. * and in this case should treat it like '$*' - see 'else...' below */
  6608. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6609. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6610. ) {
  6611. while (1) {
  6612. o_addQstr(output, G.global_argv[i]);
  6613. if (++i >= G.global_argc)
  6614. break;
  6615. o_addchr(output, '\0');
  6616. debug_print_list("expand_vars_to_list[4]", output, n);
  6617. n = o_save_ptr(output, n);
  6618. }
  6619. } else { /* quoted $* (or v="$@" case): add as one word */
  6620. while (1) {
  6621. o_addQstr(output, G.global_argv[i]);
  6622. if (!G.global_argv[++i])
  6623. break;
  6624. if (G.ifs[0])
  6625. o_addchr(output, G.ifs[0]);
  6626. }
  6627. output->has_quoted_part = 1;
  6628. }
  6629. break;
  6630. }
  6631. case SPECIAL_VAR_SYMBOL: {
  6632. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6633. /* "Empty variable", used to make "" etc to not disappear */
  6634. output->has_quoted_part = 1;
  6635. cant_be_null = 0x80;
  6636. arg++;
  6637. break;
  6638. }
  6639. case SPECIAL_VAR_QUOTED_SVS:
  6640. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6641. /* "^C variable", represents literal ^C char (possible in scripts) */
  6642. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6643. arg++;
  6644. break;
  6645. #if ENABLE_HUSH_TICK
  6646. case '`': {
  6647. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6648. o_string subst_result = NULL_O_STRING;
  6649. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6650. arg++;
  6651. /* Can't just stuff it into output o_string,
  6652. * expanded result may need to be globbed
  6653. * and $IFS-split */
  6654. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6655. G.last_exitcode = process_command_subs(&subst_result, arg);
  6656. G.expand_exitcode = G.last_exitcode;
  6657. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6658. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6659. o_free(&subst_result);
  6660. break;
  6661. }
  6662. #endif
  6663. #if ENABLE_FEATURE_SH_MATH
  6664. case '+': {
  6665. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6666. arith_t res;
  6667. arg++; /* skip '+' */
  6668. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6669. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6670. res = expand_and_evaluate_arith(arg, NULL);
  6671. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6672. sprintf(arith_buf, ARITH_FMT, res);
  6673. if (res < 0
  6674. && first_ch == (char)('+'|0x80)
  6675. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6676. ) {
  6677. /* Quoted negative ariths, like filename[0"$((-9))"],
  6678. * should not be interpreted as glob ranges.
  6679. * Convert leading '-' to '\-':
  6680. */
  6681. o_grow_by(output, 1);
  6682. output->data[output->length++] = '\\';
  6683. }
  6684. o_addstr(output, arith_buf);
  6685. break;
  6686. }
  6687. #endif
  6688. default:
  6689. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6690. n = expand_one_var(output, n, first_ch, arg, &p);
  6691. break;
  6692. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6693. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6694. * Do the check to avoid writing to a const string. */
  6695. if (*p != SPECIAL_VAR_SYMBOL)
  6696. *p = SPECIAL_VAR_SYMBOL;
  6697. arg = ++p;
  6698. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6699. if (*arg) {
  6700. /* handle trailing string */
  6701. if (output->ended_in_ifs) {
  6702. o_addchr(output, '\0');
  6703. n = o_save_ptr(output, n);
  6704. }
  6705. debug_print_list("expand_vars_to_list[a]", output, n);
  6706. /* this part is literal, and it was already pre-quoted
  6707. * if needed (much earlier), do not use o_addQstr here!
  6708. */
  6709. o_addstr(output, arg);
  6710. debug_print_list("expand_vars_to_list[b]", output, n);
  6711. } else
  6712. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6713. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6714. && !output->has_quoted_part
  6715. ) {
  6716. n--;
  6717. /* allow to reuse list[n] later without re-growth */
  6718. output->has_empty_slot = 1;
  6719. }
  6720. return n;
  6721. }
  6722. static char **expand_variables(char **argv, unsigned expflags)
  6723. {
  6724. int n;
  6725. char **list;
  6726. o_string output = NULL_O_STRING;
  6727. output.o_expflags = expflags;
  6728. n = 0;
  6729. for (;;) {
  6730. /* go to next list[n] */
  6731. output.ended_in_ifs = 0;
  6732. n = o_save_ptr(&output, n);
  6733. if (!*argv)
  6734. break;
  6735. /* expand argv[i] */
  6736. n = expand_vars_to_list(&output, n, *argv++);
  6737. /* if (!output->has_empty_slot) -- need this?? */
  6738. o_addchr(&output, '\0');
  6739. }
  6740. debug_print_list("expand_variables", &output, n);
  6741. /* output.data (malloced in one block) gets returned in "list" */
  6742. list = o_finalize_list(&output, n);
  6743. debug_print_strings("expand_variables[1]", list);
  6744. return list;
  6745. }
  6746. static char **expand_strvec_to_strvec(char **argv)
  6747. {
  6748. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6749. }
  6750. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6751. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6752. {
  6753. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6754. }
  6755. #endif
  6756. /* Used for expansion of right hand of assignments,
  6757. * $((...)), heredocs, variable expansion parts.
  6758. *
  6759. * NB: should NOT do globbing!
  6760. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6761. */
  6762. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6763. {
  6764. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6765. const int do_unbackslash = 1;
  6766. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6767. #endif
  6768. char *argv[2], **list;
  6769. debug_printf_expand("string_to_string<='%s'\n", str);
  6770. /* This is generally an optimization, but it also
  6771. * handles "", which otherwise trips over !list[0] check below.
  6772. * (is this ever happens that we actually get str="" here?)
  6773. */
  6774. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6775. //TODO: Can use on strings with \ too, just unbackslash() them?
  6776. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6777. return xstrdup(str);
  6778. }
  6779. argv[0] = (char*)str;
  6780. argv[1] = NULL;
  6781. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6782. if (!list[0]) {
  6783. /* Example where it happens:
  6784. * x=; echo ${x:-"$@"}
  6785. */
  6786. ((char*)list)[0] = '\0';
  6787. } else {
  6788. if (HUSH_DEBUG)
  6789. if (list[1])
  6790. bb_simple_error_msg_and_die("BUG in varexp2");
  6791. /* actually, just move string 2*sizeof(char*) bytes back */
  6792. overlapping_strcpy((char*)list, list[0]);
  6793. if (do_unbackslash)
  6794. unbackslash((char*)list);
  6795. }
  6796. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6797. return (char*)list;
  6798. }
  6799. #if 0
  6800. static char* expand_strvec_to_string(char **argv)
  6801. {
  6802. char **list;
  6803. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6804. /* Convert all NULs to spaces */
  6805. if (list[0]) {
  6806. int n = 1;
  6807. while (list[n]) {
  6808. if (HUSH_DEBUG)
  6809. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6810. bb_error_msg_and_die("BUG in varexp3");
  6811. /* bash uses ' ' regardless of $IFS contents */
  6812. list[n][-1] = ' ';
  6813. n++;
  6814. }
  6815. }
  6816. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6817. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6818. return (char*)list;
  6819. }
  6820. #endif
  6821. static char **expand_assignments(char **argv, int count)
  6822. {
  6823. int i;
  6824. char **p;
  6825. G.expanded_assignments = p = NULL;
  6826. /* Expand assignments into one string each */
  6827. for (i = 0; i < count; i++) {
  6828. p = add_string_to_strings(p,
  6829. expand_string_to_string(argv[i],
  6830. EXP_FLAG_ESC_GLOB_CHARS,
  6831. /*unbackslash:*/ 1
  6832. )
  6833. );
  6834. G.expanded_assignments = p;
  6835. }
  6836. G.expanded_assignments = NULL;
  6837. return p;
  6838. }
  6839. static void switch_off_special_sigs(unsigned mask)
  6840. {
  6841. unsigned sig = 0;
  6842. while ((mask >>= 1) != 0) {
  6843. sig++;
  6844. if (!(mask & 1))
  6845. continue;
  6846. #if ENABLE_HUSH_TRAP
  6847. if (G_traps) {
  6848. if (G_traps[sig] && !G_traps[sig][0])
  6849. /* trap is '', has to remain SIG_IGN */
  6850. continue;
  6851. free(G_traps[sig]);
  6852. G_traps[sig] = NULL;
  6853. }
  6854. #endif
  6855. /* We are here only if no trap or trap was not '' */
  6856. install_sighandler(sig, SIG_DFL);
  6857. }
  6858. }
  6859. #if BB_MMU
  6860. /* never called */
  6861. void re_execute_shell(char ***to_free, const char *s,
  6862. char *g_argv0, char **g_argv,
  6863. char **builtin_argv) NORETURN;
  6864. static void reset_traps_to_defaults(void)
  6865. {
  6866. /* This function is always called in a child shell
  6867. * after fork (not vfork, NOMMU doesn't use this function).
  6868. */
  6869. IF_HUSH_TRAP(unsigned sig;)
  6870. unsigned mask;
  6871. /* Child shells are not interactive.
  6872. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6873. * Testcase: (while :; do :; done) + ^Z should background.
  6874. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6875. */
  6876. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6877. if (!G_traps && !mask)
  6878. return; /* already no traps and no special sigs */
  6879. /* Switch off special sigs */
  6880. switch_off_special_sigs(mask);
  6881. # if ENABLE_HUSH_JOB
  6882. G_fatal_sig_mask = 0;
  6883. # endif
  6884. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6885. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6886. * remain set in G.special_sig_mask */
  6887. # if ENABLE_HUSH_TRAP
  6888. if (!G_traps)
  6889. return;
  6890. /* Reset all sigs to default except ones with empty traps */
  6891. for (sig = 0; sig < NSIG; sig++) {
  6892. if (!G_traps[sig])
  6893. continue; /* no trap: nothing to do */
  6894. if (!G_traps[sig][0])
  6895. continue; /* empty trap: has to remain SIG_IGN */
  6896. /* sig has non-empty trap, reset it: */
  6897. free(G_traps[sig]);
  6898. G_traps[sig] = NULL;
  6899. /* There is no signal for trap 0 (EXIT) */
  6900. if (sig == 0)
  6901. continue;
  6902. install_sighandler(sig, pick_sighandler(sig));
  6903. }
  6904. # endif
  6905. }
  6906. #else /* !BB_MMU */
  6907. static void re_execute_shell(char ***to_free, const char *s,
  6908. char *g_argv0, char **g_argv,
  6909. char **builtin_argv) NORETURN;
  6910. static void re_execute_shell(char ***to_free, const char *s,
  6911. char *g_argv0, char **g_argv,
  6912. char **builtin_argv)
  6913. {
  6914. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6915. /* delims + 2 * (number of bytes in printed hex numbers) */
  6916. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6917. char *heredoc_argv[4];
  6918. struct variable *cur;
  6919. # if ENABLE_HUSH_FUNCTIONS
  6920. struct function *funcp;
  6921. # endif
  6922. char **argv, **pp;
  6923. unsigned cnt;
  6924. unsigned long long empty_trap_mask;
  6925. if (!g_argv0) { /* heredoc */
  6926. argv = heredoc_argv;
  6927. argv[0] = (char *) G.argv0_for_re_execing;
  6928. argv[1] = (char *) "-<";
  6929. argv[2] = (char *) s;
  6930. argv[3] = NULL;
  6931. pp = &argv[3]; /* used as pointer to empty environment */
  6932. goto do_exec;
  6933. }
  6934. cnt = 0;
  6935. pp = builtin_argv;
  6936. if (pp) while (*pp++)
  6937. cnt++;
  6938. empty_trap_mask = 0;
  6939. if (G_traps) {
  6940. int sig;
  6941. for (sig = 1; sig < NSIG; sig++) {
  6942. if (G_traps[sig] && !G_traps[sig][0])
  6943. empty_trap_mask |= 1LL << sig;
  6944. }
  6945. }
  6946. sprintf(param_buf, NOMMU_HACK_FMT
  6947. , (unsigned) G.root_pid
  6948. , (unsigned) G.root_ppid
  6949. , (unsigned) G.last_bg_pid
  6950. , (unsigned) G.last_exitcode
  6951. , cnt
  6952. , empty_trap_mask
  6953. IF_HUSH_LOOPS(, G.depth_of_loop)
  6954. );
  6955. # undef NOMMU_HACK_FMT
  6956. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6957. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6958. */
  6959. cnt += 6;
  6960. for (cur = G.top_var; cur; cur = cur->next) {
  6961. if (!cur->flg_export || cur->flg_read_only)
  6962. cnt += 2;
  6963. }
  6964. # if ENABLE_HUSH_FUNCTIONS
  6965. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6966. cnt += 3;
  6967. # endif
  6968. pp = g_argv;
  6969. while (*pp++)
  6970. cnt++;
  6971. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6972. *pp++ = (char *) G.argv0_for_re_execing;
  6973. *pp++ = param_buf;
  6974. for (cur = G.top_var; cur; cur = cur->next) {
  6975. if (strcmp(cur->varstr, hush_version_str) == 0)
  6976. continue;
  6977. if (cur->flg_read_only) {
  6978. *pp++ = (char *) "-R";
  6979. *pp++ = cur->varstr;
  6980. } else if (!cur->flg_export) {
  6981. *pp++ = (char *) "-V";
  6982. *pp++ = cur->varstr;
  6983. }
  6984. }
  6985. # if ENABLE_HUSH_FUNCTIONS
  6986. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6987. *pp++ = (char *) "-F";
  6988. *pp++ = funcp->name;
  6989. *pp++ = funcp->body_as_string;
  6990. }
  6991. # endif
  6992. /* We can pass activated traps here. Say, -Tnn:trap_string
  6993. *
  6994. * However, POSIX says that subshells reset signals with traps
  6995. * to SIG_DFL.
  6996. * I tested bash-3.2 and it not only does that with true subshells
  6997. * of the form ( list ), but with any forked children shells.
  6998. * I set trap "echo W" WINCH; and then tried:
  6999. *
  7000. * { echo 1; sleep 20; echo 2; } &
  7001. * while true; do echo 1; sleep 20; echo 2; break; done &
  7002. * true | { echo 1; sleep 20; echo 2; } | cat
  7003. *
  7004. * In all these cases sending SIGWINCH to the child shell
  7005. * did not run the trap. If I add trap "echo V" WINCH;
  7006. * _inside_ group (just before echo 1), it works.
  7007. *
  7008. * I conclude it means we don't need to pass active traps here.
  7009. */
  7010. *pp++ = (char *) "-c";
  7011. *pp++ = (char *) s;
  7012. if (builtin_argv) {
  7013. while (*++builtin_argv)
  7014. *pp++ = *builtin_argv;
  7015. *pp++ = (char *) "";
  7016. }
  7017. *pp++ = g_argv0;
  7018. while (*g_argv)
  7019. *pp++ = *g_argv++;
  7020. /* *pp = NULL; - is already there */
  7021. pp = environ;
  7022. do_exec:
  7023. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7024. /* Don't propagate SIG_IGN to the child */
  7025. if (SPECIAL_JOBSTOP_SIGS != 0)
  7026. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7027. execve(bb_busybox_exec_path, argv, pp);
  7028. /* Fallback. Useful for init=/bin/hush usage etc */
  7029. if (argv[0][0] == '/')
  7030. execve(argv[0], argv, pp);
  7031. xfunc_error_retval = 127;
  7032. bb_simple_error_msg_and_die("can't re-execute the shell");
  7033. }
  7034. #endif /* !BB_MMU */
  7035. static int run_and_free_list(struct pipe *pi);
  7036. /* Executing from string: eval, sh -c '...'
  7037. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7038. * end_trigger controls how often we stop parsing
  7039. * NUL: parse all, execute, return
  7040. * ';': parse till ';' or newline, execute, repeat till EOF
  7041. */
  7042. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7043. {
  7044. /* Why we need empty flag?
  7045. * An obscure corner case "false; ``; echo $?":
  7046. * empty command in `` should still set $? to 0.
  7047. * But we can't just set $? to 0 at the start,
  7048. * this breaks "false; echo `echo $?`" case.
  7049. */
  7050. bool empty = 1;
  7051. while (1) {
  7052. struct pipe *pipe_list;
  7053. #if ENABLE_HUSH_INTERACTIVE
  7054. if (end_trigger == ';') {
  7055. G.promptmode = 0; /* PS1 */
  7056. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7057. }
  7058. #endif
  7059. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7060. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7061. /* If we are in "big" script
  7062. * (not in `cmd` or something similar)...
  7063. */
  7064. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7065. /* Discard cached input (rest of line) */
  7066. int ch = inp->last_char;
  7067. while (ch != EOF && ch != '\n') {
  7068. //bb_error_msg("Discarded:'%c'", ch);
  7069. ch = i_getch(inp);
  7070. }
  7071. /* Force prompt */
  7072. inp->p = NULL;
  7073. /* This stream isn't empty */
  7074. empty = 0;
  7075. continue;
  7076. }
  7077. if (!pipe_list && empty)
  7078. G.last_exitcode = 0;
  7079. break;
  7080. }
  7081. debug_print_tree(pipe_list, 0);
  7082. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7083. run_and_free_list(pipe_list);
  7084. empty = 0;
  7085. if (G_flag_return_in_progress == 1)
  7086. break;
  7087. }
  7088. }
  7089. static void parse_and_run_string(const char *s)
  7090. {
  7091. struct in_str input;
  7092. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7093. setup_string_in_str(&input, s);
  7094. parse_and_run_stream(&input, '\0');
  7095. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7096. }
  7097. static void parse_and_run_file(HFILE *fp)
  7098. {
  7099. struct in_str input;
  7100. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7101. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7102. setup_file_in_str(&input, fp);
  7103. parse_and_run_stream(&input, ';');
  7104. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7105. }
  7106. #if ENABLE_HUSH_TICK
  7107. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7108. {
  7109. pid_t pid;
  7110. int channel[2];
  7111. # if !BB_MMU
  7112. char **to_free = NULL;
  7113. # endif
  7114. xpipe(channel);
  7115. pid = BB_MMU ? xfork() : xvfork();
  7116. if (pid == 0) { /* child */
  7117. disable_restore_tty_pgrp_on_exit();
  7118. /* Process substitution is not considered to be usual
  7119. * 'command execution'.
  7120. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7121. */
  7122. bb_signals(0
  7123. + (1 << SIGTSTP)
  7124. + (1 << SIGTTIN)
  7125. + (1 << SIGTTOU)
  7126. , SIG_IGN);
  7127. close(channel[0]); /* NB: close _first_, then move fd! */
  7128. xmove_fd(channel[1], 1);
  7129. # if ENABLE_HUSH_TRAP
  7130. /* Awful hack for `trap` or $(trap).
  7131. *
  7132. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7133. * contains an example where "trap" is executed in a subshell:
  7134. *
  7135. * save_traps=$(trap)
  7136. * ...
  7137. * eval "$save_traps"
  7138. *
  7139. * Standard does not say that "trap" in subshell shall print
  7140. * parent shell's traps. It only says that its output
  7141. * must have suitable form, but then, in the above example
  7142. * (which is not supposed to be normative), it implies that.
  7143. *
  7144. * bash (and probably other shell) does implement it
  7145. * (traps are reset to defaults, but "trap" still shows them),
  7146. * but as a result, "trap" logic is hopelessly messed up:
  7147. *
  7148. * # trap
  7149. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7150. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7151. * # true | trap <--- trap is in subshell - no output (ditto)
  7152. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7153. * trap -- 'echo Ho' SIGWINCH
  7154. * # echo `(trap)` <--- in subshell in subshell - output
  7155. * trap -- 'echo Ho' SIGWINCH
  7156. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7157. * trap -- 'echo Ho' SIGWINCH
  7158. *
  7159. * The rules when to forget and when to not forget traps
  7160. * get really complex and nonsensical.
  7161. *
  7162. * Our solution: ONLY bare $(trap) or `trap` is special.
  7163. */
  7164. s = skip_whitespace(s);
  7165. if (is_prefixed_with(s, "trap")
  7166. && skip_whitespace(s + 4)[0] == '\0'
  7167. ) {
  7168. static const char *const argv[] = { NULL, NULL };
  7169. builtin_trap((char**)argv);
  7170. fflush_all(); /* important */
  7171. _exit(0);
  7172. }
  7173. # endif
  7174. # if BB_MMU
  7175. /* Prevent it from trying to handle ctrl-z etc */
  7176. IF_HUSH_JOB(G.run_list_level = 1;)
  7177. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7178. reset_traps_to_defaults();
  7179. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7180. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7181. parse_and_run_string(s);
  7182. _exit(G.last_exitcode);
  7183. # else
  7184. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7185. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7186. * huge=`cat BIG` # was blocking here forever
  7187. * echo OK
  7188. */
  7189. re_execute_shell(&to_free,
  7190. s,
  7191. G.global_argv[0],
  7192. G.global_argv + 1,
  7193. NULL);
  7194. # endif
  7195. }
  7196. /* parent */
  7197. *pid_p = pid;
  7198. # if ENABLE_HUSH_FAST
  7199. G.count_SIGCHLD++;
  7200. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7201. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7202. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7203. # endif
  7204. enable_restore_tty_pgrp_on_exit();
  7205. # if !BB_MMU
  7206. free(to_free);
  7207. # endif
  7208. close(channel[1]);
  7209. return channel[0];
  7210. }
  7211. /* Return code is exit status of the process that is run. */
  7212. static int process_command_subs(o_string *dest, const char *s)
  7213. {
  7214. FILE *fp;
  7215. pid_t pid;
  7216. int status, ch, eol_cnt;
  7217. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7218. /* Now send results of command back into original context */
  7219. eol_cnt = 0;
  7220. while ((ch = getc(fp)) != EOF) {
  7221. if (ch == '\0')
  7222. continue;
  7223. if (ch == '\n') {
  7224. eol_cnt++;
  7225. continue;
  7226. }
  7227. while (eol_cnt) {
  7228. o_addchr(dest, '\n');
  7229. eol_cnt--;
  7230. }
  7231. o_addQchr(dest, ch);
  7232. }
  7233. debug_printf("done reading from `cmd` pipe, closing it\n");
  7234. fclose(fp);
  7235. /* We need to extract exitcode. Test case
  7236. * "true; echo `sleep 1; false` $?"
  7237. * should print 1 */
  7238. safe_waitpid(pid, &status, 0);
  7239. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7240. return WEXITSTATUS(status);
  7241. }
  7242. #endif /* ENABLE_HUSH_TICK */
  7243. static void setup_heredoc(struct redir_struct *redir)
  7244. {
  7245. struct fd_pair pair;
  7246. pid_t pid;
  7247. int len, written;
  7248. /* the _body_ of heredoc (misleading field name) */
  7249. const char *heredoc = redir->rd_filename;
  7250. char *expanded;
  7251. #if !BB_MMU
  7252. char **to_free;
  7253. #endif
  7254. expanded = NULL;
  7255. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7256. expanded = encode_then_expand_string(heredoc);
  7257. if (expanded)
  7258. heredoc = expanded;
  7259. }
  7260. len = strlen(heredoc);
  7261. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7262. xpiped_pair(pair);
  7263. xmove_fd(pair.rd, redir->rd_fd);
  7264. /* Try writing without forking. Newer kernels have
  7265. * dynamically growing pipes. Must use non-blocking write! */
  7266. ndelay_on(pair.wr);
  7267. while (1) {
  7268. written = write(pair.wr, heredoc, len);
  7269. if (written <= 0)
  7270. break;
  7271. len -= written;
  7272. if (len == 0) {
  7273. close(pair.wr);
  7274. free(expanded);
  7275. return;
  7276. }
  7277. heredoc += written;
  7278. }
  7279. ndelay_off(pair.wr);
  7280. /* Okay, pipe buffer was not big enough */
  7281. /* Note: we must not create a stray child (bastard? :)
  7282. * for the unsuspecting parent process. Child creates a grandchild
  7283. * and exits before parent execs the process which consumes heredoc
  7284. * (that exec happens after we return from this function) */
  7285. #if !BB_MMU
  7286. to_free = NULL;
  7287. #endif
  7288. pid = xvfork();
  7289. if (pid == 0) {
  7290. /* child */
  7291. disable_restore_tty_pgrp_on_exit();
  7292. pid = BB_MMU ? xfork() : xvfork();
  7293. if (pid != 0)
  7294. _exit(0);
  7295. /* grandchild */
  7296. close(redir->rd_fd); /* read side of the pipe */
  7297. #if BB_MMU
  7298. full_write(pair.wr, heredoc, len); /* may loop or block */
  7299. _exit(0);
  7300. #else
  7301. /* Delegate blocking writes to another process */
  7302. xmove_fd(pair.wr, STDOUT_FILENO);
  7303. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7304. #endif
  7305. }
  7306. /* parent */
  7307. #if ENABLE_HUSH_FAST
  7308. G.count_SIGCHLD++;
  7309. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7310. #endif
  7311. enable_restore_tty_pgrp_on_exit();
  7312. #if !BB_MMU
  7313. free(to_free);
  7314. #endif
  7315. close(pair.wr);
  7316. free(expanded);
  7317. wait(NULL); /* wait till child has died */
  7318. }
  7319. struct squirrel {
  7320. int orig_fd;
  7321. int moved_to;
  7322. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7323. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7324. };
  7325. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7326. {
  7327. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7328. sq[i].orig_fd = orig;
  7329. sq[i].moved_to = moved;
  7330. sq[i+1].orig_fd = -1; /* end marker */
  7331. return sq;
  7332. }
  7333. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7334. {
  7335. int moved_to;
  7336. int i;
  7337. i = 0;
  7338. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7339. /* If we collide with an already moved fd... */
  7340. if (fd == sq[i].moved_to) {
  7341. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7342. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7343. if (sq[i].moved_to < 0) /* what? */
  7344. xfunc_die();
  7345. return sq;
  7346. }
  7347. if (fd == sq[i].orig_fd) {
  7348. /* Example: echo Hello >/dev/null 1>&2 */
  7349. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7350. return sq;
  7351. }
  7352. }
  7353. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7354. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7355. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7356. if (moved_to < 0 && errno != EBADF)
  7357. xfunc_die();
  7358. return append_squirrel(sq, i, fd, moved_to);
  7359. }
  7360. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7361. {
  7362. int i;
  7363. i = 0;
  7364. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7365. /* If we collide with an already moved fd... */
  7366. if (fd == sq[i].orig_fd) {
  7367. /* Examples:
  7368. * "echo 3>FILE 3>&- 3>FILE"
  7369. * "echo 3>&- 3>FILE"
  7370. * No need for last redirect to insert
  7371. * another "need to close 3" indicator.
  7372. */
  7373. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7374. return sq;
  7375. }
  7376. }
  7377. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7378. return append_squirrel(sq, i, fd, -1);
  7379. }
  7380. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7381. * Move all conflicting internally used fds,
  7382. * and remember them so that we can restore them later.
  7383. */
  7384. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7385. {
  7386. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7387. avoid_fd = 9;
  7388. #if ENABLE_HUSH_INTERACTIVE
  7389. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7390. && fd == G_interactive_fd
  7391. ) {
  7392. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7393. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7394. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7395. return 1; /* "we closed fd" */
  7396. }
  7397. #endif
  7398. /* Are we called from setup_redirects(squirrel==NULL)
  7399. * in redirect in a [v]forked child?
  7400. */
  7401. if (sqp == NULL) {
  7402. /* No need to move script fds.
  7403. * For NOMMU case, it's actively wrong: we'd change ->fd
  7404. * fields in memory for the parent, but parent's fds
  7405. * aren't moved, it would use wrong fd!
  7406. * Reproducer: "cmd 3>FILE" in script.
  7407. * If we would call move_HFILEs_on_redirect(), child would:
  7408. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7409. * close(3) = 0
  7410. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7411. */
  7412. //bb_error_msg("sqp == NULL: [v]forked child");
  7413. return 0;
  7414. }
  7415. /* If this one of script's fds? */
  7416. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7417. return 1; /* yes. "we closed fd" (actually moved it) */
  7418. /* Are we called for "exec 3>FILE"? Came through
  7419. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7420. * This case used to fail for this script:
  7421. * exec 3>FILE
  7422. * echo Ok
  7423. * ...100000 more lines...
  7424. * echo Ok
  7425. * as follows:
  7426. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7427. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7428. * dup2(4, 3) = 3
  7429. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7430. * close(4) = 0
  7431. * write(1, "Ok\n", 3) = 3
  7432. * ... = 3
  7433. * write(1, "Ok\n", 3) = 3
  7434. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7435. * ^^^^^^^^ oops, wrong fd!!!
  7436. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7437. * it now works:
  7438. */
  7439. if (sqp == ERR_PTR) {
  7440. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7441. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7442. return 0;
  7443. }
  7444. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7445. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7446. return 0; /* "we did not close fd" */
  7447. }
  7448. static void restore_redirects(struct squirrel *sq)
  7449. {
  7450. if (sq) {
  7451. int i;
  7452. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7453. if (sq[i].moved_to >= 0) {
  7454. /* We simply die on error */
  7455. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7456. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7457. } else {
  7458. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7459. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7460. close(sq[i].orig_fd);
  7461. }
  7462. }
  7463. free(sq);
  7464. }
  7465. if (G.HFILE_stdin
  7466. && G.HFILE_stdin->fd > STDIN_FILENO
  7467. /* we compare > STDIN, not == STDIN, since hfgetc()
  7468. * closes fd and sets ->fd to -1 if EOF is reached.
  7469. * Testcase: echo 'pwd' | hush
  7470. */
  7471. ) {
  7472. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7473. * Redirect moves ->fd to e.g. 10,
  7474. * and it is not restored above (we do not restore script fds
  7475. * after redirects, we just use new, "moved" fds).
  7476. * However for stdin, get_user_input() -> read_line_input(),
  7477. * and read builtin, depend on fd == STDIN_FILENO.
  7478. */
  7479. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7480. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7481. G.HFILE_stdin->fd = STDIN_FILENO;
  7482. }
  7483. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7484. }
  7485. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7486. static void close_saved_fds_and_FILE_fds(void)
  7487. {
  7488. if (G_interactive_fd)
  7489. close(G_interactive_fd);
  7490. close_all_HFILE_list();
  7491. }
  7492. #endif
  7493. static int internally_opened_fd(int fd, struct squirrel *sq)
  7494. {
  7495. int i;
  7496. #if ENABLE_HUSH_INTERACTIVE
  7497. if (fd == G_interactive_fd)
  7498. return 1;
  7499. #endif
  7500. /* If this one of script's fds? */
  7501. if (fd_in_HFILEs(fd))
  7502. return 1;
  7503. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7504. if (fd == sq[i].moved_to)
  7505. return 1;
  7506. }
  7507. return 0;
  7508. }
  7509. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7510. * and stderr if they are redirected. */
  7511. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7512. {
  7513. struct redir_struct *redir;
  7514. for (redir = prog->redirects; redir; redir = redir->next) {
  7515. int newfd;
  7516. int closed;
  7517. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7518. /* "rd_fd<<HERE" case */
  7519. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7520. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7521. * of the heredoc */
  7522. debug_printf_redir("set heredoc '%s'\n",
  7523. redir->rd_filename);
  7524. setup_heredoc(redir);
  7525. continue;
  7526. }
  7527. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7528. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7529. char *p;
  7530. int mode;
  7531. if (redir->rd_filename == NULL) {
  7532. /* Examples:
  7533. * "cmd >" (no filename)
  7534. * "cmd > <file" (2nd redirect starts too early)
  7535. */
  7536. syntax_error("invalid redirect");
  7537. continue;
  7538. }
  7539. mode = redir_table[redir->rd_type].mode;
  7540. p = expand_string_to_string(redir->rd_filename,
  7541. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7542. newfd = open_or_warn(p, mode);
  7543. free(p);
  7544. if (newfd < 0) {
  7545. /* Error message from open_or_warn can be lost
  7546. * if stderr has been redirected, but bash
  7547. * and ash both lose it as well
  7548. * (though zsh doesn't!)
  7549. */
  7550. return 1;
  7551. }
  7552. if (newfd == redir->rd_fd && sqp) {
  7553. /* open() gave us precisely the fd we wanted.
  7554. * This means that this fd was not busy
  7555. * (not opened to anywhere).
  7556. * Remember to close it on restore:
  7557. */
  7558. *sqp = add_squirrel_closed(*sqp, newfd);
  7559. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7560. }
  7561. } else {
  7562. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7563. newfd = redir->rd_dup;
  7564. }
  7565. if (newfd == redir->rd_fd)
  7566. continue;
  7567. /* if "N>FILE": move newfd to redir->rd_fd */
  7568. /* if "N>&M": dup newfd to redir->rd_fd */
  7569. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7570. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7571. if (newfd == REDIRFD_CLOSE) {
  7572. /* "N>&-" means "close me" */
  7573. if (!closed) {
  7574. /* ^^^ optimization: saving may already
  7575. * have closed it. If not... */
  7576. close(redir->rd_fd);
  7577. }
  7578. /* Sometimes we do another close on restore, getting EBADF.
  7579. * Consider "echo 3>FILE 3>&-"
  7580. * first redirect remembers "need to close 3",
  7581. * and second redirect closes 3! Restore code then closes 3 again.
  7582. */
  7583. } else {
  7584. /* if newfd is a script fd or saved fd, simulate EBADF */
  7585. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7586. //errno = EBADF;
  7587. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7588. newfd = -1; /* same effect as code above */
  7589. }
  7590. xdup2(newfd, redir->rd_fd);
  7591. if (redir->rd_dup == REDIRFD_TO_FILE)
  7592. /* "rd_fd > FILE" */
  7593. close(newfd);
  7594. /* else: "rd_fd > rd_dup" */
  7595. }
  7596. }
  7597. return 0;
  7598. }
  7599. static char *find_in_path(const char *arg)
  7600. {
  7601. char *ret = NULL;
  7602. const char *PATH = get_local_var_value("PATH");
  7603. if (!PATH)
  7604. return NULL;
  7605. while (1) {
  7606. const char *end = strchrnul(PATH, ':');
  7607. int sz = end - PATH; /* must be int! */
  7608. free(ret);
  7609. if (sz != 0) {
  7610. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7611. } else {
  7612. /* We have xxx::yyyy in $PATH,
  7613. * it means "use current dir" */
  7614. ret = xstrdup(arg);
  7615. }
  7616. if (access(ret, F_OK) == 0)
  7617. break;
  7618. if (*end == '\0') {
  7619. free(ret);
  7620. return NULL;
  7621. }
  7622. PATH = end + 1;
  7623. }
  7624. return ret;
  7625. }
  7626. static const struct built_in_command *find_builtin_helper(const char *name,
  7627. const struct built_in_command *x,
  7628. const struct built_in_command *end)
  7629. {
  7630. while (x != end) {
  7631. if (strcmp(name, x->b_cmd) != 0) {
  7632. x++;
  7633. continue;
  7634. }
  7635. debug_printf_exec("found builtin '%s'\n", name);
  7636. return x;
  7637. }
  7638. return NULL;
  7639. }
  7640. static const struct built_in_command *find_builtin1(const char *name)
  7641. {
  7642. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7643. }
  7644. static const struct built_in_command *find_builtin(const char *name)
  7645. {
  7646. const struct built_in_command *x = find_builtin1(name);
  7647. if (x)
  7648. return x;
  7649. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7650. }
  7651. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7652. static const char * FAST_FUNC get_builtin_name(int i)
  7653. {
  7654. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7655. return bltins1[i].b_cmd;
  7656. }
  7657. i -= ARRAY_SIZE(bltins1);
  7658. if (i < ARRAY_SIZE(bltins2)) {
  7659. return bltins2[i].b_cmd;
  7660. }
  7661. return NULL;
  7662. }
  7663. #endif
  7664. static void remove_nested_vars(void)
  7665. {
  7666. struct variable *cur;
  7667. struct variable **cur_pp;
  7668. cur_pp = &G.top_var;
  7669. while ((cur = *cur_pp) != NULL) {
  7670. if (cur->var_nest_level <= G.var_nest_level) {
  7671. cur_pp = &cur->next;
  7672. continue;
  7673. }
  7674. /* Unexport */
  7675. if (cur->flg_export) {
  7676. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7677. bb_unsetenv(cur->varstr);
  7678. }
  7679. /* Remove from global list */
  7680. *cur_pp = cur->next;
  7681. /* Free */
  7682. if (!cur->max_len) {
  7683. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7684. free(cur->varstr);
  7685. }
  7686. free(cur);
  7687. }
  7688. }
  7689. static void enter_var_nest_level(void)
  7690. {
  7691. G.var_nest_level++;
  7692. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7693. /* Try: f() { echo -n .; f; }; f
  7694. * struct variable::var_nest_level is uint16_t,
  7695. * thus limiting recursion to < 2^16.
  7696. * In any case, with 8 Mbyte stack SEGV happens
  7697. * not too long after 2^16 recursions anyway.
  7698. */
  7699. if (G.var_nest_level > 0xff00)
  7700. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7701. }
  7702. static void leave_var_nest_level(void)
  7703. {
  7704. G.var_nest_level--;
  7705. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7706. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7707. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7708. remove_nested_vars();
  7709. }
  7710. #if ENABLE_HUSH_FUNCTIONS
  7711. static struct function **find_function_slot(const char *name)
  7712. {
  7713. struct function *funcp;
  7714. struct function **funcpp = &G.top_func;
  7715. while ((funcp = *funcpp) != NULL) {
  7716. if (strcmp(name, funcp->name) == 0) {
  7717. debug_printf_exec("found function '%s'\n", name);
  7718. break;
  7719. }
  7720. funcpp = &funcp->next;
  7721. }
  7722. return funcpp;
  7723. }
  7724. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7725. {
  7726. const struct function *funcp = *find_function_slot(name);
  7727. return funcp;
  7728. }
  7729. /* Note: takes ownership on name ptr */
  7730. static struct function *new_function(char *name)
  7731. {
  7732. struct function **funcpp = find_function_slot(name);
  7733. struct function *funcp = *funcpp;
  7734. if (funcp != NULL) {
  7735. struct command *cmd = funcp->parent_cmd;
  7736. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7737. if (!cmd) {
  7738. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7739. free(funcp->name);
  7740. /* Note: if !funcp->body, do not free body_as_string!
  7741. * This is a special case of "-F name body" function:
  7742. * body_as_string was not malloced! */
  7743. if (funcp->body) {
  7744. free_pipe_list(funcp->body);
  7745. # if !BB_MMU
  7746. free(funcp->body_as_string);
  7747. # endif
  7748. }
  7749. } else {
  7750. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7751. cmd->argv[0] = funcp->name;
  7752. cmd->group = funcp->body;
  7753. # if !BB_MMU
  7754. cmd->group_as_string = funcp->body_as_string;
  7755. # endif
  7756. }
  7757. } else {
  7758. debug_printf_exec("remembering new function '%s'\n", name);
  7759. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7760. /*funcp->next = NULL;*/
  7761. }
  7762. funcp->name = name;
  7763. return funcp;
  7764. }
  7765. # if ENABLE_HUSH_UNSET
  7766. static void unset_func(const char *name)
  7767. {
  7768. struct function **funcpp = find_function_slot(name);
  7769. struct function *funcp = *funcpp;
  7770. if (funcp != NULL) {
  7771. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7772. *funcpp = funcp->next;
  7773. /* funcp is unlinked now, deleting it.
  7774. * Note: if !funcp->body, the function was created by
  7775. * "-F name body", do not free ->body_as_string
  7776. * and ->name as they were not malloced. */
  7777. if (funcp->body) {
  7778. free_pipe_list(funcp->body);
  7779. free(funcp->name);
  7780. # if !BB_MMU
  7781. free(funcp->body_as_string);
  7782. # endif
  7783. }
  7784. free(funcp);
  7785. }
  7786. }
  7787. # endif
  7788. # if BB_MMU
  7789. #define exec_function(to_free, funcp, argv) \
  7790. exec_function(funcp, argv)
  7791. # endif
  7792. static void exec_function(char ***to_free,
  7793. const struct function *funcp,
  7794. char **argv) NORETURN;
  7795. static void exec_function(char ***to_free,
  7796. const struct function *funcp,
  7797. char **argv)
  7798. {
  7799. # if BB_MMU
  7800. int n;
  7801. argv[0] = G.global_argv[0];
  7802. G.global_argv = argv;
  7803. G.global_argc = n = 1 + string_array_len(argv + 1);
  7804. // Example when we are here: "cmd | func"
  7805. // func will run with saved-redirect fds open.
  7806. // $ f() { echo /proc/self/fd/*; }
  7807. // $ true | f
  7808. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7809. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7810. // Same in script:
  7811. // $ . ./SCRIPT
  7812. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7813. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7814. // They are CLOEXEC so external programs won't see them, but
  7815. // for "more correctness" we might want to close those extra fds here:
  7816. //? close_saved_fds_and_FILE_fds();
  7817. /* "we are in a function, ok to use return" */
  7818. G_flag_return_in_progress = -1;
  7819. enter_var_nest_level();
  7820. IF_HUSH_LOCAL(G.func_nest_level++;)
  7821. /* On MMU, funcp->body is always non-NULL */
  7822. n = run_list(funcp->body);
  7823. _exit(n);
  7824. # else
  7825. //? close_saved_fds_and_FILE_fds();
  7826. //TODO: check whether "true | func_with_return" works
  7827. re_execute_shell(to_free,
  7828. funcp->body_as_string,
  7829. G.global_argv[0],
  7830. argv + 1,
  7831. NULL);
  7832. # endif
  7833. }
  7834. static int run_function(const struct function *funcp, char **argv)
  7835. {
  7836. int rc;
  7837. save_arg_t sv;
  7838. smallint sv_flg;
  7839. save_and_replace_G_args(&sv, argv);
  7840. /* "We are in function, ok to use return" */
  7841. sv_flg = G_flag_return_in_progress;
  7842. G_flag_return_in_progress = -1;
  7843. /* Make "local" variables properly shadow previous ones */
  7844. IF_HUSH_LOCAL(enter_var_nest_level();)
  7845. IF_HUSH_LOCAL(G.func_nest_level++;)
  7846. /* On MMU, funcp->body is always non-NULL */
  7847. # if !BB_MMU
  7848. if (!funcp->body) {
  7849. /* Function defined by -F */
  7850. parse_and_run_string(funcp->body_as_string);
  7851. rc = G.last_exitcode;
  7852. } else
  7853. # endif
  7854. {
  7855. rc = run_list(funcp->body);
  7856. }
  7857. IF_HUSH_LOCAL(G.func_nest_level--;)
  7858. IF_HUSH_LOCAL(leave_var_nest_level();)
  7859. G_flag_return_in_progress = sv_flg;
  7860. # if ENABLE_HUSH_TRAP
  7861. debug_printf_exec("G.return_exitcode=-1\n");
  7862. G.return_exitcode = -1; /* invalidate stashed return value */
  7863. # endif
  7864. restore_G_args(&sv, argv);
  7865. return rc;
  7866. }
  7867. #endif /* ENABLE_HUSH_FUNCTIONS */
  7868. #if BB_MMU
  7869. #define exec_builtin(to_free, x, argv) \
  7870. exec_builtin(x, argv)
  7871. #else
  7872. #define exec_builtin(to_free, x, argv) \
  7873. exec_builtin(to_free, argv)
  7874. #endif
  7875. static void exec_builtin(char ***to_free,
  7876. const struct built_in_command *x,
  7877. char **argv) NORETURN;
  7878. static void exec_builtin(char ***to_free,
  7879. const struct built_in_command *x,
  7880. char **argv)
  7881. {
  7882. #if BB_MMU
  7883. int rcode;
  7884. //? close_saved_fds_and_FILE_fds();
  7885. rcode = x->b_function(argv);
  7886. fflush_all();
  7887. _exit(rcode);
  7888. #else
  7889. fflush_all();
  7890. /* On NOMMU, we must never block!
  7891. * Example: { sleep 99 | read line; } & echo Ok
  7892. */
  7893. re_execute_shell(to_free,
  7894. argv[0],
  7895. G.global_argv[0],
  7896. G.global_argv + 1,
  7897. argv);
  7898. #endif
  7899. }
  7900. static void execvp_or_die(char **argv) NORETURN;
  7901. static void execvp_or_die(char **argv)
  7902. {
  7903. int e;
  7904. debug_printf_exec("execing '%s'\n", argv[0]);
  7905. /* Don't propagate SIG_IGN to the child */
  7906. if (SPECIAL_JOBSTOP_SIGS != 0)
  7907. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7908. execvp(argv[0], argv);
  7909. e = 2;
  7910. if (errno == EACCES) e = 126;
  7911. if (errno == ENOENT) e = 127;
  7912. bb_perror_msg("can't execute '%s'", argv[0]);
  7913. _exit(e);
  7914. }
  7915. #if ENABLE_HUSH_MODE_X
  7916. static void x_mode_print_optionally_squoted(const char *str)
  7917. {
  7918. unsigned len;
  7919. const char *cp;
  7920. cp = str;
  7921. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7922. /* test a char with: bash -c 'set -x; echo "CH"' */
  7923. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7924. " " "\001\002\003\004\005\006\007"
  7925. "\010\011\012\013\014\015\016\017"
  7926. "\020\021\022\023\024\025\026\027"
  7927. "\030\031\032\033\034\035\036\037"
  7928. )
  7929. ] == '\0'
  7930. ) {
  7931. /* string has no special chars */
  7932. x_mode_addstr(str);
  7933. return;
  7934. }
  7935. cp = str;
  7936. for (;;) {
  7937. /* print '....' up to EOL or first squote */
  7938. len = (int)(strchrnul(cp, '\'') - cp);
  7939. if (len != 0) {
  7940. x_mode_addchr('\'');
  7941. x_mode_addblock(cp, len);
  7942. x_mode_addchr('\'');
  7943. cp += len;
  7944. }
  7945. if (*cp == '\0')
  7946. break;
  7947. /* string contains squote(s), print them as \' */
  7948. x_mode_addchr('\\');
  7949. x_mode_addchr('\'');
  7950. cp++;
  7951. }
  7952. }
  7953. static void dump_cmd_in_x_mode(char **argv)
  7954. {
  7955. if (G_x_mode && argv) {
  7956. unsigned n;
  7957. /* "+[+++...][ cmd...]\n\0" */
  7958. x_mode_prefix();
  7959. n = 0;
  7960. while (argv[n]) {
  7961. x_mode_addchr(' ');
  7962. if (argv[n][0] == '\0') {
  7963. x_mode_addchr('\'');
  7964. x_mode_addchr('\'');
  7965. } else {
  7966. x_mode_print_optionally_squoted(argv[n]);
  7967. }
  7968. n++;
  7969. }
  7970. x_mode_flush();
  7971. }
  7972. }
  7973. #else
  7974. # define dump_cmd_in_x_mode(argv) ((void)0)
  7975. #endif
  7976. #if ENABLE_HUSH_COMMAND
  7977. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7978. {
  7979. char *to_free;
  7980. if (!opt_vV)
  7981. return;
  7982. to_free = NULL;
  7983. if (!explanation) {
  7984. char *path = getenv("PATH");
  7985. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7986. if (!explanation)
  7987. _exit(1); /* PROG was not found */
  7988. if (opt_vV != 'V')
  7989. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7990. }
  7991. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7992. free(to_free);
  7993. fflush_all();
  7994. _exit(0);
  7995. }
  7996. #else
  7997. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7998. #endif
  7999. #if BB_MMU
  8000. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  8001. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  8002. #define pseudo_exec(nommu_save, command, argv_expanded) \
  8003. pseudo_exec(command, argv_expanded)
  8004. #endif
  8005. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  8006. * Never returns.
  8007. * Don't exit() here. If you don't exec, use _exit instead.
  8008. * The at_exit handlers apparently confuse the calling process,
  8009. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  8010. */
  8011. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8012. char **argv, int assignment_cnt,
  8013. char **argv_expanded) NORETURN;
  8014. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8015. char **argv, int assignment_cnt,
  8016. char **argv_expanded)
  8017. {
  8018. const struct built_in_command *x;
  8019. struct variable **sv_shadowed;
  8020. char **new_env;
  8021. IF_HUSH_COMMAND(char opt_vV = 0;)
  8022. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8023. new_env = expand_assignments(argv, assignment_cnt);
  8024. dump_cmd_in_x_mode(new_env);
  8025. if (!argv[assignment_cnt]) {
  8026. /* Case when we are here: ... | var=val | ...
  8027. * (note that we do not exit early, i.e., do not optimize out
  8028. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8029. */
  8030. free_strings(new_env);
  8031. _exit(EXIT_SUCCESS);
  8032. }
  8033. sv_shadowed = G.shadowed_vars_pp;
  8034. #if BB_MMU
  8035. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8036. #else
  8037. G.shadowed_vars_pp = &nommu_save->old_vars;
  8038. G.var_nest_level++;
  8039. #endif
  8040. set_vars_and_save_old(new_env);
  8041. G.shadowed_vars_pp = sv_shadowed;
  8042. if (argv_expanded) {
  8043. argv = argv_expanded;
  8044. } else {
  8045. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8046. #if !BB_MMU
  8047. nommu_save->argv = argv;
  8048. #endif
  8049. }
  8050. dump_cmd_in_x_mode(argv);
  8051. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8052. if (strchr(argv[0], '/') != NULL)
  8053. goto skip;
  8054. #endif
  8055. #if ENABLE_HUSH_FUNCTIONS
  8056. /* Check if the command matches any functions (this goes before bltins) */
  8057. funcp = find_function(argv[0]);
  8058. if (funcp)
  8059. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8060. #endif
  8061. #if ENABLE_HUSH_COMMAND
  8062. /* "command BAR": run BAR without looking it up among functions
  8063. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8064. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8065. */
  8066. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8067. char *p;
  8068. argv++;
  8069. p = *argv;
  8070. if (p[0] != '-' || !p[1])
  8071. continue; /* bash allows "command command command [-OPT] BAR" */
  8072. for (;;) {
  8073. p++;
  8074. switch (*p) {
  8075. case '\0':
  8076. argv++;
  8077. p = *argv;
  8078. if (p[0] != '-' || !p[1])
  8079. goto after_opts;
  8080. continue; /* next arg is also -opts, process it too */
  8081. case 'v':
  8082. case 'V':
  8083. opt_vV = *p;
  8084. continue;
  8085. default:
  8086. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8087. }
  8088. }
  8089. }
  8090. after_opts:
  8091. # if ENABLE_HUSH_FUNCTIONS
  8092. if (opt_vV && find_function(argv[0]))
  8093. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8094. # endif
  8095. #endif
  8096. /* Check if the command matches any of the builtins.
  8097. * Depending on context, this might be redundant. But it's
  8098. * easier to waste a few CPU cycles than it is to figure out
  8099. * if this is one of those cases.
  8100. */
  8101. /* Why "BB_MMU ? :" difference in logic? -
  8102. * On NOMMU, it is more expensive to re-execute shell
  8103. * just in order to run echo or test builtin.
  8104. * It's better to skip it here and run corresponding
  8105. * non-builtin later. */
  8106. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8107. if (x) {
  8108. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8109. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8110. }
  8111. #if ENABLE_FEATURE_SH_STANDALONE
  8112. /* Check if the command matches any busybox applets */
  8113. {
  8114. int a = find_applet_by_name(argv[0]);
  8115. if (a >= 0) {
  8116. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8117. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8118. if (APPLET_IS_NOEXEC(a)) {
  8119. /* Do not leak open fds from opened script files etc.
  8120. * Testcase: interactive "ls -l /proc/self/fd"
  8121. * should not show tty fd open.
  8122. */
  8123. close_saved_fds_and_FILE_fds();
  8124. //FIXME: should also close saved redir fds
  8125. //This casuses test failures in
  8126. //redir_children_should_not_see_saved_fd_2.tests
  8127. //redir_children_should_not_see_saved_fd_3.tests
  8128. //if you replace "busybox find" with just "find" in them
  8129. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8130. switch_off_special_sigs(G.special_sig_mask);
  8131. debug_printf_exec("running applet '%s'\n", argv[0]);
  8132. run_noexec_applet_and_exit(a, argv[0], argv);
  8133. }
  8134. # endif
  8135. /* Re-exec ourselves */
  8136. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8137. /* Don't propagate SIG_IGN to the child */
  8138. if (SPECIAL_JOBSTOP_SIGS != 0)
  8139. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8140. execv(bb_busybox_exec_path, argv);
  8141. /* If they called chroot or otherwise made the binary no longer
  8142. * executable, fall through */
  8143. }
  8144. }
  8145. #endif
  8146. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8147. skip:
  8148. #endif
  8149. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8150. execvp_or_die(argv);
  8151. }
  8152. /* Called after [v]fork() in run_pipe
  8153. */
  8154. static void pseudo_exec(nommu_save_t *nommu_save,
  8155. struct command *command,
  8156. char **argv_expanded) NORETURN;
  8157. static void pseudo_exec(nommu_save_t *nommu_save,
  8158. struct command *command,
  8159. char **argv_expanded)
  8160. {
  8161. #if ENABLE_HUSH_FUNCTIONS
  8162. if (command->cmd_type == CMD_FUNCDEF) {
  8163. /* Ignore funcdefs in pipes:
  8164. * true | f() { cmd }
  8165. */
  8166. _exit(0);
  8167. }
  8168. #endif
  8169. if (command->argv) {
  8170. pseudo_exec_argv(nommu_save, command->argv,
  8171. command->assignment_cnt, argv_expanded);
  8172. }
  8173. if (command->group) {
  8174. /* Cases when we are here:
  8175. * ( list )
  8176. * { list } &
  8177. * ... | ( list ) | ...
  8178. * ... | { list } | ...
  8179. */
  8180. #if BB_MMU
  8181. int rcode;
  8182. debug_printf_exec("pseudo_exec: run_list\n");
  8183. reset_traps_to_defaults();
  8184. rcode = run_list(command->group);
  8185. /* OK to leak memory by not calling free_pipe_list,
  8186. * since this process is about to exit */
  8187. _exit(rcode);
  8188. #else
  8189. re_execute_shell(&nommu_save->argv_from_re_execing,
  8190. command->group_as_string,
  8191. G.global_argv[0],
  8192. G.global_argv + 1,
  8193. NULL);
  8194. #endif
  8195. }
  8196. /* Case when we are here: ... | >file */
  8197. debug_printf_exec("pseudo_exec'ed null command\n");
  8198. _exit(EXIT_SUCCESS);
  8199. }
  8200. #if ENABLE_HUSH_JOB
  8201. static const char *get_cmdtext(struct pipe *pi)
  8202. {
  8203. char **argv;
  8204. char *p;
  8205. int len;
  8206. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8207. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8208. * On subsequent bg argv is trashed, but we won't use it */
  8209. if (pi->cmdtext)
  8210. return pi->cmdtext;
  8211. argv = pi->cmds[0].argv;
  8212. if (!argv) {
  8213. pi->cmdtext = xzalloc(1);
  8214. return pi->cmdtext;
  8215. }
  8216. len = 0;
  8217. do {
  8218. len += strlen(*argv) + 1;
  8219. } while (*++argv);
  8220. p = xmalloc(len);
  8221. pi->cmdtext = p;
  8222. argv = pi->cmds[0].argv;
  8223. do {
  8224. p = stpcpy(p, *argv);
  8225. *p++ = ' ';
  8226. } while (*++argv);
  8227. p[-1] = '\0';
  8228. return pi->cmdtext;
  8229. }
  8230. static void remove_job_from_table(struct pipe *pi)
  8231. {
  8232. struct pipe *prev_pipe;
  8233. if (pi == G.job_list) {
  8234. G.job_list = pi->next;
  8235. } else {
  8236. prev_pipe = G.job_list;
  8237. while (prev_pipe->next != pi)
  8238. prev_pipe = prev_pipe->next;
  8239. prev_pipe->next = pi->next;
  8240. }
  8241. G.last_jobid = 0;
  8242. if (G.job_list)
  8243. G.last_jobid = G.job_list->jobid;
  8244. }
  8245. static void delete_finished_job(struct pipe *pi)
  8246. {
  8247. remove_job_from_table(pi);
  8248. free_pipe(pi);
  8249. }
  8250. static void clean_up_last_dead_job(void)
  8251. {
  8252. if (G.job_list && !G.job_list->alive_cmds)
  8253. delete_finished_job(G.job_list);
  8254. }
  8255. static void insert_job_into_table(struct pipe *pi)
  8256. {
  8257. struct pipe *job, **jobp;
  8258. int i;
  8259. clean_up_last_dead_job();
  8260. /* Find the end of the list, and find next job ID to use */
  8261. i = 0;
  8262. jobp = &G.job_list;
  8263. while ((job = *jobp) != NULL) {
  8264. if (job->jobid > i)
  8265. i = job->jobid;
  8266. jobp = &job->next;
  8267. }
  8268. pi->jobid = i + 1;
  8269. /* Create a new job struct at the end */
  8270. job = *jobp = xmemdup(pi, sizeof(*pi));
  8271. job->next = NULL;
  8272. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8273. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8274. for (i = 0; i < pi->num_cmds; i++) {
  8275. job->cmds[i].pid = pi->cmds[i].pid;
  8276. /* all other fields are not used and stay zero */
  8277. }
  8278. job->cmdtext = xstrdup(get_cmdtext(pi));
  8279. if (G_interactive_fd)
  8280. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8281. G.last_jobid = job->jobid;
  8282. }
  8283. #endif /* JOB */
  8284. static int job_exited_or_stopped(struct pipe *pi)
  8285. {
  8286. int rcode, i;
  8287. if (pi->alive_cmds != pi->stopped_cmds)
  8288. return -1;
  8289. /* All processes in fg pipe have exited or stopped */
  8290. rcode = 0;
  8291. i = pi->num_cmds;
  8292. while (--i >= 0) {
  8293. rcode = pi->cmds[i].cmd_exitcode;
  8294. /* usually last process gives overall exitstatus,
  8295. * but with "set -o pipefail", last *failed* process does */
  8296. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8297. break;
  8298. }
  8299. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8300. return rcode;
  8301. }
  8302. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8303. {
  8304. #if ENABLE_HUSH_JOB
  8305. struct pipe *pi;
  8306. #endif
  8307. int i, dead;
  8308. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8309. #if DEBUG_JOBS
  8310. if (WIFSTOPPED(status))
  8311. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8312. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8313. if (WIFSIGNALED(status))
  8314. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8315. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8316. if (WIFEXITED(status))
  8317. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8318. childpid, WEXITSTATUS(status));
  8319. #endif
  8320. /* Were we asked to wait for a fg pipe? */
  8321. if (fg_pipe) {
  8322. i = fg_pipe->num_cmds;
  8323. while (--i >= 0) {
  8324. int rcode;
  8325. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8326. if (fg_pipe->cmds[i].pid != childpid)
  8327. continue;
  8328. if (dead) {
  8329. int ex;
  8330. fg_pipe->cmds[i].pid = 0;
  8331. fg_pipe->alive_cmds--;
  8332. ex = WEXITSTATUS(status);
  8333. /* bash prints killer signal's name for *last*
  8334. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8335. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8336. */
  8337. if (WIFSIGNALED(status)) {
  8338. int sig = WTERMSIG(status);
  8339. #if ENABLE_HUSH_JOB
  8340. if (G.run_list_level == 1
  8341. /* ^^^^^ Do not print in nested contexts, example:
  8342. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8343. */
  8344. && i == fg_pipe->num_cmds-1
  8345. ) {
  8346. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8347. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8348. }
  8349. #endif
  8350. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8351. /* MIPS has 128 sigs (1..128), if sig==128,
  8352. * 128 + sig would result in exitcode 256 -> 0!
  8353. */
  8354. ex = 128 | sig;
  8355. }
  8356. fg_pipe->cmds[i].cmd_exitcode = ex;
  8357. } else {
  8358. fg_pipe->stopped_cmds++;
  8359. }
  8360. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8361. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8362. rcode = job_exited_or_stopped(fg_pipe);
  8363. if (rcode >= 0) {
  8364. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8365. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8366. * and "killall -STOP cat" */
  8367. if (G_interactive_fd) {
  8368. #if ENABLE_HUSH_JOB
  8369. if (fg_pipe->alive_cmds != 0)
  8370. insert_job_into_table(fg_pipe);
  8371. #endif
  8372. return rcode;
  8373. }
  8374. if (fg_pipe->alive_cmds == 0)
  8375. return rcode;
  8376. }
  8377. /* There are still running processes in the fg_pipe */
  8378. return -1;
  8379. }
  8380. /* It wasn't in fg_pipe, look for process in bg pipes */
  8381. }
  8382. #if ENABLE_HUSH_JOB
  8383. /* We were asked to wait for bg or orphaned children */
  8384. /* No need to remember exitcode in this case */
  8385. for (pi = G.job_list; pi; pi = pi->next) {
  8386. for (i = 0; i < pi->num_cmds; i++) {
  8387. if (pi->cmds[i].pid == childpid)
  8388. goto found_pi_and_prognum;
  8389. }
  8390. }
  8391. /* Happens when shell is used as init process (init=/bin/sh) */
  8392. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8393. return -1; /* this wasn't a process from fg_pipe */
  8394. found_pi_and_prognum:
  8395. if (dead) {
  8396. /* child exited */
  8397. int rcode = WEXITSTATUS(status);
  8398. if (WIFSIGNALED(status))
  8399. /* NB: not 128 + sig, MIPS has sig 128 */
  8400. rcode = 128 | WTERMSIG(status);
  8401. pi->cmds[i].cmd_exitcode = rcode;
  8402. if (G.last_bg_pid == pi->cmds[i].pid)
  8403. G.last_bg_pid_exitcode = rcode;
  8404. pi->cmds[i].pid = 0;
  8405. pi->alive_cmds--;
  8406. if (!pi->alive_cmds) {
  8407. # if ENABLE_HUSH_BASH_COMPAT
  8408. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8409. # endif
  8410. if (G_interactive_fd) {
  8411. printf(JOB_STATUS_FORMAT, pi->jobid,
  8412. "Done", pi->cmdtext);
  8413. delete_finished_job(pi);
  8414. } else {
  8415. /*
  8416. * bash deletes finished jobs from job table only in interactive mode,
  8417. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8418. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8419. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8420. * We only retain one "dead" job, if it's the single job on the list.
  8421. * This covers most of real-world scenarios where this is useful.
  8422. */
  8423. if (pi != G.job_list)
  8424. delete_finished_job(pi);
  8425. }
  8426. }
  8427. } else {
  8428. /* child stopped */
  8429. pi->stopped_cmds++;
  8430. }
  8431. #endif
  8432. return -1; /* this wasn't a process from fg_pipe */
  8433. }
  8434. /* Check to see if any processes have exited -- if they have,
  8435. * figure out why and see if a job has completed.
  8436. *
  8437. * If non-NULL fg_pipe: wait for its completion or stop.
  8438. * Return its exitcode or zero if stopped.
  8439. *
  8440. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8441. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8442. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8443. * or 0 if no children changed status.
  8444. *
  8445. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8446. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8447. * or 0 if no children changed status.
  8448. */
  8449. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8450. {
  8451. int attributes;
  8452. int status;
  8453. int rcode = 0;
  8454. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8455. attributes = WUNTRACED;
  8456. if (fg_pipe == NULL)
  8457. attributes |= WNOHANG;
  8458. errno = 0;
  8459. #if ENABLE_HUSH_FAST
  8460. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8461. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8462. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8463. /* There was neither fork nor SIGCHLD since last waitpid */
  8464. /* Avoid doing waitpid syscall if possible */
  8465. if (!G.we_have_children) {
  8466. errno = ECHILD;
  8467. return -1;
  8468. }
  8469. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8470. /* We have children, but they did not exit
  8471. * or stop yet (we saw no SIGCHLD) */
  8472. return 0;
  8473. }
  8474. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8475. }
  8476. #endif
  8477. /* Do we do this right?
  8478. * bash-3.00# sleep 20 | false
  8479. * <ctrl-Z pressed>
  8480. * [3]+ Stopped sleep 20 | false
  8481. * bash-3.00# echo $?
  8482. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8483. * [hush 1.14.0: yes we do it right]
  8484. */
  8485. while (1) {
  8486. pid_t childpid;
  8487. #if ENABLE_HUSH_FAST
  8488. int i;
  8489. i = G.count_SIGCHLD;
  8490. #endif
  8491. childpid = waitpid(-1, &status, attributes);
  8492. if (childpid <= 0) {
  8493. if (childpid && errno != ECHILD)
  8494. bb_simple_perror_msg("waitpid");
  8495. #if ENABLE_HUSH_FAST
  8496. else { /* Until next SIGCHLD, waitpid's are useless */
  8497. G.we_have_children = (childpid == 0);
  8498. G.handled_SIGCHLD = i;
  8499. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8500. }
  8501. #endif
  8502. /* ECHILD (no children), or 0 (no change in children status) */
  8503. rcode = childpid;
  8504. break;
  8505. }
  8506. rcode = process_wait_result(fg_pipe, childpid, status);
  8507. if (rcode >= 0) {
  8508. /* fg_pipe exited or stopped */
  8509. break;
  8510. }
  8511. if (childpid == waitfor_pid) { /* "wait PID" */
  8512. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8513. rcode = WEXITSTATUS(status);
  8514. if (WIFSIGNALED(status))
  8515. rcode = 128 | WTERMSIG(status);
  8516. if (WIFSTOPPED(status))
  8517. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8518. rcode = 128 | WSTOPSIG(status);
  8519. rcode++;
  8520. break; /* "wait PID" called us, give it exitcode+1 */
  8521. }
  8522. #if ENABLE_HUSH_BASH_COMPAT
  8523. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8524. && G.dead_job_exitcode >= 0 /* some job did finish */
  8525. ) {
  8526. debug_printf_exec("waitfor_pid:-1\n");
  8527. rcode = G.dead_job_exitcode + 1;
  8528. break;
  8529. }
  8530. #endif
  8531. /* This wasn't one of our processes, or */
  8532. /* fg_pipe still has running processes, do waitpid again */
  8533. } /* while (waitpid succeeds)... */
  8534. return rcode;
  8535. }
  8536. #if ENABLE_HUSH_JOB
  8537. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8538. {
  8539. pid_t p;
  8540. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8541. if (G_saved_tty_pgrp) {
  8542. /* Job finished, move the shell to the foreground */
  8543. p = getpgrp(); /* our process group id */
  8544. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8545. tcsetpgrp(G_interactive_fd, p);
  8546. }
  8547. return rcode;
  8548. }
  8549. #endif
  8550. /* Start all the jobs, but don't wait for anything to finish.
  8551. * See checkjobs().
  8552. *
  8553. * Return code is normally -1, when the caller has to wait for children
  8554. * to finish to determine the exit status of the pipe. If the pipe
  8555. * is a simple builtin command, however, the action is done by the
  8556. * time run_pipe returns, and the exit code is provided as the
  8557. * return value.
  8558. *
  8559. * Returns -1 only if started some children. IOW: we have to
  8560. * mask out retvals of builtins etc with 0xff!
  8561. *
  8562. * The only case when we do not need to [v]fork is when the pipe
  8563. * is single, non-backgrounded, non-subshell command. Examples:
  8564. * cmd ; ... { list } ; ...
  8565. * cmd && ... { list } && ...
  8566. * cmd || ... { list } || ...
  8567. * If it is, then we can run cmd as a builtin, NOFORK,
  8568. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8569. * with run_list. If it isn't one of these, we fork and exec cmd.
  8570. *
  8571. * Cases when we must fork:
  8572. * non-single: cmd | cmd
  8573. * backgrounded: cmd & { list } &
  8574. * subshell: ( list ) [&]
  8575. */
  8576. #if !ENABLE_HUSH_MODE_X
  8577. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8578. redirect_and_varexp_helper(command, sqp)
  8579. #endif
  8580. static int redirect_and_varexp_helper(
  8581. struct command *command,
  8582. struct squirrel **sqp,
  8583. char **argv_expanded)
  8584. {
  8585. /* Assignments occur before redirects. Try:
  8586. * a=`sleep 1` sleep 2 3>/qwe/rty
  8587. */
  8588. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8589. dump_cmd_in_x_mode(new_env);
  8590. dump_cmd_in_x_mode(argv_expanded);
  8591. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8592. set_vars_and_save_old(new_env);
  8593. return setup_redirects(command, sqp);
  8594. }
  8595. static NOINLINE int run_pipe(struct pipe *pi)
  8596. {
  8597. static const char *const null_ptr = NULL;
  8598. int cmd_no;
  8599. int next_infd;
  8600. struct command *command;
  8601. char **argv_expanded;
  8602. char **argv;
  8603. struct squirrel *squirrel = NULL;
  8604. int rcode;
  8605. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8606. debug_enter();
  8607. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8608. * Result should be 3 lines: q w e, qwe, q w e
  8609. */
  8610. if (G.ifs_whitespace != G.ifs)
  8611. free(G.ifs_whitespace);
  8612. G.ifs = get_local_var_value("IFS");
  8613. if (G.ifs) {
  8614. char *p;
  8615. G.ifs_whitespace = (char*)G.ifs;
  8616. p = skip_whitespace(G.ifs);
  8617. if (*p) {
  8618. /* Not all $IFS is whitespace */
  8619. char *d;
  8620. int len = p - G.ifs;
  8621. p = skip_non_whitespace(p);
  8622. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8623. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8624. while (*p) {
  8625. if (isspace(*p))
  8626. *d++ = *p;
  8627. p++;
  8628. }
  8629. *d = '\0';
  8630. }
  8631. } else {
  8632. G.ifs = defifs;
  8633. G.ifs_whitespace = (char*)G.ifs;
  8634. }
  8635. IF_HUSH_JOB(pi->pgrp = -1;)
  8636. pi->stopped_cmds = 0;
  8637. command = &pi->cmds[0];
  8638. argv_expanded = NULL;
  8639. if (pi->num_cmds != 1
  8640. || pi->followup == PIPE_BG
  8641. || command->cmd_type == CMD_SUBSHELL
  8642. ) {
  8643. goto must_fork;
  8644. }
  8645. pi->alive_cmds = 1;
  8646. debug_printf_exec(": group:%p argv:'%s'\n",
  8647. command->group, command->argv ? command->argv[0] : "NONE");
  8648. if (command->group) {
  8649. #if ENABLE_HUSH_FUNCTIONS
  8650. if (command->cmd_type == CMD_FUNCDEF) {
  8651. /* "executing" func () { list } */
  8652. struct function *funcp;
  8653. funcp = new_function(command->argv[0]);
  8654. /* funcp->name is already set to argv[0] */
  8655. funcp->body = command->group;
  8656. # if !BB_MMU
  8657. funcp->body_as_string = command->group_as_string;
  8658. command->group_as_string = NULL;
  8659. # endif
  8660. command->group = NULL;
  8661. command->argv[0] = NULL;
  8662. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8663. funcp->parent_cmd = command;
  8664. command->child_func = funcp;
  8665. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8666. debug_leave();
  8667. return EXIT_SUCCESS;
  8668. }
  8669. #endif
  8670. /* { list } */
  8671. debug_printf_exec("non-subshell group\n");
  8672. rcode = 1; /* exitcode if redir failed */
  8673. if (setup_redirects(command, &squirrel) == 0) {
  8674. debug_printf_exec(": run_list\n");
  8675. //FIXME: we need to pass squirrel down into run_list()
  8676. //for SH_STANDALONE case, or else this construct:
  8677. // { find /proc/self/fd; true; } >FILE; cmd2
  8678. //has no way of closing saved fd#1 for "find",
  8679. //and in SH_STANDALONE mode, "find" is not execed,
  8680. //therefore CLOEXEC on saved fd does not help.
  8681. rcode = run_list(command->group) & 0xff;
  8682. }
  8683. restore_redirects(squirrel);
  8684. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8685. debug_leave();
  8686. debug_printf_exec("run_pipe: return %d\n", rcode);
  8687. return rcode;
  8688. }
  8689. argv = command->argv ? command->argv : (char **) &null_ptr;
  8690. {
  8691. const struct built_in_command *x;
  8692. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8693. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8694. struct variable **sv_shadowed;
  8695. struct variable *old_vars;
  8696. #if ENABLE_HUSH_LINENO_VAR
  8697. G.execute_lineno = command->lineno;
  8698. #endif
  8699. if (argv[command->assignment_cnt] == NULL) {
  8700. /* Assignments, but no command.
  8701. * Ensure redirects take effect (that is, create files).
  8702. * Try "a=t >file"
  8703. */
  8704. unsigned i;
  8705. G.expand_exitcode = 0;
  8706. only_assignments:
  8707. rcode = setup_redirects(command, &squirrel);
  8708. restore_redirects(squirrel);
  8709. /* Set shell variables */
  8710. i = 0;
  8711. while (i < command->assignment_cnt) {
  8712. char *p = expand_string_to_string(argv[i],
  8713. EXP_FLAG_ESC_GLOB_CHARS,
  8714. /*unbackslash:*/ 1
  8715. );
  8716. #if ENABLE_HUSH_MODE_X
  8717. if (G_x_mode) {
  8718. char *eq;
  8719. if (i == 0)
  8720. x_mode_prefix();
  8721. x_mode_addchr(' ');
  8722. eq = strchrnul(p, '=');
  8723. if (*eq) eq++;
  8724. x_mode_addblock(p, (eq - p));
  8725. x_mode_print_optionally_squoted(eq);
  8726. x_mode_flush();
  8727. }
  8728. #endif
  8729. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8730. if (set_local_var(p, /*flag:*/ 0)) {
  8731. /* assignment to readonly var / putenv error? */
  8732. rcode = 1;
  8733. }
  8734. i++;
  8735. }
  8736. /* Redirect error sets $? to 1. Otherwise,
  8737. * if evaluating assignment value set $?, retain it.
  8738. * Else, clear $?:
  8739. * false; q=`exit 2`; echo $? - should print 2
  8740. * false; x=1; echo $? - should print 0
  8741. * Because of the 2nd case, we can't just use G.last_exitcode.
  8742. */
  8743. if (rcode == 0)
  8744. rcode = G.expand_exitcode;
  8745. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8746. debug_leave();
  8747. debug_printf_exec("run_pipe: return %d\n", rcode);
  8748. return rcode;
  8749. }
  8750. /* Expand the rest into (possibly) many strings each */
  8751. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8752. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8753. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8754. else
  8755. #endif
  8756. #if defined(CMD_SINGLEWORD_NOGLOB)
  8757. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8758. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8759. else
  8760. #endif
  8761. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8762. /* If someone gives us an empty string: `cmd with empty output` */
  8763. if (!argv_expanded[0]) {
  8764. free(argv_expanded);
  8765. /* `false` still has to set exitcode 1 */
  8766. G.expand_exitcode = G.last_exitcode;
  8767. goto only_assignments;
  8768. }
  8769. old_vars = NULL;
  8770. sv_shadowed = G.shadowed_vars_pp;
  8771. /* Check if argv[0] matches any functions (this goes before bltins) */
  8772. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8773. IF_HUSH_FUNCTIONS(x = NULL;)
  8774. IF_HUSH_FUNCTIONS(if (!funcp))
  8775. x = find_builtin(argv_expanded[0]);
  8776. if (x || funcp) {
  8777. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8778. debug_printf("exec with redirects only\n");
  8779. /*
  8780. * Variable assignments are executed, but then "forgotten":
  8781. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8782. * sleeps, but prints nothing.
  8783. */
  8784. enter_var_nest_level();
  8785. G.shadowed_vars_pp = &old_vars;
  8786. rcode = redirect_and_varexp_helper(command,
  8787. /*squirrel:*/ ERR_PTR,
  8788. argv_expanded
  8789. );
  8790. G.shadowed_vars_pp = sv_shadowed;
  8791. /* rcode=1 can be if redir file can't be opened */
  8792. goto clean_up_and_ret1;
  8793. }
  8794. /* Bump var nesting, or this will leak exported $a:
  8795. * a=b true; env | grep ^a=
  8796. */
  8797. enter_var_nest_level();
  8798. /* Collect all variables "shadowed" by helper
  8799. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8800. * into old_vars list:
  8801. */
  8802. G.shadowed_vars_pp = &old_vars;
  8803. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8804. if (rcode == 0) {
  8805. if (!funcp) {
  8806. /* Do not collect *to old_vars list* vars shadowed
  8807. * by e.g. "local VAR" builtin (collect them
  8808. * in the previously nested list instead):
  8809. * don't want them to be restored immediately
  8810. * after "local" completes.
  8811. */
  8812. G.shadowed_vars_pp = sv_shadowed;
  8813. debug_printf_exec(": builtin '%s' '%s'...\n",
  8814. x->b_cmd, argv_expanded[1]);
  8815. fflush_all();
  8816. rcode = x->b_function(argv_expanded) & 0xff;
  8817. fflush_all();
  8818. }
  8819. #if ENABLE_HUSH_FUNCTIONS
  8820. else {
  8821. debug_printf_exec(": function '%s' '%s'...\n",
  8822. funcp->name, argv_expanded[1]);
  8823. rcode = run_function(funcp, argv_expanded) & 0xff;
  8824. /*
  8825. * But do collect *to old_vars list* vars shadowed
  8826. * within function execution. To that end, restore
  8827. * this pointer _after_ function run:
  8828. */
  8829. G.shadowed_vars_pp = sv_shadowed;
  8830. }
  8831. #endif
  8832. }
  8833. } else
  8834. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8835. int n = find_applet_by_name(argv_expanded[0]);
  8836. if (n < 0 || !APPLET_IS_NOFORK(n))
  8837. goto must_fork;
  8838. enter_var_nest_level();
  8839. /* Collect all variables "shadowed" by helper into old_vars list */
  8840. G.shadowed_vars_pp = &old_vars;
  8841. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8842. G.shadowed_vars_pp = sv_shadowed;
  8843. if (rcode == 0) {
  8844. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8845. argv_expanded[0], argv_expanded[1]);
  8846. /*
  8847. * Note: signals (^C) can't interrupt here.
  8848. * We remember them and they will be acted upon
  8849. * after applet returns.
  8850. * This makes applets which can run for a long time
  8851. * and/or wait for user input ineligible for NOFORK:
  8852. * for example, "yes" or "rm" (rm -i waits for input).
  8853. */
  8854. rcode = run_nofork_applet(n, argv_expanded);
  8855. }
  8856. } else
  8857. goto must_fork;
  8858. restore_redirects(squirrel);
  8859. clean_up_and_ret1:
  8860. leave_var_nest_level();
  8861. add_vars(old_vars);
  8862. /*
  8863. * Try "usleep 99999999" + ^C + "echo $?"
  8864. * with FEATURE_SH_NOFORK=y.
  8865. */
  8866. if (!funcp) {
  8867. /* It was builtin or nofork.
  8868. * if this would be a real fork/execed program,
  8869. * it should have died if a fatal sig was received.
  8870. * But OTOH, there was no separate process,
  8871. * the sig was sent to _shell_, not to non-existing
  8872. * child.
  8873. * Let's just handle ^C only, this one is obvious:
  8874. * we aren't ok with exitcode 0 when ^C was pressed
  8875. * during builtin/nofork.
  8876. */
  8877. if (sigismember(&G.pending_set, SIGINT))
  8878. rcode = 128 | SIGINT;
  8879. }
  8880. free(argv_expanded);
  8881. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8882. debug_leave();
  8883. debug_printf_exec("run_pipe return %d\n", rcode);
  8884. return rcode;
  8885. }
  8886. must_fork:
  8887. /* NB: argv_expanded may already be created, and that
  8888. * might include `cmd` runs! Do not rerun it! We *must*
  8889. * use argv_expanded if it's non-NULL */
  8890. /* Going to fork a child per each pipe member */
  8891. pi->alive_cmds = 0;
  8892. next_infd = 0;
  8893. cmd_no = 0;
  8894. while (cmd_no < pi->num_cmds) {
  8895. struct fd_pair pipefds;
  8896. #if !BB_MMU
  8897. int sv_var_nest_level = G.var_nest_level;
  8898. volatile nommu_save_t nommu_save;
  8899. nommu_save.old_vars = NULL;
  8900. nommu_save.argv = NULL;
  8901. nommu_save.argv_from_re_execing = NULL;
  8902. #endif
  8903. command = &pi->cmds[cmd_no];
  8904. cmd_no++;
  8905. if (command->argv) {
  8906. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8907. command->argv[0], command->argv[1]);
  8908. } else {
  8909. debug_printf_exec(": pipe member with no argv\n");
  8910. }
  8911. /* pipes are inserted between pairs of commands */
  8912. pipefds.rd = 0;
  8913. pipefds.wr = 1;
  8914. if (cmd_no < pi->num_cmds)
  8915. xpiped_pair(pipefds);
  8916. #if ENABLE_HUSH_LINENO_VAR
  8917. G.execute_lineno = command->lineno;
  8918. #endif
  8919. command->pid = BB_MMU ? fork() : vfork();
  8920. if (!command->pid) { /* child */
  8921. #if ENABLE_HUSH_JOB
  8922. disable_restore_tty_pgrp_on_exit();
  8923. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8924. /* Every child adds itself to new process group
  8925. * with pgid == pid_of_first_child_in_pipe */
  8926. if (G.run_list_level == 1 && G_interactive_fd) {
  8927. pid_t pgrp;
  8928. pgrp = pi->pgrp;
  8929. if (pgrp < 0) /* true for 1st process only */
  8930. pgrp = getpid();
  8931. if (setpgid(0, pgrp) == 0
  8932. && pi->followup != PIPE_BG
  8933. && G_saved_tty_pgrp /* we have ctty */
  8934. ) {
  8935. /* We do it in *every* child, not just first,
  8936. * to avoid races */
  8937. tcsetpgrp(G_interactive_fd, pgrp);
  8938. }
  8939. }
  8940. #endif
  8941. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8942. /* 1st cmd in backgrounded pipe
  8943. * should have its stdin /dev/null'ed */
  8944. close(0);
  8945. if (open(bb_dev_null, O_RDONLY))
  8946. xopen("/", O_RDONLY);
  8947. } else {
  8948. xmove_fd(next_infd, 0);
  8949. }
  8950. xmove_fd(pipefds.wr, 1);
  8951. if (pipefds.rd > 1)
  8952. close(pipefds.rd);
  8953. /* Like bash, explicit redirects override pipes,
  8954. * and the pipe fd (fd#1) is available for dup'ing:
  8955. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8956. * of cmd1 goes into pipe.
  8957. */
  8958. if (setup_redirects(command, NULL)) {
  8959. /* Happens when redir file can't be opened:
  8960. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8961. * FOO
  8962. * hush: can't open '/qwe/rty': No such file or directory
  8963. * BAZ
  8964. * (echo BAR is not executed, it hits _exit(1) below)
  8965. */
  8966. _exit(1);
  8967. }
  8968. /* Stores to nommu_save list of env vars putenv'ed
  8969. * (NOMMU, on MMU we don't need that) */
  8970. /* cast away volatility... */
  8971. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8972. /* pseudo_exec() does not return */
  8973. }
  8974. /* parent or error */
  8975. #if ENABLE_HUSH_FAST
  8976. G.count_SIGCHLD++;
  8977. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8978. #endif
  8979. enable_restore_tty_pgrp_on_exit();
  8980. #if !BB_MMU
  8981. /* Clean up after vforked child */
  8982. free(nommu_save.argv);
  8983. free(nommu_save.argv_from_re_execing);
  8984. G.var_nest_level = sv_var_nest_level;
  8985. remove_nested_vars();
  8986. add_vars(nommu_save.old_vars);
  8987. #endif
  8988. free(argv_expanded);
  8989. argv_expanded = NULL;
  8990. if (command->pid < 0) { /* [v]fork failed */
  8991. /* Clearly indicate, was it fork or vfork */
  8992. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8993. } else {
  8994. pi->alive_cmds++;
  8995. #if ENABLE_HUSH_JOB
  8996. /* Second and next children need to know pid of first one */
  8997. if (pi->pgrp < 0)
  8998. pi->pgrp = command->pid;
  8999. #endif
  9000. }
  9001. if (cmd_no > 1)
  9002. close(next_infd);
  9003. if (cmd_no < pi->num_cmds)
  9004. close(pipefds.wr);
  9005. /* Pass read (output) pipe end to next iteration */
  9006. next_infd = pipefds.rd;
  9007. }
  9008. if (!pi->alive_cmds) {
  9009. debug_leave();
  9010. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9011. return 1;
  9012. }
  9013. debug_leave();
  9014. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9015. return -1;
  9016. }
  9017. /* NB: called by pseudo_exec, and therefore must not modify any
  9018. * global data until exec/_exit (we can be a child after vfork!) */
  9019. static int run_list(struct pipe *pi)
  9020. {
  9021. #if ENABLE_HUSH_CASE
  9022. char *case_word = NULL;
  9023. #endif
  9024. #if ENABLE_HUSH_LOOPS
  9025. struct pipe *loop_top = NULL;
  9026. char **for_lcur = NULL;
  9027. char **for_list = NULL;
  9028. #endif
  9029. smallint last_followup;
  9030. smalluint rcode;
  9031. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9032. smalluint cond_code = 0;
  9033. #else
  9034. enum { cond_code = 0 };
  9035. #endif
  9036. #if HAS_KEYWORDS
  9037. smallint rword; /* RES_foo */
  9038. smallint last_rword; /* ditto */
  9039. #endif
  9040. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  9041. debug_enter();
  9042. #if ENABLE_HUSH_LOOPS
  9043. /* Check syntax for "for" */
  9044. {
  9045. struct pipe *cpipe;
  9046. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9047. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9048. continue;
  9049. /* current word is FOR or IN (BOLD in comments below) */
  9050. if (cpipe->next == NULL) {
  9051. syntax_error("malformed for");
  9052. debug_leave();
  9053. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9054. return 1;
  9055. }
  9056. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9057. if (cpipe->next->res_word == RES_DO)
  9058. continue;
  9059. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9060. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9061. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9062. ) {
  9063. syntax_error("malformed for");
  9064. debug_leave();
  9065. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9066. return 1;
  9067. }
  9068. }
  9069. }
  9070. #endif
  9071. /* Past this point, all code paths should jump to ret: label
  9072. * in order to return, no direct "return" statements please.
  9073. * This helps to ensure that no memory is leaked. */
  9074. #if ENABLE_HUSH_JOB
  9075. G.run_list_level++;
  9076. #endif
  9077. #if HAS_KEYWORDS
  9078. rword = RES_NONE;
  9079. last_rword = RES_XXXX;
  9080. #endif
  9081. last_followup = PIPE_SEQ;
  9082. rcode = G.last_exitcode;
  9083. /* Go through list of pipes, (maybe) executing them. */
  9084. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9085. int r;
  9086. int sv_errexit_depth;
  9087. if (G.flag_SIGINT)
  9088. break;
  9089. if (G_flag_return_in_progress == 1)
  9090. break;
  9091. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9092. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  9093. rword, cond_code, last_rword);
  9094. sv_errexit_depth = G.errexit_depth;
  9095. if (
  9096. #if ENABLE_HUSH_IF
  9097. rword == RES_IF || rword == RES_ELIF ||
  9098. #endif
  9099. pi->followup != PIPE_SEQ
  9100. ) {
  9101. G.errexit_depth++;
  9102. }
  9103. #if ENABLE_HUSH_LOOPS
  9104. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9105. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9106. ) {
  9107. /* start of a loop: remember where loop starts */
  9108. loop_top = pi;
  9109. G.depth_of_loop++;
  9110. }
  9111. #endif
  9112. /* Still in the same "if...", "then..." or "do..." branch? */
  9113. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9114. if ((rcode == 0 && last_followup == PIPE_OR)
  9115. || (rcode != 0 && last_followup == PIPE_AND)
  9116. ) {
  9117. /* It is "<true> || CMD" or "<false> && CMD"
  9118. * and we should not execute CMD */
  9119. debug_printf_exec("skipped cmd because of || or &&\n");
  9120. last_followup = pi->followup;
  9121. goto dont_check_jobs_but_continue;
  9122. }
  9123. }
  9124. last_followup = pi->followup;
  9125. IF_HAS_KEYWORDS(last_rword = rword;)
  9126. #if ENABLE_HUSH_IF
  9127. if (cond_code) {
  9128. if (rword == RES_THEN) {
  9129. /* if false; then ... fi has exitcode 0! */
  9130. G.last_exitcode = rcode = EXIT_SUCCESS;
  9131. /* "if <false> THEN cmd": skip cmd */
  9132. continue;
  9133. }
  9134. } else {
  9135. if (rword == RES_ELSE || rword == RES_ELIF) {
  9136. /* "if <true> then ... ELSE/ELIF cmd":
  9137. * skip cmd and all following ones */
  9138. break;
  9139. }
  9140. }
  9141. #endif
  9142. #if ENABLE_HUSH_LOOPS
  9143. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9144. if (!for_lcur) {
  9145. /* first loop through for */
  9146. static const char encoded_dollar_at[] ALIGN1 = {
  9147. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9148. }; /* encoded representation of "$@" */
  9149. static const char *const encoded_dollar_at_argv[] = {
  9150. encoded_dollar_at, NULL
  9151. }; /* argv list with one element: "$@" */
  9152. char **vals;
  9153. G.last_exitcode = rcode = EXIT_SUCCESS;
  9154. vals = (char**)encoded_dollar_at_argv;
  9155. if (pi->next->res_word == RES_IN) {
  9156. /* if no variable values after "in" we skip "for" */
  9157. if (!pi->next->cmds[0].argv) {
  9158. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9159. break;
  9160. }
  9161. vals = pi->next->cmds[0].argv;
  9162. } /* else: "for var; do..." -> assume "$@" list */
  9163. /* create list of variable values */
  9164. debug_print_strings("for_list made from", vals);
  9165. for_list = expand_strvec_to_strvec(vals);
  9166. for_lcur = for_list;
  9167. debug_print_strings("for_list", for_list);
  9168. }
  9169. if (!*for_lcur) {
  9170. /* "for" loop is over, clean up */
  9171. free(for_list);
  9172. for_list = NULL;
  9173. for_lcur = NULL;
  9174. break;
  9175. }
  9176. /* Insert next value from for_lcur */
  9177. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9178. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  9179. continue;
  9180. }
  9181. if (rword == RES_IN) {
  9182. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9183. }
  9184. if (rword == RES_DONE) {
  9185. continue; /* "done" has no cmds too */
  9186. }
  9187. #endif
  9188. #if ENABLE_HUSH_CASE
  9189. if (rword == RES_CASE) {
  9190. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9191. case_word = expand_string_to_string(pi->cmds->argv[0],
  9192. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9193. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9194. //unbackslash(case_word);
  9195. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9196. continue;
  9197. }
  9198. if (rword == RES_MATCH) {
  9199. char **argv;
  9200. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9201. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9202. break;
  9203. /* all prev words didn't match, does this one match? */
  9204. argv = pi->cmds->argv;
  9205. while (*argv) {
  9206. char *pattern;
  9207. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9208. pattern = expand_string_to_string(*argv,
  9209. EXP_FLAG_ESC_GLOB_CHARS,
  9210. /*unbackslash:*/ 0
  9211. );
  9212. /* TODO: which FNM_xxx flags to use? */
  9213. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9214. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9215. pattern, case_word, cond_code);
  9216. free(pattern);
  9217. if (cond_code == 0) {
  9218. /* match! we will execute this branch */
  9219. free(case_word);
  9220. case_word = NULL; /* make future "word)" stop */
  9221. break;
  9222. }
  9223. argv++;
  9224. }
  9225. continue;
  9226. }
  9227. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9228. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9229. if (cond_code != 0)
  9230. continue; /* not matched yet, skip this pipe */
  9231. }
  9232. if (rword == RES_ESAC) {
  9233. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9234. if (case_word) {
  9235. /* "case" did not match anything: still set $? (to 0) */
  9236. G.last_exitcode = rcode = EXIT_SUCCESS;
  9237. }
  9238. }
  9239. #endif
  9240. /* Just pressing <enter> in shell should check for jobs.
  9241. * OTOH, in non-interactive shell this is useless
  9242. * and only leads to extra job checks */
  9243. if (pi->num_cmds == 0) {
  9244. if (G_interactive_fd)
  9245. goto check_jobs_and_continue;
  9246. continue;
  9247. }
  9248. /* After analyzing all keywords and conditions, we decided
  9249. * to execute this pipe. NB: have to do checkjobs(NULL)
  9250. * after run_pipe to collect any background children,
  9251. * even if list execution is to be stopped. */
  9252. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9253. #if ENABLE_HUSH_LOOPS
  9254. G.flag_break_continue = 0;
  9255. #endif
  9256. rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
  9257. /* NB: rcode is a smalluint, r is int */
  9258. if (r != -1) {
  9259. /* We ran a builtin, function, or group.
  9260. * rcode is already known
  9261. * and we don't need to wait for anything. */
  9262. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9263. G.last_exitcode = rcode;
  9264. check_and_run_traps();
  9265. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9266. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9267. #endif
  9268. #if ENABLE_HUSH_LOOPS
  9269. /* Was it "break" or "continue"? */
  9270. if (G.flag_break_continue) {
  9271. smallint fbc = G.flag_break_continue;
  9272. /* We might fall into outer *loop*,
  9273. * don't want to break it too */
  9274. if (loop_top) {
  9275. G.depth_break_continue--;
  9276. if (G.depth_break_continue == 0)
  9277. G.flag_break_continue = 0;
  9278. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9279. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9280. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9281. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9282. break;
  9283. }
  9284. /* "continue": simulate end of loop */
  9285. rword = RES_DONE;
  9286. continue;
  9287. }
  9288. #endif
  9289. if (G_flag_return_in_progress == 1) {
  9290. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9291. break;
  9292. }
  9293. } else if (pi->followup == PIPE_BG) {
  9294. /* What does bash do with attempts to background builtins? */
  9295. /* even bash 3.2 doesn't do that well with nested bg:
  9296. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9297. * I'm NOT treating inner &'s as jobs */
  9298. #if ENABLE_HUSH_JOB
  9299. if (G.run_list_level == 1)
  9300. insert_job_into_table(pi);
  9301. #endif
  9302. /* Last command's pid goes to $! */
  9303. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9304. G.last_bg_pid_exitcode = 0;
  9305. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9306. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9307. rcode = EXIT_SUCCESS;
  9308. goto check_traps;
  9309. } else {
  9310. #if ENABLE_HUSH_JOB
  9311. if (G.run_list_level == 1 && G_interactive_fd) {
  9312. /* Waits for completion, then fg's main shell */
  9313. rcode = checkjobs_and_fg_shell(pi);
  9314. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9315. goto check_traps;
  9316. }
  9317. #endif
  9318. /* This one just waits for completion */
  9319. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9320. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9321. check_traps:
  9322. G.last_exitcode = rcode;
  9323. check_and_run_traps();
  9324. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9325. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9326. #endif
  9327. }
  9328. /* Handle "set -e" */
  9329. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9330. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9331. if (G.errexit_depth == 0)
  9332. hush_exit(rcode);
  9333. }
  9334. G.errexit_depth = sv_errexit_depth;
  9335. /* Analyze how result affects subsequent commands */
  9336. #if ENABLE_HUSH_IF
  9337. if (rword == RES_IF || rword == RES_ELIF)
  9338. cond_code = rcode;
  9339. #endif
  9340. check_jobs_and_continue:
  9341. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9342. dont_check_jobs_but_continue: ;
  9343. #if ENABLE_HUSH_LOOPS
  9344. /* Beware of "while false; true; do ..."! */
  9345. if (pi->next
  9346. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9347. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9348. ) {
  9349. if (rword == RES_WHILE) {
  9350. if (rcode) {
  9351. /* "while false; do...done" - exitcode 0 */
  9352. G.last_exitcode = rcode = EXIT_SUCCESS;
  9353. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9354. break;
  9355. }
  9356. }
  9357. if (rword == RES_UNTIL) {
  9358. if (!rcode) {
  9359. debug_printf_exec(": until expr is true: breaking\n");
  9360. break;
  9361. }
  9362. }
  9363. }
  9364. #endif
  9365. } /* for (pi) */
  9366. #if ENABLE_HUSH_JOB
  9367. G.run_list_level--;
  9368. #endif
  9369. #if ENABLE_HUSH_LOOPS
  9370. if (loop_top)
  9371. G.depth_of_loop--;
  9372. free(for_list);
  9373. #endif
  9374. #if ENABLE_HUSH_CASE
  9375. free(case_word);
  9376. #endif
  9377. debug_leave();
  9378. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9379. return rcode;
  9380. }
  9381. /* Select which version we will use */
  9382. static int run_and_free_list(struct pipe *pi)
  9383. {
  9384. int rcode = 0;
  9385. debug_printf_exec("run_and_free_list entered\n");
  9386. if (!G.o_opt[OPT_O_NOEXEC]) {
  9387. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9388. rcode = run_list(pi);
  9389. }
  9390. /* free_pipe_list has the side effect of clearing memory.
  9391. * In the long run that function can be merged with run_list,
  9392. * but doing that now would hobble the debugging effort. */
  9393. free_pipe_list(pi);
  9394. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9395. return rcode;
  9396. }
  9397. static void install_sighandlers(unsigned mask)
  9398. {
  9399. sighandler_t old_handler;
  9400. unsigned sig = 0;
  9401. while ((mask >>= 1) != 0) {
  9402. sig++;
  9403. if (!(mask & 1))
  9404. continue;
  9405. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9406. /* POSIX allows shell to re-enable SIGCHLD
  9407. * even if it was SIG_IGN on entry.
  9408. * Therefore we skip IGN check for it:
  9409. */
  9410. if (sig == SIGCHLD)
  9411. continue;
  9412. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9413. * Try:
  9414. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9415. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9416. */
  9417. if (sig == SIGHUP && G_interactive_fd)
  9418. continue;
  9419. /* Unless one of the above signals, is it SIG_IGN? */
  9420. if (old_handler == SIG_IGN) {
  9421. /* oops... restore back to IGN, and record this fact */
  9422. install_sighandler(sig, old_handler);
  9423. #if ENABLE_HUSH_TRAP
  9424. if (!G_traps)
  9425. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9426. free(G_traps[sig]);
  9427. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9428. #endif
  9429. }
  9430. }
  9431. }
  9432. /* Called a few times only (or even once if "sh -c") */
  9433. static void install_special_sighandlers(void)
  9434. {
  9435. unsigned mask;
  9436. /* Which signals are shell-special? */
  9437. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9438. if (G_interactive_fd) {
  9439. mask |= SPECIAL_INTERACTIVE_SIGS;
  9440. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9441. mask |= SPECIAL_JOBSTOP_SIGS;
  9442. }
  9443. /* Careful, do not re-install handlers we already installed */
  9444. if (G.special_sig_mask != mask) {
  9445. unsigned diff = mask & ~G.special_sig_mask;
  9446. G.special_sig_mask = mask;
  9447. install_sighandlers(diff);
  9448. }
  9449. }
  9450. #if ENABLE_HUSH_JOB
  9451. /* helper */
  9452. /* Set handlers to restore tty pgrp and exit */
  9453. static void install_fatal_sighandlers(void)
  9454. {
  9455. unsigned mask;
  9456. /* We will restore tty pgrp on these signals */
  9457. mask = 0
  9458. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9459. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9460. + (1 << SIGBUS ) * HUSH_DEBUG
  9461. + (1 << SIGSEGV) * HUSH_DEBUG
  9462. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9463. + (1 << SIGABRT)
  9464. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9465. + (1 << SIGPIPE)
  9466. + (1 << SIGALRM)
  9467. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9468. * if we aren't interactive... but in this case
  9469. * we never want to restore pgrp on exit, and this fn is not called
  9470. */
  9471. /*+ (1 << SIGHUP )*/
  9472. /*+ (1 << SIGTERM)*/
  9473. /*+ (1 << SIGINT )*/
  9474. ;
  9475. G_fatal_sig_mask = mask;
  9476. install_sighandlers(mask);
  9477. }
  9478. #endif
  9479. static int set_mode(int state, char mode, const char *o_opt)
  9480. {
  9481. int idx;
  9482. switch (mode) {
  9483. case 'n':
  9484. /* set -n has no effect in interactive shell */
  9485. /* Try: while set -n; do echo $-; done */
  9486. if (!G_interactive_fd)
  9487. G.o_opt[OPT_O_NOEXEC] = state;
  9488. break;
  9489. case 'x':
  9490. IF_HUSH_MODE_X(G_x_mode = state;)
  9491. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9492. break;
  9493. case 'e':
  9494. G.o_opt[OPT_O_ERREXIT] = state;
  9495. break;
  9496. case 'o':
  9497. if (!o_opt) {
  9498. /* "set -o" or "set +o" without parameter.
  9499. * in bash, set -o produces this output:
  9500. * pipefail off
  9501. * and set +o:
  9502. * set +o pipefail
  9503. * We always use the second form.
  9504. */
  9505. const char *p = o_opt_strings;
  9506. idx = 0;
  9507. while (*p) {
  9508. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9509. idx++;
  9510. p += strlen(p) + 1;
  9511. }
  9512. break;
  9513. }
  9514. idx = index_in_strings(o_opt_strings, o_opt);
  9515. if (idx >= 0) {
  9516. G.o_opt[idx] = state;
  9517. break;
  9518. }
  9519. /* fall through to error */
  9520. default:
  9521. return EXIT_FAILURE;
  9522. }
  9523. return EXIT_SUCCESS;
  9524. }
  9525. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9526. int hush_main(int argc, char **argv)
  9527. {
  9528. pid_t cached_getpid;
  9529. enum {
  9530. OPT_login = (1 << 0),
  9531. };
  9532. unsigned flags;
  9533. #if !BB_MMU
  9534. unsigned builtin_argc = 0;
  9535. #endif
  9536. char **e;
  9537. struct variable *cur_var;
  9538. struct variable *shell_ver;
  9539. INIT_G();
  9540. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9541. G.last_exitcode = EXIT_SUCCESS;
  9542. #if ENABLE_HUSH_TRAP
  9543. # if ENABLE_HUSH_FUNCTIONS
  9544. G.return_exitcode = -1;
  9545. # endif
  9546. G.pre_trap_exitcode = -1;
  9547. #endif
  9548. #if ENABLE_HUSH_FAST
  9549. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9550. #endif
  9551. #if !BB_MMU
  9552. G.argv0_for_re_execing = argv[0];
  9553. #endif
  9554. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9555. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9556. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9557. /* Deal with HUSH_VERSION */
  9558. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9559. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9560. shell_ver = xzalloc(sizeof(*shell_ver));
  9561. shell_ver->flg_export = 1;
  9562. shell_ver->flg_read_only = 1;
  9563. /* Code which handles ${var<op>...} needs writable values for all variables,
  9564. * therefore we xstrdup: */
  9565. shell_ver->varstr = xstrdup(hush_version_str);
  9566. /* Create shell local variables from the values
  9567. * currently living in the environment */
  9568. G.top_var = shell_ver;
  9569. cur_var = G.top_var;
  9570. e = environ;
  9571. if (e) while (*e) {
  9572. char *value = strchr(*e, '=');
  9573. if (value) { /* paranoia */
  9574. cur_var->next = xzalloc(sizeof(*cur_var));
  9575. cur_var = cur_var->next;
  9576. cur_var->varstr = *e;
  9577. cur_var->max_len = strlen(*e);
  9578. cur_var->flg_export = 1;
  9579. }
  9580. e++;
  9581. }
  9582. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9583. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9584. putenv(shell_ver->varstr);
  9585. /* Export PWD */
  9586. set_pwd_var(SETFLAG_EXPORT);
  9587. #if BASH_HOSTNAME_VAR
  9588. /* Set (but not export) HOSTNAME unless already set */
  9589. if (!get_local_var_value("HOSTNAME")) {
  9590. struct utsname uts;
  9591. uname(&uts);
  9592. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9593. }
  9594. #endif
  9595. /* IFS is not inherited from the parent environment */
  9596. set_local_var_from_halves("IFS", defifs);
  9597. if (!get_local_var_value("PATH"))
  9598. set_local_var_from_halves("PATH", bb_default_root_path);
  9599. /* PS1/PS2 are set later, if we determine that we are interactive */
  9600. /* bash also exports SHLVL and _,
  9601. * and sets (but doesn't export) the following variables:
  9602. * BASH=/bin/bash
  9603. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9604. * BASH_VERSION='3.2.0(1)-release'
  9605. * HOSTTYPE=i386
  9606. * MACHTYPE=i386-pc-linux-gnu
  9607. * OSTYPE=linux-gnu
  9608. * PPID=<NNNNN> - we also do it elsewhere
  9609. * EUID=<NNNNN>
  9610. * UID=<NNNNN>
  9611. * GROUPS=()
  9612. * LINES=<NNN>
  9613. * COLUMNS=<NNN>
  9614. * BASH_ARGC=()
  9615. * BASH_ARGV=()
  9616. * BASH_LINENO=()
  9617. * BASH_SOURCE=()
  9618. * DIRSTACK=()
  9619. * PIPESTATUS=([0]="0")
  9620. * HISTFILE=/<xxx>/.bash_history
  9621. * HISTFILESIZE=500
  9622. * HISTSIZE=500
  9623. * MAILCHECK=60
  9624. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9625. * SHELL=/bin/bash
  9626. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9627. * TERM=dumb
  9628. * OPTERR=1
  9629. * OPTIND=1
  9630. * PS4='+ '
  9631. */
  9632. #if NUM_SCRIPTS > 0
  9633. if (argc < 0) {
  9634. char *script = get_script_content(-argc - 1);
  9635. G.global_argv = argv;
  9636. G.global_argc = string_array_len(argv);
  9637. //install_special_sighandlers(); - needed?
  9638. parse_and_run_string(script);
  9639. goto final_return;
  9640. }
  9641. #endif
  9642. /* Initialize some more globals to non-zero values */
  9643. die_func = restore_ttypgrp_and__exit;
  9644. /* Shell is non-interactive at first. We need to call
  9645. * install_special_sighandlers() if we are going to execute "sh <script>",
  9646. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9647. * If we later decide that we are interactive, we run install_special_sighandlers()
  9648. * in order to intercept (more) signals.
  9649. */
  9650. /* Parse options */
  9651. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9652. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9653. while (1) {
  9654. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9655. "cexinsl"
  9656. #if !BB_MMU
  9657. "<:$:R:V:"
  9658. # if ENABLE_HUSH_FUNCTIONS
  9659. "F:"
  9660. # endif
  9661. #endif
  9662. );
  9663. if (opt <= 0)
  9664. break;
  9665. switch (opt) {
  9666. case 'c':
  9667. /* Note: -c is not an option with param!
  9668. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9669. */
  9670. G.opt_c = 1;
  9671. break;
  9672. case 'i':
  9673. /* Well, we cannot just declare interactiveness,
  9674. * we have to have some stuff (ctty, etc) */
  9675. /* G_interactive_fd++; */
  9676. //There are a few cases where bash -i -c 'SCRIPT'
  9677. //has visible effect (differs from bash -c 'SCRIPT'):
  9678. //it ignores TERM:
  9679. // bash -i -c 'kill $$; echo ALIVE'
  9680. // ALIVE
  9681. //it resets SIG_INGed HUP to SIG_DFL:
  9682. // trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
  9683. // Hangup [the message is not printed by bash, it's the shell which started it]
  9684. //is talkative about jobs and exiting:
  9685. // bash -i -c 'sleep 1 & exit'
  9686. // [1] 16170
  9687. // exit
  9688. //includes $ENV file (only if run as "sh"):
  9689. // echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
  9690. // last: cannot open /var/log/wtmp: No such file or directory
  9691. // HERE
  9692. //(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
  9693. //
  9694. //ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
  9695. //(this may be a bug, bash does not do this).
  9696. //(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
  9697. //
  9698. //None of the above feel like useful features people would rely on.
  9699. break;
  9700. case 's':
  9701. G.opt_s = 1;
  9702. break;
  9703. case 'l':
  9704. flags |= OPT_login;
  9705. break;
  9706. #if !BB_MMU
  9707. case '<': /* "big heredoc" support */
  9708. full_write1_str(optarg);
  9709. _exit(0);
  9710. case '$': {
  9711. unsigned long long empty_trap_mask;
  9712. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9713. optarg++;
  9714. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9715. optarg++;
  9716. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9717. optarg++;
  9718. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9719. optarg++;
  9720. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9721. optarg++;
  9722. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9723. if (empty_trap_mask != 0) {
  9724. IF_HUSH_TRAP(int sig;)
  9725. install_special_sighandlers();
  9726. # if ENABLE_HUSH_TRAP
  9727. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9728. for (sig = 1; sig < NSIG; sig++) {
  9729. if (empty_trap_mask & (1LL << sig)) {
  9730. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9731. install_sighandler(sig, SIG_IGN);
  9732. }
  9733. }
  9734. # endif
  9735. }
  9736. # if ENABLE_HUSH_LOOPS
  9737. optarg++;
  9738. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9739. # endif
  9740. /* Suppress "killed by signal" message, -$ hack is used
  9741. * for subshells: echo `sh -c 'kill -9 $$'`
  9742. * should be silent.
  9743. */
  9744. IF_HUSH_JOB(G.run_list_level = 1;)
  9745. # if ENABLE_HUSH_FUNCTIONS
  9746. /* nommu uses re-exec trick for "... | func | ...",
  9747. * should allow "return".
  9748. * This accidentally allows returns in subshells.
  9749. */
  9750. G_flag_return_in_progress = -1;
  9751. # endif
  9752. break;
  9753. }
  9754. case 'R':
  9755. case 'V':
  9756. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9757. break;
  9758. # if ENABLE_HUSH_FUNCTIONS
  9759. case 'F': {
  9760. struct function *funcp = new_function(optarg);
  9761. /* funcp->name is already set to optarg */
  9762. /* funcp->body is set to NULL. It's a special case. */
  9763. funcp->body_as_string = argv[optind];
  9764. optind++;
  9765. break;
  9766. }
  9767. # endif
  9768. #endif
  9769. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9770. /*case 'n':*/
  9771. /*case 'x':*/
  9772. /*case 'e':*/
  9773. default:
  9774. if (set_mode(1, opt, NULL) == 0) /* no error */
  9775. break;
  9776. bb_show_usage();
  9777. }
  9778. } /* option parsing loop */
  9779. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9780. G.global_argc = argc - (optind - 1);
  9781. G.global_argv = argv + (optind - 1);
  9782. G.global_argv[0] = argv[0];
  9783. /* If we are login shell... */
  9784. if (flags & OPT_login) {
  9785. const char *hp = NULL;
  9786. HFILE *input;
  9787. debug_printf("sourcing /etc/profile\n");
  9788. input = hfopen("/etc/profile");
  9789. run_profile:
  9790. if (input != NULL) {
  9791. install_special_sighandlers();
  9792. parse_and_run_file(input);
  9793. hfclose(input);
  9794. }
  9795. /* bash: after sourcing /etc/profile,
  9796. * tries to source (in the given order):
  9797. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9798. * stopping on first found. --noprofile turns this off.
  9799. * bash also sources ~/.bash_logout on exit.
  9800. * If called as sh, skips .bash_XXX files.
  9801. */
  9802. if (!hp) { /* unless we looped on the "goto" already */
  9803. hp = get_local_var_value("HOME");
  9804. if (hp && hp[0]) {
  9805. debug_printf("sourcing ~/.profile\n");
  9806. hp = concat_path_file(hp, ".profile");
  9807. input = hfopen(hp);
  9808. free((char*)hp);
  9809. goto run_profile;
  9810. }
  9811. }
  9812. }
  9813. /* -c takes effect *after* -l */
  9814. if (G.opt_c) {
  9815. /* Possibilities:
  9816. * sh ... -c 'script'
  9817. * sh ... -c 'script' ARG0 [ARG1...]
  9818. * On NOMMU, if builtin_argc != 0,
  9819. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9820. * "" needs to be replaced with NULL
  9821. * and BARGV vector fed to builtin function.
  9822. * Note: the form without ARG0 never happens:
  9823. * sh ... -c 'builtin' BARGV... ""
  9824. */
  9825. char *script;
  9826. install_special_sighandlers();
  9827. G.global_argc--;
  9828. G.global_argv++;
  9829. #if !BB_MMU
  9830. if (builtin_argc) {
  9831. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9832. const struct built_in_command *x;
  9833. x = find_builtin(G.global_argv[0]);
  9834. if (x) { /* paranoia */
  9835. argv = G.global_argv;
  9836. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9837. G.global_argv += builtin_argc + 1;
  9838. G.global_argv[-1] = NULL; /* replace "" */
  9839. G.last_exitcode = x->b_function(argv);
  9840. }
  9841. goto final_return;
  9842. }
  9843. #endif
  9844. script = G.global_argv[0];
  9845. if (!script)
  9846. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9847. if (!G.global_argv[1]) {
  9848. /* -c 'script' (no params): prevent empty $0 */
  9849. G.global_argv[0] = argv[0];
  9850. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9851. G.global_argc--;
  9852. G.global_argv++;
  9853. }
  9854. parse_and_run_string(script);
  9855. goto final_return;
  9856. }
  9857. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9858. if (!G.opt_s && G.global_argv[1]) {
  9859. HFILE *input;
  9860. /*
  9861. * "bash <script>" (which is never interactive (unless -i?))
  9862. * sources $BASH_ENV here (without scanning $PATH).
  9863. * If called as sh, does the same but with $ENV.
  9864. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9865. */
  9866. G.global_argc--;
  9867. G.global_argv++;
  9868. debug_printf("running script '%s'\n", G.global_argv[0]);
  9869. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9870. input = hfopen(G.global_argv[0]);
  9871. if (!input) {
  9872. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9873. }
  9874. xfunc_error_retval = 1;
  9875. install_special_sighandlers();
  9876. parse_and_run_file(input);
  9877. #if ENABLE_FEATURE_CLEAN_UP
  9878. hfclose(input);
  9879. #endif
  9880. goto final_return;
  9881. }
  9882. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9883. G.opt_s = 1;
  9884. /* Up to here, shell was non-interactive. Now it may become one.
  9885. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9886. */
  9887. /* A shell is interactive if the '-i' flag was given,
  9888. * or if all of the following conditions are met:
  9889. * no -c command
  9890. * no arguments remaining or the -s flag given
  9891. * standard input is a terminal
  9892. * standard output is a terminal
  9893. * Refer to Posix.2, the description of the 'sh' utility.
  9894. */
  9895. #if ENABLE_HUSH_JOB
  9896. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9897. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9898. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9899. if (G_saved_tty_pgrp < 0)
  9900. G_saved_tty_pgrp = 0;
  9901. /* try to dup stdin to high fd#, >= 255 */
  9902. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9903. if (G_interactive_fd < 0) {
  9904. /* try to dup to any fd */
  9905. G_interactive_fd = dup(STDIN_FILENO);
  9906. if (G_interactive_fd < 0) {
  9907. /* give up */
  9908. G_interactive_fd = 0;
  9909. G_saved_tty_pgrp = 0;
  9910. }
  9911. }
  9912. }
  9913. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9914. if (G_interactive_fd) {
  9915. close_on_exec_on(G_interactive_fd);
  9916. if (G_saved_tty_pgrp) {
  9917. /* If we were run as 'hush &', sleep until we are
  9918. * in the foreground (tty pgrp == our pgrp).
  9919. * If we get started under a job aware app (like bash),
  9920. * make sure we are now in charge so we don't fight over
  9921. * who gets the foreground */
  9922. while (1) {
  9923. pid_t shell_pgrp = getpgrp();
  9924. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9925. if (G_saved_tty_pgrp == shell_pgrp)
  9926. break;
  9927. /* send TTIN to ourself (should stop us) */
  9928. kill(- shell_pgrp, SIGTTIN);
  9929. }
  9930. }
  9931. /* Install more signal handlers */
  9932. install_special_sighandlers();
  9933. if (G_saved_tty_pgrp) {
  9934. /* Set other signals to restore saved_tty_pgrp */
  9935. install_fatal_sighandlers();
  9936. /* Put ourselves in our own process group
  9937. * (bash, too, does this only if ctty is available) */
  9938. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9939. /* Grab control of the terminal */
  9940. tcsetpgrp(G_interactive_fd, cached_getpid);
  9941. }
  9942. enable_restore_tty_pgrp_on_exit();
  9943. # if ENABLE_FEATURE_EDITING
  9944. G.line_input_state = new_line_input_t(FOR_SHELL);
  9945. # if EDITING_HAS_get_exe_name
  9946. G.line_input_state->get_exe_name = get_builtin_name;
  9947. # endif
  9948. # endif
  9949. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9950. {
  9951. const char *hp = get_local_var_value("HISTFILE");
  9952. if (!hp) {
  9953. hp = get_local_var_value("HOME");
  9954. if (hp)
  9955. hp = concat_path_file(hp, ".hush_history");
  9956. } else {
  9957. hp = xstrdup(hp);
  9958. }
  9959. if (hp) {
  9960. G.line_input_state->hist_file = hp;
  9961. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9962. }
  9963. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9964. hp = get_local_var_value("HISTFILESIZE");
  9965. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9966. # endif
  9967. }
  9968. # endif
  9969. } else {
  9970. install_special_sighandlers();
  9971. }
  9972. #elif ENABLE_HUSH_INTERACTIVE
  9973. /* No job control compiled in, only prompt/line editing */
  9974. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9975. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9976. if (G_interactive_fd < 0) {
  9977. /* try to dup to any fd */
  9978. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9979. if (G_interactive_fd < 0)
  9980. /* give up */
  9981. G_interactive_fd = 0;
  9982. }
  9983. }
  9984. if (G_interactive_fd) {
  9985. close_on_exec_on(G_interactive_fd);
  9986. }
  9987. install_special_sighandlers();
  9988. #else
  9989. /* We have interactiveness code disabled */
  9990. install_special_sighandlers();
  9991. #endif
  9992. /* bash:
  9993. * if interactive but not a login shell, sources ~/.bashrc
  9994. * (--norc turns this off, --rcfile <file> overrides)
  9995. */
  9996. if (G_interactive_fd) {
  9997. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9998. /* Set (but not export) PS1/2 unless already set */
  9999. if (!get_local_var_value("PS1"))
  10000. set_local_var_from_halves("PS1", "\\w \\$ ");
  10001. if (!get_local_var_value("PS2"))
  10002. set_local_var_from_halves("PS2", "> ");
  10003. #endif
  10004. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  10005. /* note: ash and hush share this string */
  10006. printf("\n\n%s %s\n"
  10007. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  10008. "\n",
  10009. bb_banner,
  10010. "hush - the humble shell"
  10011. );
  10012. }
  10013. }
  10014. parse_and_run_file(hfopen(NULL)); /* stdin */
  10015. final_return:
  10016. hush_exit(G.last_exitcode);
  10017. }
  10018. /*
  10019. * Built-ins
  10020. */
  10021. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  10022. {
  10023. return 0;
  10024. }
  10025. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  10026. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  10027. {
  10028. int argc = string_array_len(argv);
  10029. return applet_main_func(argc, argv);
  10030. }
  10031. #endif
  10032. #if ENABLE_HUSH_TEST || BASH_TEST2
  10033. static int FAST_FUNC builtin_test(char **argv)
  10034. {
  10035. return run_applet_main(argv, test_main);
  10036. }
  10037. #endif
  10038. #if ENABLE_HUSH_ECHO
  10039. static int FAST_FUNC builtin_echo(char **argv)
  10040. {
  10041. return run_applet_main(argv, echo_main);
  10042. }
  10043. #endif
  10044. #if ENABLE_HUSH_PRINTF
  10045. static int FAST_FUNC builtin_printf(char **argv)
  10046. {
  10047. return run_applet_main(argv, printf_main);
  10048. }
  10049. #endif
  10050. #if ENABLE_HUSH_HELP
  10051. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10052. {
  10053. const struct built_in_command *x;
  10054. printf(
  10055. "Built-in commands:\n"
  10056. "------------------\n");
  10057. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10058. if (x->b_descr)
  10059. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10060. }
  10061. return EXIT_SUCCESS;
  10062. }
  10063. #endif
  10064. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10065. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10066. {
  10067. show_history(G.line_input_state);
  10068. return EXIT_SUCCESS;
  10069. }
  10070. #endif
  10071. static char **skip_dash_dash(char **argv)
  10072. {
  10073. argv++;
  10074. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  10075. argv++;
  10076. return argv;
  10077. }
  10078. static int FAST_FUNC builtin_cd(char **argv)
  10079. {
  10080. const char *newdir;
  10081. argv = skip_dash_dash(argv);
  10082. newdir = argv[0];
  10083. if (newdir == NULL) {
  10084. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10085. * bash says "bash: cd: HOME not set" and does nothing
  10086. * (exitcode 1)
  10087. */
  10088. const char *home = get_local_var_value("HOME");
  10089. newdir = home ? home : "/";
  10090. }
  10091. if (chdir(newdir)) {
  10092. /* Mimic bash message exactly */
  10093. bb_perror_msg("cd: %s", newdir);
  10094. return EXIT_FAILURE;
  10095. }
  10096. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10097. * Note: do not enforce exporting. If PWD was unset or unexported,
  10098. * set it again, but do not export. bash does the same.
  10099. */
  10100. set_pwd_var(/*flag:*/ 0);
  10101. return EXIT_SUCCESS;
  10102. }
  10103. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10104. {
  10105. puts(get_cwd(0));
  10106. return EXIT_SUCCESS;
  10107. }
  10108. static int FAST_FUNC builtin_eval(char **argv)
  10109. {
  10110. argv = skip_dash_dash(argv);
  10111. if (!argv[0])
  10112. return EXIT_SUCCESS;
  10113. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10114. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10115. if (!argv[1]) {
  10116. /* bash:
  10117. * eval "echo Hi; done" ("done" is syntax error):
  10118. * "echo Hi" will not execute too.
  10119. */
  10120. parse_and_run_string(argv[0]);
  10121. } else {
  10122. /* "The eval utility shall construct a command by
  10123. * concatenating arguments together, separating
  10124. * each with a <space> character."
  10125. */
  10126. char *str, *p;
  10127. unsigned len = 0;
  10128. char **pp = argv;
  10129. do
  10130. len += strlen(*pp) + 1;
  10131. while (*++pp);
  10132. str = p = xmalloc(len);
  10133. pp = argv;
  10134. for (;;) {
  10135. p = stpcpy(p, *pp);
  10136. pp++;
  10137. if (!*pp)
  10138. break;
  10139. *p++ = ' ';
  10140. }
  10141. parse_and_run_string(str);
  10142. free(str);
  10143. }
  10144. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10145. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10146. return G.last_exitcode;
  10147. }
  10148. static int FAST_FUNC builtin_exec(char **argv)
  10149. {
  10150. argv = skip_dash_dash(argv);
  10151. if (argv[0] == NULL)
  10152. return EXIT_SUCCESS; /* bash does this */
  10153. /* Careful: we can end up here after [v]fork. Do not restore
  10154. * tty pgrp then, only top-level shell process does that */
  10155. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10156. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10157. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10158. * open here. However, they are all CLOEXEC, and execv below
  10159. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10160. * it should show no extra open fds in the "ls" process.
  10161. * If we'd try to run builtins/NOEXECs, this would need improving.
  10162. */
  10163. //close_saved_fds_and_FILE_fds();
  10164. /* TODO: if exec fails, bash does NOT exit! We do.
  10165. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10166. * and tcsetpgrp, and this is inherently racy.
  10167. */
  10168. execvp_or_die(argv);
  10169. }
  10170. static int FAST_FUNC builtin_exit(char **argv)
  10171. {
  10172. debug_printf_exec("%s()\n", __func__);
  10173. /* interactive bash:
  10174. * # trap "echo EEE" EXIT
  10175. * # exit
  10176. * exit
  10177. * There are stopped jobs.
  10178. * (if there are _stopped_ jobs, running ones don't count)
  10179. * # exit
  10180. * exit
  10181. * EEE (then bash exits)
  10182. *
  10183. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10184. */
  10185. /* note: EXIT trap is run by hush_exit */
  10186. argv = skip_dash_dash(argv);
  10187. if (argv[0] == NULL) {
  10188. #if ENABLE_HUSH_TRAP
  10189. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10190. hush_exit(G.pre_trap_exitcode);
  10191. #endif
  10192. hush_exit(G.last_exitcode);
  10193. }
  10194. /* mimic bash: exit 123abc == exit 255 + error msg */
  10195. xfunc_error_retval = 255;
  10196. /* bash: exit -2 == exit 254, no error msg */
  10197. hush_exit(xatoi(argv[0]) & 0xff);
  10198. }
  10199. #if ENABLE_HUSH_TYPE
  10200. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10201. static int FAST_FUNC builtin_type(char **argv)
  10202. {
  10203. int ret = EXIT_SUCCESS;
  10204. while (*++argv) {
  10205. const char *type;
  10206. char *path = NULL;
  10207. if (0) {} /* make conditional compile easier below */
  10208. /*else if (find_alias(*argv))
  10209. type = "an alias";*/
  10210. # if ENABLE_HUSH_FUNCTIONS
  10211. else if (find_function(*argv))
  10212. type = "a function";
  10213. # endif
  10214. else if (find_builtin(*argv))
  10215. type = "a shell builtin";
  10216. else if ((path = find_in_path(*argv)) != NULL)
  10217. type = path;
  10218. else {
  10219. bb_error_msg("type: %s: not found", *argv);
  10220. ret = EXIT_FAILURE;
  10221. continue;
  10222. }
  10223. printf("%s is %s\n", *argv, type);
  10224. free(path);
  10225. }
  10226. return ret;
  10227. }
  10228. #endif
  10229. #if ENABLE_HUSH_READ
  10230. /* Interruptibility of read builtin in bash
  10231. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10232. *
  10233. * Empty trap makes read ignore corresponding signal, for any signal.
  10234. *
  10235. * SIGINT:
  10236. * - terminates non-interactive shell;
  10237. * - interrupts read in interactive shell;
  10238. * if it has non-empty trap:
  10239. * - executes trap and returns to command prompt in interactive shell;
  10240. * - executes trap and returns to read in non-interactive shell;
  10241. * SIGTERM:
  10242. * - is ignored (does not interrupt) read in interactive shell;
  10243. * - terminates non-interactive shell;
  10244. * if it has non-empty trap:
  10245. * - executes trap and returns to read;
  10246. * SIGHUP:
  10247. * - terminates shell (regardless of interactivity);
  10248. * if it has non-empty trap:
  10249. * - executes trap and returns to read;
  10250. * SIGCHLD from children:
  10251. * - does not interrupt read regardless of interactivity:
  10252. * try: sleep 1 & read x; echo $x
  10253. */
  10254. static int FAST_FUNC builtin_read(char **argv)
  10255. {
  10256. const char *r;
  10257. struct builtin_read_params params;
  10258. memset(&params, 0, sizeof(params));
  10259. /* "!": do not abort on errors.
  10260. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10261. */
  10262. params.read_flags = getopt32(argv,
  10263. # if BASH_READ_D
  10264. IF_NOT_HUSH_BASH_COMPAT("^")
  10265. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10266. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10267. # else
  10268. IF_NOT_HUSH_BASH_COMPAT("^")
  10269. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10270. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10271. # endif
  10272. //TODO: print "read: need variable name"
  10273. //for the case of !BASH "read" with no args (now it fails silently)
  10274. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10275. );
  10276. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10277. return EXIT_FAILURE;
  10278. argv += optind;
  10279. params.argv = argv;
  10280. params.setvar = set_local_var_from_halves;
  10281. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10282. again:
  10283. r = shell_builtin_read(&params);
  10284. if ((uintptr_t)r == 1 && errno == EINTR) {
  10285. unsigned sig = check_and_run_traps();
  10286. if (sig != SIGINT)
  10287. goto again;
  10288. }
  10289. if ((uintptr_t)r > 1) {
  10290. bb_simple_error_msg(r);
  10291. r = (char*)(uintptr_t)1;
  10292. }
  10293. return (uintptr_t)r;
  10294. }
  10295. #endif
  10296. #if ENABLE_HUSH_UMASK
  10297. static int FAST_FUNC builtin_umask(char **argv)
  10298. {
  10299. int rc;
  10300. mode_t mask;
  10301. rc = 1;
  10302. mask = umask(0);
  10303. argv = skip_dash_dash(argv);
  10304. if (argv[0]) {
  10305. mode_t old_mask = mask;
  10306. /* numeric umasks are taken as-is */
  10307. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10308. if (!isdigit(argv[0][0]))
  10309. mask ^= 0777;
  10310. mask = bb_parse_mode(argv[0], mask);
  10311. if (!isdigit(argv[0][0]))
  10312. mask ^= 0777;
  10313. if ((unsigned)mask > 0777) {
  10314. mask = old_mask;
  10315. /* bash messages:
  10316. * bash: umask: 'q': invalid symbolic mode operator
  10317. * bash: umask: 999: octal number out of range
  10318. */
  10319. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10320. rc = 0;
  10321. }
  10322. } else {
  10323. /* Mimic bash */
  10324. printf("%04o\n", (unsigned) mask);
  10325. /* fall through and restore mask which we set to 0 */
  10326. }
  10327. umask(mask);
  10328. return !rc; /* rc != 0 - success */
  10329. }
  10330. #endif
  10331. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10332. static void print_escaped(const char *s)
  10333. {
  10334. if (*s == '\'')
  10335. goto squote;
  10336. do {
  10337. const char *p = strchrnul(s, '\'');
  10338. /* print 'xxxx', possibly just '' */
  10339. printf("'%.*s'", (int)(p - s), s);
  10340. if (*p == '\0')
  10341. break;
  10342. s = p;
  10343. squote:
  10344. /* s points to '; print "'''...'''" */
  10345. putchar('"');
  10346. do putchar('\''); while (*++s == '\'');
  10347. putchar('"');
  10348. } while (*s);
  10349. }
  10350. #endif
  10351. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10352. static int helper_export_local(char **argv, unsigned flags)
  10353. {
  10354. do {
  10355. char *name = *argv;
  10356. const char *name_end = endofname(name);
  10357. if (*name_end == '\0') {
  10358. struct variable *var, **vpp;
  10359. vpp = get_ptr_to_local_var(name, name_end - name);
  10360. var = vpp ? *vpp : NULL;
  10361. if (flags & SETFLAG_UNEXPORT) {
  10362. /* export -n NAME (without =VALUE) */
  10363. if (var) {
  10364. var->flg_export = 0;
  10365. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10366. unsetenv(name);
  10367. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10368. continue;
  10369. }
  10370. if (flags & SETFLAG_EXPORT) {
  10371. /* export NAME (without =VALUE) */
  10372. if (var) {
  10373. var->flg_export = 1;
  10374. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10375. putenv(var->varstr);
  10376. continue;
  10377. }
  10378. }
  10379. if (flags & SETFLAG_MAKE_RO) {
  10380. /* readonly NAME (without =VALUE) */
  10381. if (var) {
  10382. var->flg_read_only = 1;
  10383. continue;
  10384. }
  10385. }
  10386. # if ENABLE_HUSH_LOCAL
  10387. /* Is this "local" bltin? */
  10388. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10389. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10390. if (var && var->var_nest_level == lvl) {
  10391. /* "local x=abc; ...; local x" - ignore second local decl */
  10392. continue;
  10393. }
  10394. }
  10395. # endif
  10396. /* Exporting non-existing variable.
  10397. * bash does not put it in environment,
  10398. * but remembers that it is exported,
  10399. * and does put it in env when it is set later.
  10400. * We just set it to "" and export.
  10401. */
  10402. /* Or, it's "local NAME" (without =VALUE).
  10403. * bash sets the value to "".
  10404. */
  10405. /* Or, it's "readonly NAME" (without =VALUE).
  10406. * bash remembers NAME and disallows its creation
  10407. * in the future.
  10408. */
  10409. name = xasprintf("%s=", name);
  10410. } else {
  10411. if (*name_end != '=') {
  10412. bb_error_msg("'%s': bad variable name", name);
  10413. /* do not parse following argv[]s: */
  10414. return 1;
  10415. }
  10416. /* (Un)exporting/making local NAME=VALUE */
  10417. name = xstrdup(name);
  10418. /* Testcase: export PS1='\w \$ ' */
  10419. unbackslash(name);
  10420. }
  10421. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10422. if (set_local_var(name, flags))
  10423. return EXIT_FAILURE;
  10424. } while (*++argv);
  10425. return EXIT_SUCCESS;
  10426. }
  10427. #endif
  10428. #if ENABLE_HUSH_EXPORT
  10429. static int FAST_FUNC builtin_export(char **argv)
  10430. {
  10431. unsigned opt_unexport;
  10432. # if ENABLE_HUSH_EXPORT_N
  10433. /* "!": do not abort on errors */
  10434. opt_unexport = getopt32(argv, "!n");
  10435. if (opt_unexport == (uint32_t)-1)
  10436. return EXIT_FAILURE;
  10437. argv += optind;
  10438. # else
  10439. opt_unexport = 0;
  10440. argv++;
  10441. # endif
  10442. if (argv[0] == NULL) {
  10443. char **e = environ;
  10444. if (e) {
  10445. while (*e) {
  10446. # if 0
  10447. puts(*e++);
  10448. # else
  10449. /* ash emits: export VAR='VAL'
  10450. * bash: declare -x VAR="VAL"
  10451. * we follow ash example */
  10452. const char *s = *e++;
  10453. const char *p = strchr(s, '=');
  10454. if (!p) /* wtf? take next variable */
  10455. continue;
  10456. /* export var= */
  10457. printf("export %.*s", (int)(p - s) + 1, s);
  10458. print_escaped(p + 1);
  10459. putchar('\n');
  10460. # endif
  10461. }
  10462. /*fflush_all(); - done after each builtin anyway */
  10463. }
  10464. return EXIT_SUCCESS;
  10465. }
  10466. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10467. }
  10468. #endif
  10469. #if ENABLE_HUSH_LOCAL
  10470. static int FAST_FUNC builtin_local(char **argv)
  10471. {
  10472. if (G.func_nest_level == 0) {
  10473. bb_error_msg("%s: not in a function", argv[0]);
  10474. return EXIT_FAILURE; /* bash compat */
  10475. }
  10476. argv++;
  10477. /* Since all builtins run in a nested variable level,
  10478. * need to use level - 1 here. Or else the variable will be removed at once
  10479. * after builtin returns.
  10480. */
  10481. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10482. }
  10483. #endif
  10484. #if ENABLE_HUSH_READONLY
  10485. static int FAST_FUNC builtin_readonly(char **argv)
  10486. {
  10487. argv++;
  10488. if (*argv == NULL) {
  10489. /* bash: readonly [-p]: list all readonly VARs
  10490. * (-p has no effect in bash)
  10491. */
  10492. struct variable *e;
  10493. for (e = G.top_var; e; e = e->next) {
  10494. if (e->flg_read_only) {
  10495. //TODO: quote value: readonly VAR='VAL'
  10496. printf("readonly %s\n", e->varstr);
  10497. }
  10498. }
  10499. return EXIT_SUCCESS;
  10500. }
  10501. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10502. }
  10503. #endif
  10504. #if ENABLE_HUSH_UNSET
  10505. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10506. static int FAST_FUNC builtin_unset(char **argv)
  10507. {
  10508. int ret;
  10509. unsigned opts;
  10510. /* "!": do not abort on errors */
  10511. /* "+": stop at 1st non-option */
  10512. opts = getopt32(argv, "!+vf");
  10513. if (opts == (unsigned)-1)
  10514. return EXIT_FAILURE;
  10515. if (opts == 3) {
  10516. bb_simple_error_msg("unset: -v and -f are exclusive");
  10517. return EXIT_FAILURE;
  10518. }
  10519. argv += optind;
  10520. ret = EXIT_SUCCESS;
  10521. while (*argv) {
  10522. if (!(opts & 2)) { /* not -f */
  10523. if (unset_local_var(*argv)) {
  10524. /* unset <nonexistent_var> doesn't fail.
  10525. * Error is when one tries to unset RO var.
  10526. * Message was printed by unset_local_var. */
  10527. ret = EXIT_FAILURE;
  10528. }
  10529. }
  10530. # if ENABLE_HUSH_FUNCTIONS
  10531. else {
  10532. unset_func(*argv);
  10533. }
  10534. # endif
  10535. argv++;
  10536. }
  10537. return ret;
  10538. }
  10539. #endif
  10540. #if ENABLE_HUSH_SET
  10541. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10542. * built-in 'set' handler
  10543. * SUSv3 says:
  10544. * set [-abCefhmnuvx] [-o option] [argument...]
  10545. * set [+abCefhmnuvx] [+o option] [argument...]
  10546. * set -- [argument...]
  10547. * set -o
  10548. * set +o
  10549. * Implementations shall support the options in both their hyphen and
  10550. * plus-sign forms. These options can also be specified as options to sh.
  10551. * Examples:
  10552. * Write out all variables and their values: set
  10553. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10554. * Turn on the -x and -v options: set -xv
  10555. * Unset all positional parameters: set --
  10556. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10557. * Set the positional parameters to the expansion of x, even if x expands
  10558. * with a leading '-' or '+': set -- $x
  10559. *
  10560. * So far, we only support "set -- [argument...]" and some of the short names.
  10561. */
  10562. static int FAST_FUNC builtin_set(char **argv)
  10563. {
  10564. int n;
  10565. char **pp, **g_argv;
  10566. char *arg = *++argv;
  10567. if (arg == NULL) {
  10568. struct variable *e;
  10569. for (e = G.top_var; e; e = e->next)
  10570. puts(e->varstr);
  10571. return EXIT_SUCCESS;
  10572. }
  10573. do {
  10574. if (strcmp(arg, "--") == 0) {
  10575. ++argv;
  10576. goto set_argv;
  10577. }
  10578. if (arg[0] != '+' && arg[0] != '-')
  10579. break;
  10580. for (n = 1; arg[n]; ++n) {
  10581. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10582. bb_error_msg("%s: %s: invalid option", "set", arg);
  10583. return EXIT_FAILURE;
  10584. }
  10585. if (arg[n] == 'o' && argv[1])
  10586. argv++;
  10587. }
  10588. } while ((arg = *++argv) != NULL);
  10589. /* Now argv[0] is 1st argument */
  10590. if (arg == NULL)
  10591. return EXIT_SUCCESS;
  10592. set_argv:
  10593. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10594. g_argv = G.global_argv;
  10595. if (G.global_args_malloced) {
  10596. pp = g_argv;
  10597. while (*++pp)
  10598. free(*pp);
  10599. g_argv[1] = NULL;
  10600. } else {
  10601. G.global_args_malloced = 1;
  10602. pp = xzalloc(sizeof(pp[0]) * 2);
  10603. pp[0] = g_argv[0]; /* retain $0 */
  10604. g_argv = pp;
  10605. }
  10606. /* This realloc's G.global_argv */
  10607. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10608. G.global_argc = 1 + string_array_len(pp + 1);
  10609. return EXIT_SUCCESS;
  10610. }
  10611. #endif
  10612. static int FAST_FUNC builtin_shift(char **argv)
  10613. {
  10614. int n = 1;
  10615. argv = skip_dash_dash(argv);
  10616. if (argv[0]) {
  10617. n = bb_strtou(argv[0], NULL, 10);
  10618. if (errno || n < 0) {
  10619. /* shared string with ash.c */
  10620. bb_error_msg("Illegal number: %s", argv[0]);
  10621. /*
  10622. * ash aborts in this case.
  10623. * bash prints error message and set $? to 1.
  10624. * Interestingly, for "shift 99999" bash does not
  10625. * print error message, but does set $? to 1
  10626. * (and does no shifting at all).
  10627. */
  10628. }
  10629. }
  10630. if (n >= 0 && n < G.global_argc) {
  10631. if (G_global_args_malloced) {
  10632. int m = 1;
  10633. while (m <= n)
  10634. free(G.global_argv[m++]);
  10635. }
  10636. G.global_argc -= n;
  10637. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10638. G.global_argc * sizeof(G.global_argv[0]));
  10639. return EXIT_SUCCESS;
  10640. }
  10641. return EXIT_FAILURE;
  10642. }
  10643. #if ENABLE_HUSH_GETOPTS
  10644. static int FAST_FUNC builtin_getopts(char **argv)
  10645. {
  10646. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10647. TODO:
  10648. If a required argument is not found, and getopts is not silent,
  10649. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10650. diagnostic message is printed. If getopts is silent, then a
  10651. colon (:) is placed in VAR and OPTARG is set to the option
  10652. character found.
  10653. Test that VAR is a valid variable name?
  10654. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10655. */
  10656. char cbuf[2];
  10657. const char *cp, *optstring, *var;
  10658. int c, n, exitcode, my_opterr;
  10659. unsigned count;
  10660. optstring = *++argv;
  10661. if (!optstring || !(var = *++argv)) {
  10662. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10663. return EXIT_FAILURE;
  10664. }
  10665. if (argv[1])
  10666. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10667. else
  10668. argv = G.global_argv;
  10669. cbuf[1] = '\0';
  10670. my_opterr = 0;
  10671. if (optstring[0] != ':') {
  10672. cp = get_local_var_value("OPTERR");
  10673. /* 0 if "OPTERR=0", 1 otherwise */
  10674. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10675. }
  10676. /* getopts stops on first non-option. Add "+" to force that */
  10677. /*if (optstring[0] != '+')*/ {
  10678. char *s = alloca(strlen(optstring) + 2);
  10679. sprintf(s, "+%s", optstring);
  10680. optstring = s;
  10681. }
  10682. /* Naively, now we should just
  10683. * cp = get_local_var_value("OPTIND");
  10684. * optind = cp ? atoi(cp) : 0;
  10685. * optarg = NULL;
  10686. * opterr = my_opterr;
  10687. * c = getopt(string_array_len(argv), argv, optstring);
  10688. * and be done? Not so fast...
  10689. * Unlike normal getopt() usage in C programs, here
  10690. * each successive call will (usually) have the same argv[] CONTENTS,
  10691. * but not the ADDRESSES. Worse yet, it's possible that between
  10692. * invocations of "getopts", there will be calls to shell builtins
  10693. * which use getopt() internally. Example:
  10694. * while getopts "abc" RES -a -bc -abc de; do
  10695. * unset -ff func
  10696. * done
  10697. * This would not work correctly: getopt() call inside "unset"
  10698. * modifies internal libc state which is tracking position in
  10699. * multi-option strings ("-abc"). At best, it can skip options
  10700. * or return the same option infinitely. With glibc implementation
  10701. * of getopt(), it would use outright invalid pointers and return
  10702. * garbage even _without_ "unset" mangling internal state.
  10703. *
  10704. * We resort to resetting getopt() state and calling it N times,
  10705. * until we get Nth result (or failure).
  10706. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10707. */
  10708. GETOPT_RESET();
  10709. count = 0;
  10710. n = string_array_len(argv);
  10711. do {
  10712. optarg = NULL;
  10713. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10714. c = getopt(n, argv, optstring);
  10715. if (c < 0)
  10716. break;
  10717. count++;
  10718. } while (count <= G.getopt_count);
  10719. /* Set OPTIND. Prevent resetting of the magic counter! */
  10720. set_local_var_from_halves("OPTIND", utoa(optind));
  10721. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10722. GETOPT_RESET(); /* just in case */
  10723. /* Set OPTARG */
  10724. /* Always set or unset, never left as-is, even on exit/error:
  10725. * "If no option was found, or if the option that was found
  10726. * does not have an option-argument, OPTARG shall be unset."
  10727. */
  10728. cp = optarg;
  10729. if (c == '?') {
  10730. /* If ":optstring" and unknown option is seen,
  10731. * it is stored to OPTARG.
  10732. */
  10733. if (optstring[1] == ':') {
  10734. cbuf[0] = optopt;
  10735. cp = cbuf;
  10736. }
  10737. }
  10738. if (cp)
  10739. set_local_var_from_halves("OPTARG", cp);
  10740. else
  10741. unset_local_var("OPTARG");
  10742. /* Convert -1 to "?" */
  10743. exitcode = EXIT_SUCCESS;
  10744. if (c < 0) { /* -1: end of options */
  10745. exitcode = EXIT_FAILURE;
  10746. c = '?';
  10747. }
  10748. /* Set VAR */
  10749. cbuf[0] = c;
  10750. set_local_var_from_halves(var, cbuf);
  10751. return exitcode;
  10752. }
  10753. #endif
  10754. static int FAST_FUNC builtin_source(char **argv)
  10755. {
  10756. char *arg_path, *filename;
  10757. HFILE *input;
  10758. save_arg_t sv;
  10759. char *args_need_save;
  10760. #if ENABLE_HUSH_FUNCTIONS
  10761. smallint sv_flg;
  10762. #endif
  10763. argv = skip_dash_dash(argv);
  10764. filename = argv[0];
  10765. if (!filename) {
  10766. /* bash says: "bash: .: filename argument required" */
  10767. return 2; /* bash compat */
  10768. }
  10769. arg_path = NULL;
  10770. if (!strchr(filename, '/')) {
  10771. arg_path = find_in_path(filename);
  10772. if (arg_path)
  10773. filename = arg_path;
  10774. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10775. errno = ENOENT;
  10776. bb_simple_perror_msg(filename);
  10777. return EXIT_FAILURE;
  10778. }
  10779. }
  10780. input = hfopen(filename);
  10781. free(arg_path);
  10782. if (!input) {
  10783. bb_perror_msg("%s", filename);
  10784. /* POSIX: non-interactive shell should abort here,
  10785. * not merely fail. So far no one complained :)
  10786. */
  10787. return EXIT_FAILURE;
  10788. }
  10789. #if ENABLE_HUSH_FUNCTIONS
  10790. sv_flg = G_flag_return_in_progress;
  10791. /* "we are inside sourced file, ok to use return" */
  10792. G_flag_return_in_progress = -1;
  10793. #endif
  10794. args_need_save = argv[1]; /* used as a boolean variable */
  10795. if (args_need_save)
  10796. save_and_replace_G_args(&sv, argv);
  10797. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10798. G.last_exitcode = 0;
  10799. parse_and_run_file(input);
  10800. hfclose(input);
  10801. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10802. restore_G_args(&sv, argv);
  10803. #if ENABLE_HUSH_FUNCTIONS
  10804. G_flag_return_in_progress = sv_flg;
  10805. #endif
  10806. return G.last_exitcode;
  10807. }
  10808. #if ENABLE_HUSH_TRAP
  10809. static int FAST_FUNC builtin_trap(char **argv)
  10810. {
  10811. int sig;
  10812. char *new_cmd;
  10813. if (!G_traps)
  10814. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10815. argv++;
  10816. if (!*argv) {
  10817. int i;
  10818. /* No args: print all trapped */
  10819. for (i = 0; i < NSIG; ++i) {
  10820. if (G_traps[i]) {
  10821. printf("trap -- ");
  10822. print_escaped(G_traps[i]);
  10823. /* note: bash adds "SIG", but only if invoked
  10824. * as "bash". If called as "sh", or if set -o posix,
  10825. * then it prints short signal names.
  10826. * We are printing short names: */
  10827. printf(" %s\n", get_signame(i));
  10828. }
  10829. }
  10830. /*fflush_all(); - done after each builtin anyway */
  10831. return EXIT_SUCCESS;
  10832. }
  10833. new_cmd = NULL;
  10834. /* If first arg is a number: reset all specified signals */
  10835. sig = bb_strtou(*argv, NULL, 10);
  10836. if (errno == 0) {
  10837. int ret;
  10838. process_sig_list:
  10839. ret = EXIT_SUCCESS;
  10840. while (*argv) {
  10841. sighandler_t handler;
  10842. sig = get_signum(*argv++);
  10843. if (sig < 0) {
  10844. ret = EXIT_FAILURE;
  10845. /* Mimic bash message exactly */
  10846. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10847. continue;
  10848. }
  10849. free(G_traps[sig]);
  10850. G_traps[sig] = xstrdup(new_cmd);
  10851. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10852. get_signame(sig), sig, G_traps[sig]);
  10853. /* There is no signal for 0 (EXIT) */
  10854. if (sig == 0)
  10855. continue;
  10856. if (new_cmd)
  10857. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10858. else
  10859. /* We are removing trap handler */
  10860. handler = pick_sighandler(sig);
  10861. install_sighandler(sig, handler);
  10862. }
  10863. return ret;
  10864. }
  10865. if (!argv[1]) { /* no second arg */
  10866. bb_simple_error_msg("trap: invalid arguments");
  10867. return EXIT_FAILURE;
  10868. }
  10869. /* First arg is "-": reset all specified to default */
  10870. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10871. /* Everything else: set arg as signal handler
  10872. * (includes "" case, which ignores signal) */
  10873. if (argv[0][0] == '-') {
  10874. if (argv[0][1] == '\0') { /* "-" */
  10875. /* new_cmd remains NULL: "reset these sigs" */
  10876. goto reset_traps;
  10877. }
  10878. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10879. argv++;
  10880. }
  10881. /* else: "-something", no special meaning */
  10882. }
  10883. new_cmd = *argv;
  10884. reset_traps:
  10885. argv++;
  10886. goto process_sig_list;
  10887. }
  10888. #endif
  10889. #if ENABLE_HUSH_JOB
  10890. static struct pipe *parse_jobspec(const char *str)
  10891. {
  10892. struct pipe *pi;
  10893. unsigned jobnum;
  10894. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10895. if (str[0] != '%'
  10896. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10897. ) {
  10898. bb_error_msg("bad argument '%s'", str);
  10899. return NULL;
  10900. }
  10901. /* It is "%%", "%+" or "%" - current job */
  10902. jobnum = G.last_jobid;
  10903. if (jobnum == 0) {
  10904. bb_simple_error_msg("no current job");
  10905. return NULL;
  10906. }
  10907. }
  10908. for (pi = G.job_list; pi; pi = pi->next) {
  10909. if (pi->jobid == jobnum) {
  10910. return pi;
  10911. }
  10912. }
  10913. bb_error_msg("%u: no such job", jobnum);
  10914. return NULL;
  10915. }
  10916. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10917. {
  10918. struct pipe *job;
  10919. const char *status_string;
  10920. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10921. for (job = G.job_list; job; job = job->next) {
  10922. if (job->alive_cmds == job->stopped_cmds)
  10923. status_string = "Stopped";
  10924. else
  10925. status_string = "Running";
  10926. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10927. }
  10928. clean_up_last_dead_job();
  10929. return EXIT_SUCCESS;
  10930. }
  10931. /* built-in 'fg' and 'bg' handler */
  10932. static int FAST_FUNC builtin_fg_bg(char **argv)
  10933. {
  10934. int i;
  10935. struct pipe *pi;
  10936. if (!G_interactive_fd)
  10937. return EXIT_FAILURE;
  10938. /* If they gave us no args, assume they want the last backgrounded task */
  10939. if (!argv[1]) {
  10940. for (pi = G.job_list; pi; pi = pi->next) {
  10941. if (pi->jobid == G.last_jobid) {
  10942. goto found;
  10943. }
  10944. }
  10945. bb_error_msg("%s: no current job", argv[0]);
  10946. return EXIT_FAILURE;
  10947. }
  10948. pi = parse_jobspec(argv[1]);
  10949. if (!pi)
  10950. return EXIT_FAILURE;
  10951. found:
  10952. /* TODO: bash prints a string representation
  10953. * of job being foregrounded (like "sleep 1 | cat") */
  10954. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10955. /* Put the job into the foreground. */
  10956. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10957. }
  10958. /* Restart the processes in the job */
  10959. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10960. for (i = 0; i < pi->num_cmds; i++) {
  10961. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10962. }
  10963. pi->stopped_cmds = 0;
  10964. i = kill(- pi->pgrp, SIGCONT);
  10965. if (i < 0) {
  10966. if (errno == ESRCH) {
  10967. delete_finished_job(pi);
  10968. return EXIT_SUCCESS;
  10969. }
  10970. bb_simple_perror_msg("kill (SIGCONT)");
  10971. }
  10972. if (argv[0][0] == 'f') {
  10973. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10974. return checkjobs_and_fg_shell(pi);
  10975. }
  10976. return EXIT_SUCCESS;
  10977. }
  10978. #endif
  10979. #if ENABLE_HUSH_KILL
  10980. static int FAST_FUNC builtin_kill(char **argv)
  10981. {
  10982. int ret = 0;
  10983. # if ENABLE_HUSH_JOB
  10984. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10985. int i = 1;
  10986. do {
  10987. struct pipe *pi;
  10988. char *dst;
  10989. int j, n;
  10990. if (argv[i][0] != '%')
  10991. continue;
  10992. /*
  10993. * "kill %N" - job kill
  10994. * Converting to pgrp / pid kill
  10995. */
  10996. pi = parse_jobspec(argv[i]);
  10997. if (!pi) {
  10998. /* Eat bad jobspec */
  10999. j = i;
  11000. do {
  11001. j++;
  11002. argv[j - 1] = argv[j];
  11003. } while (argv[j]);
  11004. ret = 1;
  11005. i--;
  11006. continue;
  11007. }
  11008. /*
  11009. * In jobs started under job control, we signal
  11010. * entire process group by kill -PGRP_ID.
  11011. * This happens, f.e., in interactive shell.
  11012. *
  11013. * Otherwise, we signal each child via
  11014. * kill PID1 PID2 PID3.
  11015. * Testcases:
  11016. * sh -c 'sleep 1|sleep 1 & kill %1'
  11017. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  11018. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  11019. */
  11020. n = G_interactive_fd ? 1 : pi->num_cmds;
  11021. dst = alloca(n * sizeof(int)*4);
  11022. argv[i] = dst;
  11023. if (G_interactive_fd)
  11024. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  11025. else for (j = 0; j < n; j++) {
  11026. struct command *cmd = &pi->cmds[j];
  11027. /* Skip exited members of the job */
  11028. if (cmd->pid == 0)
  11029. continue;
  11030. /*
  11031. * kill_main has matching code to expect
  11032. * leading space. Needed to not confuse
  11033. * negative pids with "kill -SIGNAL_NO" syntax
  11034. */
  11035. dst += sprintf(dst, " %u", (int)cmd->pid);
  11036. }
  11037. *dst = '\0';
  11038. } while (argv[++i]);
  11039. }
  11040. # endif
  11041. if (argv[1] || ret == 0) {
  11042. ret = run_applet_main(argv, kill_main);
  11043. }
  11044. /* else: ret = 1, "kill %bad_jobspec" case */
  11045. return ret;
  11046. }
  11047. #endif
  11048. #if ENABLE_HUSH_WAIT
  11049. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11050. # if !ENABLE_HUSH_JOB
  11051. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11052. # endif
  11053. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11054. {
  11055. int ret = 0;
  11056. for (;;) {
  11057. int sig;
  11058. sigset_t oldset;
  11059. if (!sigisemptyset(&G.pending_set))
  11060. goto check_sig;
  11061. /* waitpid is not interruptible by SA_RESTARTed
  11062. * signals which we use. Thus, this ugly dance:
  11063. */
  11064. /* Make sure possible SIGCHLD is stored in kernel's
  11065. * pending signal mask before we call waitpid.
  11066. * Or else we may race with SIGCHLD, lose it,
  11067. * and get stuck in sigsuspend...
  11068. */
  11069. sigfillset(&oldset); /* block all signals, remember old set */
  11070. sigprocmask2(SIG_SETMASK, &oldset);
  11071. if (!sigisemptyset(&G.pending_set)) {
  11072. /* Crap! we raced with some signal! */
  11073. goto restore;
  11074. }
  11075. /*errno = 0; - checkjobs does this */
  11076. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11077. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11078. debug_printf_exec("checkjobs:%d\n", ret);
  11079. # if ENABLE_HUSH_JOB
  11080. if (waitfor_pipe) {
  11081. int rcode = job_exited_or_stopped(waitfor_pipe);
  11082. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11083. if (rcode >= 0) {
  11084. ret = rcode;
  11085. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11086. break;
  11087. }
  11088. }
  11089. # endif
  11090. /* if ECHILD, there are no children (ret is -1 or 0) */
  11091. /* if ret == 0, no children changed state */
  11092. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11093. if (errno == ECHILD || ret) {
  11094. ret--;
  11095. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11096. ret = 0;
  11097. # if ENABLE_HUSH_BASH_COMPAT
  11098. if (waitfor_pid == -1 && errno == ECHILD) {
  11099. /* exitcode of "wait -n" with no children is 127, not 0 */
  11100. ret = 127;
  11101. }
  11102. # endif
  11103. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11104. break;
  11105. }
  11106. /* Wait for SIGCHLD or any other signal */
  11107. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11108. /* Note: sigsuspend invokes signal handler */
  11109. sigsuspend(&oldset);
  11110. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11111. * to make sure SIGCHLD is not masked off?
  11112. * It was reported that this:
  11113. * fn() { : | return; }
  11114. * shopt -s lastpipe
  11115. * fn
  11116. * exec hush SCRIPT
  11117. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11118. * making "wait" commands in SCRIPT block forever.
  11119. */
  11120. restore:
  11121. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11122. check_sig:
  11123. /* So, did we get a signal? */
  11124. sig = check_and_run_traps();
  11125. if (sig /*&& sig != SIGCHLD - always true */) {
  11126. /* Do this for any (non-ignored) signal, not only for ^C */
  11127. ret = 128 | sig;
  11128. break;
  11129. }
  11130. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11131. }
  11132. return ret;
  11133. }
  11134. static int FAST_FUNC builtin_wait(char **argv)
  11135. {
  11136. int ret;
  11137. int status;
  11138. argv = skip_dash_dash(argv);
  11139. # if ENABLE_HUSH_BASH_COMPAT
  11140. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11141. /* wait -n */
  11142. /* (bash accepts "wait -n PID" too and ignores PID) */
  11143. G.dead_job_exitcode = -1;
  11144. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11145. }
  11146. # endif
  11147. if (argv[0] == NULL) {
  11148. /* Don't care about wait results */
  11149. /* Note 1: must wait until there are no more children */
  11150. /* Note 2: must be interruptible */
  11151. /* Examples:
  11152. * $ sleep 3 & sleep 6 & wait
  11153. * [1] 30934 sleep 3
  11154. * [2] 30935 sleep 6
  11155. * [1] Done sleep 3
  11156. * [2] Done sleep 6
  11157. * $ sleep 3 & sleep 6 & wait
  11158. * [1] 30936 sleep 3
  11159. * [2] 30937 sleep 6
  11160. * [1] Done sleep 3
  11161. * ^C <-- after ~4 sec from keyboard
  11162. * $
  11163. */
  11164. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11165. }
  11166. do {
  11167. pid_t pid = bb_strtou(*argv, NULL, 10);
  11168. if (errno || pid <= 0) {
  11169. # if ENABLE_HUSH_JOB
  11170. if (argv[0][0] == '%') {
  11171. struct pipe *wait_pipe;
  11172. ret = 127; /* bash compat for bad jobspecs */
  11173. wait_pipe = parse_jobspec(*argv);
  11174. if (wait_pipe) {
  11175. ret = job_exited_or_stopped(wait_pipe);
  11176. if (ret < 0) {
  11177. ret = wait_for_child_or_signal(wait_pipe, 0);
  11178. } else {
  11179. /* waiting on "last dead job" removes it */
  11180. clean_up_last_dead_job();
  11181. }
  11182. }
  11183. /* else: parse_jobspec() already emitted error msg */
  11184. continue;
  11185. }
  11186. # endif
  11187. /* mimic bash message */
  11188. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11189. ret = EXIT_FAILURE;
  11190. continue; /* bash checks all argv[] */
  11191. }
  11192. /* Do we have such child? */
  11193. ret = waitpid(pid, &status, WNOHANG);
  11194. if (ret < 0) {
  11195. /* No */
  11196. ret = 127;
  11197. if (errno == ECHILD) {
  11198. if (pid == G.last_bg_pid) {
  11199. /* "wait $!" but last bg task has already exited. Try:
  11200. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11201. * In bash it prints exitcode 0, then 3.
  11202. * In dash, it is 127.
  11203. */
  11204. ret = G.last_bg_pid_exitcode;
  11205. } else {
  11206. /* Example: "wait 1". mimic bash message */
  11207. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11208. }
  11209. } else {
  11210. /* ??? */
  11211. bb_perror_msg("wait %s", *argv);
  11212. }
  11213. continue; /* bash checks all argv[] */
  11214. }
  11215. if (ret == 0) {
  11216. /* Yes, and it still runs */
  11217. ret = wait_for_child_or_signal(NULL, pid);
  11218. } else {
  11219. /* Yes, and it just exited */
  11220. process_wait_result(NULL, pid, status);
  11221. ret = WEXITSTATUS(status);
  11222. if (WIFSIGNALED(status))
  11223. ret = 128 | WTERMSIG(status);
  11224. }
  11225. } while (*++argv);
  11226. return ret;
  11227. }
  11228. #endif
  11229. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11230. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11231. {
  11232. if (argv[1]) {
  11233. def = bb_strtou(argv[1], NULL, 10);
  11234. if (errno || def < def_min || argv[2]) {
  11235. bb_error_msg("%s: bad arguments", argv[0]);
  11236. def = UINT_MAX;
  11237. }
  11238. }
  11239. return def;
  11240. }
  11241. #endif
  11242. #if ENABLE_HUSH_LOOPS
  11243. static int FAST_FUNC builtin_break(char **argv)
  11244. {
  11245. unsigned depth;
  11246. if (G.depth_of_loop == 0) {
  11247. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11248. /* if we came from builtin_continue(), need to undo "= 1" */
  11249. G.flag_break_continue = 0;
  11250. return EXIT_SUCCESS; /* bash compat */
  11251. }
  11252. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11253. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11254. if (depth == UINT_MAX)
  11255. G.flag_break_continue = BC_BREAK;
  11256. if (G.depth_of_loop < depth)
  11257. G.depth_break_continue = G.depth_of_loop;
  11258. return EXIT_SUCCESS;
  11259. }
  11260. static int FAST_FUNC builtin_continue(char **argv)
  11261. {
  11262. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11263. return builtin_break(argv);
  11264. }
  11265. #endif
  11266. #if ENABLE_HUSH_FUNCTIONS
  11267. static int FAST_FUNC builtin_return(char **argv)
  11268. {
  11269. int rc;
  11270. if (G_flag_return_in_progress != -1) {
  11271. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11272. return EXIT_FAILURE; /* bash compat */
  11273. }
  11274. G_flag_return_in_progress = 1;
  11275. /* bash:
  11276. * out of range: wraps around at 256, does not error out
  11277. * non-numeric param:
  11278. * f() { false; return qwe; }; f; echo $?
  11279. * bash: return: qwe: numeric argument required <== we do this
  11280. * 255 <== we also do this
  11281. */
  11282. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11283. # if ENABLE_HUSH_TRAP
  11284. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11285. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11286. G.return_exitcode = rc;
  11287. }
  11288. # endif
  11289. return rc;
  11290. }
  11291. #endif
  11292. #if ENABLE_HUSH_TIMES
  11293. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11294. {
  11295. static const uint8_t times_tbl[] ALIGN1 = {
  11296. ' ', offsetof(struct tms, tms_utime),
  11297. '\n', offsetof(struct tms, tms_stime),
  11298. ' ', offsetof(struct tms, tms_cutime),
  11299. '\n', offsetof(struct tms, tms_cstime),
  11300. 0
  11301. };
  11302. const uint8_t *p;
  11303. unsigned clk_tck;
  11304. struct tms buf;
  11305. clk_tck = bb_clk_tck();
  11306. times(&buf);
  11307. p = times_tbl;
  11308. do {
  11309. unsigned sec, frac;
  11310. unsigned long t;
  11311. t = *(clock_t *)(((char *) &buf) + p[1]);
  11312. sec = t / clk_tck;
  11313. frac = t % clk_tck;
  11314. printf("%um%u.%03us%c",
  11315. sec / 60, sec % 60,
  11316. (frac * 1000) / clk_tck,
  11317. p[0]);
  11318. p += 2;
  11319. } while (*p);
  11320. return EXIT_SUCCESS;
  11321. }
  11322. #endif
  11323. #if ENABLE_HUSH_MEMLEAK
  11324. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11325. {
  11326. void *p;
  11327. unsigned long l;
  11328. # ifdef M_TRIM_THRESHOLD
  11329. /* Optional. Reduces probability of false positives */
  11330. malloc_trim(0);
  11331. # endif
  11332. /* Crude attempt to find where "free memory" starts,
  11333. * sans fragmentation. */
  11334. p = malloc(240);
  11335. l = (unsigned long)p;
  11336. free(p);
  11337. p = malloc(3400);
  11338. if (l < (unsigned long)p) l = (unsigned long)p;
  11339. free(p);
  11340. # if 0 /* debug */
  11341. {
  11342. struct mallinfo mi = mallinfo();
  11343. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11344. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11345. }
  11346. # endif
  11347. if (!G.memleak_value)
  11348. G.memleak_value = l;
  11349. l -= G.memleak_value;
  11350. if ((long)l < 0)
  11351. l = 0;
  11352. l /= 1024;
  11353. if (l > 127)
  11354. l = 127;
  11355. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11356. return l;
  11357. }
  11358. #endif