hush.c 343 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380
  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 (70 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[] ALIGN_PTR = {
  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. /* set by signal handler if SIGINT is received _and_ its trap is not set */
  879. smallint flag_SIGINT;
  880. #if ENABLE_HUSH_LOOPS
  881. smallint flag_break_continue;
  882. #endif
  883. #if ENABLE_HUSH_FUNCTIONS
  884. /* 0: outside of a function (or sourced file)
  885. * -1: inside of a function, ok to use return builtin
  886. * 1: return is invoked, skip all till end of func
  887. */
  888. smallint flag_return_in_progress;
  889. # define G_flag_return_in_progress (G.flag_return_in_progress)
  890. #else
  891. # define G_flag_return_in_progress 0
  892. #endif
  893. smallint exiting; /* used to prevent EXIT trap recursion */
  894. /* These support $? */
  895. smalluint last_exitcode;
  896. smalluint expand_exitcode;
  897. smalluint last_bg_pid_exitcode;
  898. #if ENABLE_HUSH_SET
  899. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  900. smalluint global_args_malloced;
  901. # define G_global_args_malloced (G.global_args_malloced)
  902. #else
  903. # define G_global_args_malloced 0
  904. #endif
  905. #if ENABLE_HUSH_BASH_COMPAT
  906. int dead_job_exitcode; /* for "wait -n" */
  907. #endif
  908. /* how many non-NULL argv's we have. NB: $# + 1 */
  909. int global_argc;
  910. char **global_argv;
  911. #if !BB_MMU
  912. char *argv0_for_re_execing;
  913. #endif
  914. #if ENABLE_HUSH_LOOPS
  915. unsigned depth_break_continue;
  916. unsigned depth_of_loop;
  917. #endif
  918. #if ENABLE_HUSH_GETOPTS
  919. unsigned getopt_count;
  920. #endif
  921. const char *ifs;
  922. char *ifs_whitespace; /* = G.ifs or malloced */
  923. const char *cwd;
  924. struct variable *top_var;
  925. char **expanded_assignments;
  926. struct variable **shadowed_vars_pp;
  927. unsigned var_nest_level;
  928. #if ENABLE_HUSH_FUNCTIONS
  929. # if ENABLE_HUSH_LOCAL
  930. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  931. # endif
  932. struct function *top_func;
  933. #endif
  934. /* Signal and trap handling */
  935. #if ENABLE_HUSH_FAST
  936. unsigned count_SIGCHLD;
  937. unsigned handled_SIGCHLD;
  938. smallint we_have_children;
  939. #endif
  940. #if ENABLE_HUSH_LINENO_VAR
  941. unsigned parse_lineno;
  942. unsigned execute_lineno;
  943. #endif
  944. HFILE *HFILE_list;
  945. HFILE *HFILE_stdin;
  946. /* Which signals have non-DFL handler (even with no traps set)?
  947. * Set at the start to:
  948. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  949. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  950. * The rest is cleared right before execv syscalls.
  951. * Other than these two times, never modified.
  952. */
  953. unsigned special_sig_mask;
  954. #if ENABLE_HUSH_JOB
  955. unsigned fatal_sig_mask;
  956. # define G_fatal_sig_mask (G.fatal_sig_mask)
  957. #else
  958. # define G_fatal_sig_mask 0
  959. #endif
  960. #if ENABLE_HUSH_TRAP
  961. int pre_trap_exitcode;
  962. # if ENABLE_HUSH_FUNCTIONS
  963. int return_exitcode;
  964. # endif
  965. char **traps; /* char *traps[NSIG] */
  966. # define G_traps G.traps
  967. #else
  968. # define G_traps ((char**)NULL)
  969. #endif
  970. sigset_t pending_set;
  971. #if ENABLE_HUSH_MEMLEAK
  972. unsigned long memleak_value;
  973. #endif
  974. #if ENABLE_HUSH_MODE_X
  975. unsigned x_mode_depth;
  976. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  977. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  978. * for all subsequent output.
  979. */
  980. int x_mode_fd;
  981. o_string x_mode_buf;
  982. #endif
  983. #if HUSH_DEBUG >= 2
  984. int debug_indent;
  985. #endif
  986. #if ENABLE_HUSH_TEST || BASH_TEST2
  987. /* Cached supplementary group array (for testing executable'ity of files) */
  988. struct cached_groupinfo groupinfo;
  989. # define GROUPINFO_INIT { G.groupinfo.euid = -1; G.groupinfo.egid = -1; }
  990. #else
  991. # define GROUPINFO_INIT /* nothing */
  992. #endif
  993. struct sigaction sa;
  994. char optstring_buf[sizeof("eixcs")];
  995. #if BASH_EPOCH_VARS
  996. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  997. #endif
  998. #if ENABLE_FEATURE_EDITING
  999. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  1000. #endif
  1001. };
  1002. #define G (*ptr_to_globals)
  1003. /* Not #defining name to G.name - this quickly gets unwieldy
  1004. * (too many defines). Also, I actually prefer to see when a variable
  1005. * is global, thus "G." prefix is a useful hint */
  1006. #define INIT_G() do { \
  1007. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1008. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1009. sigfillset(&G.sa.sa_mask); \
  1010. G.sa.sa_flags = SA_RESTART; \
  1011. GROUPINFO_INIT; \
  1012. } while (0)
  1013. /* Function prototypes for builtins */
  1014. static int builtin_cd(char **argv) FAST_FUNC;
  1015. #if ENABLE_HUSH_ECHO
  1016. static int builtin_echo(char **argv) FAST_FUNC;
  1017. #endif
  1018. static int builtin_eval(char **argv) FAST_FUNC;
  1019. static int builtin_exec(char **argv) FAST_FUNC;
  1020. static int builtin_exit(char **argv) FAST_FUNC;
  1021. #if ENABLE_HUSH_EXPORT
  1022. static int builtin_export(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_READONLY
  1025. static int builtin_readonly(char **argv) FAST_FUNC;
  1026. #endif
  1027. static int builtin_false(char **argv) FAST_FUNC;
  1028. #if ENABLE_HUSH_JOB
  1029. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1030. static int builtin_jobs(char **argv) FAST_FUNC;
  1031. #endif
  1032. #if ENABLE_HUSH_GETOPTS
  1033. static int builtin_getopts(char **argv) FAST_FUNC;
  1034. #endif
  1035. #if ENABLE_HUSH_HELP
  1036. static int builtin_help(char **argv) FAST_FUNC;
  1037. #endif
  1038. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1039. static int builtin_history(char **argv) FAST_FUNC;
  1040. #endif
  1041. #if ENABLE_HUSH_LOCAL
  1042. static int builtin_local(char **argv) FAST_FUNC;
  1043. #endif
  1044. #if ENABLE_HUSH_MEMLEAK
  1045. static int builtin_memleak(char **argv) FAST_FUNC;
  1046. #endif
  1047. #if ENABLE_HUSH_PRINTF
  1048. static int builtin_printf(char **argv) FAST_FUNC;
  1049. #endif
  1050. static int builtin_pwd(char **argv) FAST_FUNC;
  1051. #if ENABLE_HUSH_READ
  1052. static int builtin_read(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_SET
  1055. static int builtin_set(char **argv) FAST_FUNC;
  1056. #endif
  1057. static int builtin_shift(char **argv) FAST_FUNC;
  1058. static int builtin_source(char **argv) FAST_FUNC;
  1059. #if ENABLE_HUSH_TEST || BASH_TEST2
  1060. static int builtin_test(char **argv) FAST_FUNC;
  1061. #endif
  1062. #if ENABLE_HUSH_TRAP
  1063. static int builtin_trap(char **argv) FAST_FUNC;
  1064. #endif
  1065. #if ENABLE_HUSH_TYPE
  1066. static int builtin_type(char **argv) FAST_FUNC;
  1067. #endif
  1068. #if ENABLE_HUSH_TIMES
  1069. static int builtin_times(char **argv) FAST_FUNC;
  1070. #endif
  1071. static int builtin_true(char **argv) FAST_FUNC;
  1072. #if ENABLE_HUSH_UMASK
  1073. static int builtin_umask(char **argv) FAST_FUNC;
  1074. #endif
  1075. #if ENABLE_HUSH_UNSET
  1076. static int builtin_unset(char **argv) FAST_FUNC;
  1077. #endif
  1078. #if ENABLE_HUSH_KILL
  1079. static int builtin_kill(char **argv) FAST_FUNC;
  1080. #endif
  1081. #if ENABLE_HUSH_WAIT
  1082. static int builtin_wait(char **argv) FAST_FUNC;
  1083. #endif
  1084. #if ENABLE_HUSH_LOOPS
  1085. static int builtin_break(char **argv) FAST_FUNC;
  1086. static int builtin_continue(char **argv) FAST_FUNC;
  1087. #endif
  1088. #if ENABLE_HUSH_FUNCTIONS
  1089. static int builtin_return(char **argv) FAST_FUNC;
  1090. #endif
  1091. /* Table of built-in functions. They can be forked or not, depending on
  1092. * context: within pipes, they fork. As simple commands, they do not.
  1093. * When used in non-forking context, they can change global variables
  1094. * in the parent shell process. If forked, of course they cannot.
  1095. * For example, 'unset foo | whatever' will parse and run, but foo will
  1096. * still be set at the end. */
  1097. struct built_in_command {
  1098. const char *b_cmd;
  1099. int (*b_function)(char **argv) FAST_FUNC;
  1100. #if ENABLE_HUSH_HELP
  1101. const char *b_descr;
  1102. # define BLTIN(cmd, func, help) { cmd, func, help }
  1103. #else
  1104. # define BLTIN(cmd, func, help) { cmd, func }
  1105. #endif
  1106. };
  1107. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1108. BLTIN("." , builtin_source , "Run commands in file"),
  1109. BLTIN(":" , builtin_true , NULL),
  1110. #if ENABLE_HUSH_JOB
  1111. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1112. #endif
  1113. #if ENABLE_HUSH_LOOPS
  1114. BLTIN("break" , builtin_break , "Exit loop"),
  1115. #endif
  1116. BLTIN("cd" , builtin_cd , "Change directory"),
  1117. #if ENABLE_HUSH_LOOPS
  1118. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1119. #endif
  1120. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1121. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1122. BLTIN("exit" , builtin_exit , NULL),
  1123. #if ENABLE_HUSH_EXPORT
  1124. BLTIN("export" , builtin_export , "Set environment variables"),
  1125. #endif
  1126. BLTIN("false" , builtin_false , NULL),
  1127. #if ENABLE_HUSH_JOB
  1128. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1129. #endif
  1130. #if ENABLE_HUSH_GETOPTS
  1131. BLTIN("getopts" , builtin_getopts , NULL),
  1132. #endif
  1133. #if ENABLE_HUSH_HELP
  1134. BLTIN("help" , builtin_help , NULL),
  1135. #endif
  1136. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1137. BLTIN("history" , builtin_history , "Show history"),
  1138. #endif
  1139. #if ENABLE_HUSH_JOB
  1140. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1141. #endif
  1142. #if ENABLE_HUSH_KILL
  1143. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1144. #endif
  1145. #if ENABLE_HUSH_LOCAL
  1146. BLTIN("local" , builtin_local , "Set local variables"),
  1147. #endif
  1148. #if ENABLE_HUSH_MEMLEAK
  1149. BLTIN("memleak" , builtin_memleak , NULL),
  1150. #endif
  1151. #if ENABLE_HUSH_READ
  1152. BLTIN("read" , builtin_read , "Input into variable"),
  1153. #endif
  1154. #if ENABLE_HUSH_READONLY
  1155. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1156. #endif
  1157. #if ENABLE_HUSH_FUNCTIONS
  1158. BLTIN("return" , builtin_return , "Return from function"),
  1159. #endif
  1160. #if ENABLE_HUSH_SET
  1161. BLTIN("set" , builtin_set , "Set positional parameters"),
  1162. #endif
  1163. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1164. #if BASH_SOURCE
  1165. BLTIN("source" , builtin_source , NULL),
  1166. #endif
  1167. #if ENABLE_HUSH_TIMES
  1168. BLTIN("times" , builtin_times , NULL),
  1169. #endif
  1170. #if ENABLE_HUSH_TRAP
  1171. BLTIN("trap" , builtin_trap , "Trap signals"),
  1172. #endif
  1173. BLTIN("true" , builtin_true , NULL),
  1174. #if ENABLE_HUSH_TYPE
  1175. BLTIN("type" , builtin_type , "Show command type"),
  1176. #endif
  1177. #if ENABLE_HUSH_ULIMIT
  1178. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1179. #endif
  1180. #if ENABLE_HUSH_UMASK
  1181. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1182. #endif
  1183. #if ENABLE_HUSH_UNSET
  1184. BLTIN("unset" , builtin_unset , "Unset variables"),
  1185. #endif
  1186. #if ENABLE_HUSH_WAIT
  1187. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1188. #endif
  1189. };
  1190. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1191. * (it's cheaper to run an external program in this case):
  1192. */
  1193. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1194. #if ENABLE_HUSH_TEST
  1195. BLTIN("[" , builtin_test , NULL),
  1196. #endif
  1197. #if BASH_TEST2
  1198. BLTIN("[[" , builtin_test , NULL),
  1199. #endif
  1200. #if ENABLE_HUSH_ECHO
  1201. BLTIN("echo" , builtin_echo , NULL),
  1202. #endif
  1203. #if ENABLE_HUSH_PRINTF
  1204. BLTIN("printf" , builtin_printf , NULL),
  1205. #endif
  1206. BLTIN("pwd" , builtin_pwd , NULL),
  1207. #if ENABLE_HUSH_TEST
  1208. BLTIN("test" , builtin_test , NULL),
  1209. #endif
  1210. };
  1211. /*
  1212. * Debug printouts.
  1213. */
  1214. #if HUSH_DEBUG >= 2
  1215. /* prevent disasters with G.debug_indent < 0 */
  1216. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1217. # define debug_enter() (G.debug_indent++)
  1218. # define debug_leave() (G.debug_indent--)
  1219. #else
  1220. # define indent() ((void)0)
  1221. # define debug_enter() ((void)0)
  1222. # define debug_leave() ((void)0)
  1223. #endif
  1224. #ifndef debug_printf
  1225. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. #endif
  1227. #ifndef debug_printf_parse
  1228. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. #endif
  1230. #ifndef debug_printf_heredoc
  1231. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1232. #endif
  1233. #ifndef debug_printf_exec
  1234. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1235. #endif
  1236. #ifndef debug_printf_env
  1237. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1238. #endif
  1239. #ifndef debug_printf_jobs
  1240. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1241. # define DEBUG_JOBS 1
  1242. #else
  1243. # define DEBUG_JOBS 0
  1244. #endif
  1245. #ifndef debug_printf_expand
  1246. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1247. # define DEBUG_EXPAND 1
  1248. #else
  1249. # define DEBUG_EXPAND 0
  1250. #endif
  1251. #ifndef debug_printf_varexp
  1252. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1253. #endif
  1254. #ifndef debug_printf_glob
  1255. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1256. # define DEBUG_GLOB 1
  1257. #else
  1258. # define DEBUG_GLOB 0
  1259. #endif
  1260. #ifndef debug_printf_redir
  1261. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1262. #endif
  1263. #ifndef debug_printf_list
  1264. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1265. #endif
  1266. #ifndef debug_printf_subst
  1267. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1268. #endif
  1269. #ifndef debug_printf_prompt
  1270. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1271. #endif
  1272. #ifndef debug_printf_clean
  1273. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1274. # define DEBUG_CLEAN 1
  1275. #else
  1276. # define DEBUG_CLEAN 0
  1277. #endif
  1278. #if DEBUG_EXPAND
  1279. static void debug_print_strings(const char *prefix, char **vv)
  1280. {
  1281. indent();
  1282. fdprintf(2, "%s:\n", prefix);
  1283. while (*vv)
  1284. fdprintf(2, " '%s'\n", *vv++);
  1285. }
  1286. #else
  1287. # define debug_print_strings(prefix, vv) ((void)0)
  1288. #endif
  1289. /*
  1290. * Leak hunting. Use hush_leaktool.sh for post-processing.
  1291. */
  1292. #if LEAK_HUNTING
  1293. static void *xxmalloc(int lineno, size_t size)
  1294. {
  1295. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1296. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1297. return ptr;
  1298. }
  1299. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1300. {
  1301. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1302. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1303. return ptr;
  1304. }
  1305. static char *xxstrdup(int lineno, const char *str)
  1306. {
  1307. char *ptr = xstrdup(str);
  1308. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1309. return ptr;
  1310. }
  1311. static void xxfree(void *ptr)
  1312. {
  1313. fdprintf(2, "free %p\n", ptr);
  1314. free(ptr);
  1315. }
  1316. # define xmalloc(s) xxmalloc(__LINE__, s)
  1317. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1318. # define xstrdup(s) xxstrdup(__LINE__, s)
  1319. # define free(p) xxfree(p)
  1320. #endif
  1321. /*
  1322. * Syntax and runtime errors. They always abort scripts.
  1323. * In interactive use they usually discard unparsed and/or unexecuted commands
  1324. * and return to the prompt.
  1325. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1326. */
  1327. #if HUSH_DEBUG < 2
  1328. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1329. # define syntax_error(lineno, msg) syntax_error(msg)
  1330. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1331. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1332. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1333. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1334. #endif
  1335. static void die_if_script(void)
  1336. {
  1337. if (!G_interactive_fd) {
  1338. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1339. xfunc_error_retval = G.last_exitcode;
  1340. xfunc_die();
  1341. }
  1342. }
  1343. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1344. {
  1345. va_list p;
  1346. #if HUSH_DEBUG >= 2
  1347. bb_error_msg("hush.c:%u", lineno);
  1348. #endif
  1349. va_start(p, fmt);
  1350. bb_verror_msg(fmt, p, NULL);
  1351. va_end(p);
  1352. die_if_script();
  1353. }
  1354. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1355. {
  1356. if (msg)
  1357. bb_error_msg("syntax error: %s", msg);
  1358. else
  1359. bb_simple_error_msg("syntax error");
  1360. die_if_script();
  1361. }
  1362. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1363. {
  1364. bb_error_msg("syntax error at '%s'", msg);
  1365. die_if_script();
  1366. }
  1367. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1368. {
  1369. bb_error_msg("syntax error: unterminated %s", s);
  1370. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1371. // (but bash --posix, or if bash is run as "sh", does terminate in script, so maybe uncomment this?)
  1372. // die_if_script();
  1373. }
  1374. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1375. {
  1376. char msg[2] = { ch, '\0' };
  1377. syntax_error_unterm_str(lineno, msg);
  1378. }
  1379. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1380. {
  1381. char msg[2];
  1382. msg[0] = ch;
  1383. msg[1] = '\0';
  1384. #if HUSH_DEBUG >= 2
  1385. bb_error_msg("hush.c:%u", lineno);
  1386. #endif
  1387. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1388. die_if_script();
  1389. }
  1390. #if HUSH_DEBUG < 2
  1391. # undef msg_and_die_if_script
  1392. # undef syntax_error
  1393. # undef syntax_error_at
  1394. # undef syntax_error_unterm_ch
  1395. # undef syntax_error_unterm_str
  1396. # undef syntax_error_unexpected_ch
  1397. #else
  1398. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1399. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1400. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1401. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1402. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1403. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1404. #endif
  1405. /*
  1406. * Utility functions
  1407. */
  1408. /* Replace each \x with x in place, return ptr past NUL. */
  1409. static char *unbackslash(char *src)
  1410. {
  1411. char *dst = src = strchrnul(src, '\\');
  1412. while (1) {
  1413. if (*src == '\\') {
  1414. src++;
  1415. if (*src != '\0') {
  1416. /* \x -> x */
  1417. *dst++ = *src++;
  1418. continue;
  1419. }
  1420. /* else: "\<nul>". Do not delete this backslash.
  1421. * Testcase: eval 'echo ok\'
  1422. */
  1423. *dst++ = '\\';
  1424. /* fallthrough */
  1425. }
  1426. if ((*dst++ = *src++) == '\0')
  1427. break;
  1428. }
  1429. return dst;
  1430. }
  1431. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1432. {
  1433. int i;
  1434. unsigned count1;
  1435. unsigned count2;
  1436. char **v;
  1437. v = strings;
  1438. count1 = 0;
  1439. if (v) {
  1440. while (*v) {
  1441. count1++;
  1442. v++;
  1443. }
  1444. }
  1445. count2 = 0;
  1446. v = add;
  1447. while (*v) {
  1448. count2++;
  1449. v++;
  1450. }
  1451. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1452. v[count1 + count2] = NULL;
  1453. i = count2;
  1454. while (--i >= 0)
  1455. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1456. return v;
  1457. }
  1458. #if LEAK_HUNTING
  1459. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1460. {
  1461. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1462. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1463. return ptr;
  1464. }
  1465. #define add_strings_to_strings(strings, add, need_to_dup) \
  1466. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1467. #endif
  1468. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1469. static char **add_string_to_strings(char **strings, char *add)
  1470. {
  1471. char *v[2];
  1472. v[0] = add;
  1473. v[1] = NULL;
  1474. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1475. }
  1476. #if LEAK_HUNTING
  1477. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1478. {
  1479. char **ptr = add_string_to_strings(strings, add);
  1480. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1481. return ptr;
  1482. }
  1483. #define add_string_to_strings(strings, add) \
  1484. xx_add_string_to_strings(__LINE__, strings, add)
  1485. #endif
  1486. static void free_strings(char **strings)
  1487. {
  1488. char **v;
  1489. if (!strings)
  1490. return;
  1491. v = strings;
  1492. while (*v) {
  1493. free(*v);
  1494. v++;
  1495. }
  1496. free(strings);
  1497. }
  1498. static int dup_CLOEXEC(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 (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1505. close_on_exec_on(newfd);
  1506. } else { /* newfd < 0 */
  1507. if (errno == EBUSY)
  1508. goto repeat;
  1509. if (errno == EINTR)
  1510. goto repeat;
  1511. if (errno != EBADF) {
  1512. /* "echo >&9999" gets EINVAL trying to save fd 1 to above 9999.
  1513. * We could try saving it _below_ 9999 instead (how?), but
  1514. * this probably means that dup2(9999,1) to effectuate >&9999
  1515. * would also not work: fd 9999 can't exist.
  1516. * (This differs from "echo >&99" where saving works, but
  1517. * subsequent dup2(99,1) fails if fd 99 is not open).
  1518. */
  1519. bb_perror_msg("fcntl(%d,F_DUPFD,%d)", fd, avoid_fd + 1);
  1520. }
  1521. }
  1522. return newfd;
  1523. }
  1524. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1525. {
  1526. int newfd;
  1527. repeat:
  1528. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1529. if (newfd < 0) {
  1530. if (errno == EBUSY)
  1531. goto repeat;
  1532. if (errno == EINTR)
  1533. goto repeat;
  1534. /* fd was not open? */
  1535. if (errno == EBADF)
  1536. return fd;
  1537. xfunc_die();
  1538. }
  1539. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1540. close_on_exec_on(newfd);
  1541. close(fd);
  1542. return newfd;
  1543. }
  1544. /*
  1545. * Manipulating HFILEs
  1546. */
  1547. static HFILE *hfopen(const char *name)
  1548. {
  1549. HFILE *fp;
  1550. int fd;
  1551. fd = STDIN_FILENO;
  1552. if (name) {
  1553. fd = open(name, O_RDONLY | O_CLOEXEC);
  1554. if (fd < 0)
  1555. return NULL;
  1556. if (O_CLOEXEC == 0) /* ancient libc */
  1557. close_on_exec_on(fd);
  1558. }
  1559. fp = xmalloc(sizeof(*fp));
  1560. if (name == NULL)
  1561. G.HFILE_stdin = fp;
  1562. fp->fd = fd;
  1563. fp->cur = fp->end = fp->buf;
  1564. fp->next_hfile = G.HFILE_list;
  1565. G.HFILE_list = fp;
  1566. return fp;
  1567. }
  1568. static void hfclose(HFILE *fp)
  1569. {
  1570. HFILE **pp = &G.HFILE_list;
  1571. while (*pp) {
  1572. HFILE *cur = *pp;
  1573. if (cur == fp) {
  1574. *pp = cur->next_hfile;
  1575. break;
  1576. }
  1577. pp = &cur->next_hfile;
  1578. }
  1579. if (fp->fd >= 0)
  1580. close(fp->fd);
  1581. free(fp);
  1582. }
  1583. static int refill_HFILE_and_getc(HFILE *fp)
  1584. {
  1585. int n;
  1586. if (fp->fd < 0) {
  1587. /* Already saw EOF */
  1588. return EOF;
  1589. }
  1590. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1591. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1592. * IOW: ^C will not immediately stop line input.
  1593. * But poll() is different: it does NOT restart after signals.
  1594. */
  1595. if (fp == G.HFILE_stdin) {
  1596. struct pollfd pfd[1];
  1597. pfd[0].fd = fp->fd;
  1598. pfd[0].events = POLLIN;
  1599. n = poll(pfd, 1, -1);
  1600. if (n < 0
  1601. /*&& errno == EINTR - assumed true */
  1602. && sigismember(&G.pending_set, SIGINT)
  1603. ) {
  1604. return '\0';
  1605. }
  1606. }
  1607. #else
  1608. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1609. #endif
  1610. /* Try to buffer more input */
  1611. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1612. if (n < 0) {
  1613. bb_simple_perror_msg("read error");
  1614. n = 0;
  1615. }
  1616. fp->cur = fp->buf;
  1617. fp->end = fp->buf + n;
  1618. if (n == 0) {
  1619. /* EOF/error */
  1620. close(fp->fd);
  1621. fp->fd = -1;
  1622. return EOF;
  1623. }
  1624. return (unsigned char)(*fp->cur++);
  1625. }
  1626. /* Inlined for common case of non-empty buffer.
  1627. */
  1628. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1629. {
  1630. if (fp->cur < fp->end)
  1631. return (unsigned char)(*fp->cur++);
  1632. /* Buffer empty */
  1633. return refill_HFILE_and_getc(fp);
  1634. }
  1635. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1636. {
  1637. HFILE *fl = G.HFILE_list;
  1638. while (fl) {
  1639. if (fd == fl->fd) {
  1640. /* We use it only on script files, they are all CLOEXEC */
  1641. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1642. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1643. return 1; /* "found and moved" */
  1644. }
  1645. fl = fl->next_hfile;
  1646. }
  1647. #if ENABLE_HUSH_MODE_X
  1648. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1649. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1650. return 1; /* "found and moved" */
  1651. }
  1652. #endif
  1653. return 0; /* "not in the list" */
  1654. }
  1655. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1656. static void close_all_HFILE_list(void)
  1657. {
  1658. HFILE *fl = G.HFILE_list;
  1659. while (fl) {
  1660. /* hfclose would also free HFILE object.
  1661. * It is disastrous if we share memory with a vforked parent.
  1662. * I'm not sure we never come here after vfork.
  1663. * Therefore just close fd, nothing more.
  1664. *
  1665. * ">" instead of ">=": we don't close fd#0,
  1666. * interactive shell uses hfopen(NULL) as stdin input
  1667. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1668. * If we'd close it here, then e.g. interactive "set | sort"
  1669. * with NOFORKed sort, would have sort's input fd closed.
  1670. */
  1671. if (fl->fd > 0)
  1672. /*hfclose(fl); - unsafe */
  1673. close(fl->fd);
  1674. fl = fl->next_hfile;
  1675. }
  1676. }
  1677. #endif
  1678. static int fd_in_HFILEs(int fd)
  1679. {
  1680. HFILE *fl = G.HFILE_list;
  1681. while (fl) {
  1682. if (fl->fd == fd)
  1683. return 1;
  1684. fl = fl->next_hfile;
  1685. }
  1686. return 0;
  1687. }
  1688. /*
  1689. * Helpers for setting new $n and restoring them back
  1690. */
  1691. typedef struct save_arg_t {
  1692. char *sv_argv0;
  1693. char **sv_g_argv;
  1694. int sv_g_argc;
  1695. IF_HUSH_SET(smallint sv_g_malloced;)
  1696. } save_arg_t;
  1697. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1698. {
  1699. sv->sv_argv0 = argv[0];
  1700. sv->sv_g_argv = G.global_argv;
  1701. sv->sv_g_argc = G.global_argc;
  1702. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1703. argv[0] = G.global_argv[0]; /* retain $0 */
  1704. G.global_argv = argv;
  1705. IF_HUSH_SET(G.global_args_malloced = 0;)
  1706. G.global_argc = 1 + string_array_len(argv + 1);
  1707. }
  1708. static void restore_G_args(save_arg_t *sv, char **argv)
  1709. {
  1710. #if ENABLE_HUSH_SET
  1711. if (G.global_args_malloced) {
  1712. /* someone ran "set -- arg1 arg2 ...", undo */
  1713. char **pp = G.global_argv;
  1714. while (*++pp) /* note: does not free $0 */
  1715. free(*pp);
  1716. free(G.global_argv);
  1717. }
  1718. #endif
  1719. argv[0] = sv->sv_argv0;
  1720. G.global_argv = sv->sv_g_argv;
  1721. G.global_argc = sv->sv_g_argc;
  1722. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1723. }
  1724. /*
  1725. * Basic theory of signal handling in shell
  1726. * ========================================
  1727. * This does not describe what hush does, rather, it is current understanding
  1728. * what it _should_ do. If it doesn't, it's a bug.
  1729. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1730. *
  1731. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1732. * is finished or backgrounded. It is the same in interactive and
  1733. * non-interactive shells, and is the same regardless of whether
  1734. * a user trap handler is installed or a shell special one is in effect.
  1735. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1736. * backgrounds (i.e. stops) or kills all members of currently running
  1737. * pipe.
  1738. *
  1739. * Wait builtin is interruptible by signals for which user trap is set
  1740. * or by SIGINT in interactive shell.
  1741. *
  1742. * Trap handlers will execute even within trap handlers. (right?)
  1743. *
  1744. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1745. * except for handlers set to '' (empty string).
  1746. *
  1747. * If job control is off, backgrounded commands ("cmd &")
  1748. * have SIGINT, SIGQUIT set to SIG_IGN.
  1749. *
  1750. * Commands which are run in command substitution ("`cmd`")
  1751. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1752. *
  1753. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1754. * by the shell from its parent.
  1755. *
  1756. * Signals which differ from SIG_DFL action
  1757. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1758. *
  1759. * SIGQUIT: ignore
  1760. * SIGTERM (interactive): ignore
  1761. * SIGHUP (interactive):
  1762. * Send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit.
  1763. * Kernel would do this for us ("orphaned process group" handling
  1764. * according to POSIX) if we are a session leader and thus our death
  1765. * frees the controlling tty, but to be bash-compatible, we also do it
  1766. * for every interactive shell's death by SIGHUP.
  1767. * (Also, we need to restore tty pgrp, otherwise e.g. Midnight Commander
  1768. * backgrounds when hush started from it gets killed by SIGHUP).
  1769. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1770. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1771. * that all pipe members are stopped. Try this in bash:
  1772. * while :; do :; done - ^Z does not background it
  1773. * (while :; do :; done) - ^Z backgrounds it
  1774. * SIGINT (interactive): wait for last pipe, ignore the rest
  1775. * of the command line, show prompt. NB: ^C does not send SIGINT
  1776. * to interactive shell while shell is waiting for a pipe,
  1777. * since shell is bg'ed (is not in foreground process group).
  1778. * Example 1: this waits 5 sec, but does not execute ls:
  1779. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1780. * Example 2: this does not wait and does not execute ls:
  1781. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1782. * Example 3: this does not wait 5 sec, but executes ls:
  1783. * "sleep 5; ls -l" + press ^C
  1784. * Example 4: this does not wait and does not execute ls:
  1785. * "sleep 5 & wait; ls -l" + press ^C
  1786. *
  1787. * (What happens to signals which are IGN on shell start?)
  1788. * (What happens with signal mask on shell start?)
  1789. *
  1790. * Old implementation
  1791. * ==================
  1792. * We use in-kernel pending signal mask to determine which signals were sent.
  1793. * We block all signals which we don't want to take action immediately,
  1794. * i.e. we block all signals which need to have special handling as described
  1795. * above, and all signals which have traps set.
  1796. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1797. * and act on them.
  1798. *
  1799. * unsigned special_sig_mask: a mask of such "special" signals
  1800. * sigset_t blocked_set: current blocked signal set
  1801. *
  1802. * "trap - SIGxxx":
  1803. * clear bit in blocked_set unless it is also in special_sig_mask
  1804. * "trap 'cmd' SIGxxx":
  1805. * set bit in blocked_set (even if 'cmd' is '')
  1806. * after [v]fork, if we plan to be a shell:
  1807. * unblock signals with special interactive handling
  1808. * (child shell is not interactive),
  1809. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1810. * after [v]fork, if we plan to exec:
  1811. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1812. * Restore blocked signal set to one inherited by shell just prior to exec.
  1813. *
  1814. * Note: as a result, we do not use signal handlers much. The only uses
  1815. * are to count SIGCHLDs
  1816. * and to restore tty pgrp on signal-induced exit.
  1817. *
  1818. * Note 2 (compat):
  1819. * Standard says "When a subshell is entered, traps that are not being ignored
  1820. * are set to the default actions". bash interprets it so that traps which
  1821. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1822. *
  1823. * Problem: the above approach makes it unwieldy to catch signals while
  1824. * we are in read builtin, or while we read commands from stdin:
  1825. * masked signals are not visible!
  1826. *
  1827. * New implementation
  1828. * ==================
  1829. * We record each signal we are interested in by installing signal handler
  1830. * for them - a bit like emulating kernel pending signal mask in userspace.
  1831. * We are interested in: signals which need to have special handling
  1832. * as described above, and all signals which have traps set.
  1833. * Signals are recorded in pending_set.
  1834. * After each pipe execution, we extract any pending signals
  1835. * and act on them.
  1836. *
  1837. * unsigned special_sig_mask: a mask of shell-special signals.
  1838. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1839. * char *traps[sig] if trap for sig is set (even if it's '').
  1840. * sigset_t pending_set: set of sigs we received.
  1841. *
  1842. * "trap - SIGxxx":
  1843. * if sig is in special_sig_mask, set handler back to:
  1844. * record_pending_signo, or to IGN if it's a tty stop signal
  1845. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1846. * else: set handler back to SIG_DFL
  1847. * "trap 'cmd' SIGxxx":
  1848. * set handler to record_pending_signo.
  1849. * "trap '' SIGxxx":
  1850. * set handler to SIG_IGN.
  1851. * after [v]fork, if we plan to be a shell:
  1852. * set signals with special interactive handling to SIG_DFL
  1853. * (because child shell is not interactive),
  1854. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1855. * after [v]fork, if we plan to exec:
  1856. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1857. *
  1858. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1859. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1860. *
  1861. * Note (compat):
  1862. * Standard says "When a subshell is entered, traps that are not being ignored
  1863. * are set to the default actions". bash interprets it so that traps which
  1864. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1865. */
  1866. enum {
  1867. SPECIAL_INTERACTIVE_SIGS = 0
  1868. | (1 << SIGTERM)
  1869. | (1 << SIGINT)
  1870. | (1 << SIGHUP)
  1871. ,
  1872. SPECIAL_JOBSTOP_SIGS = 0
  1873. #if ENABLE_HUSH_JOB
  1874. | (1 << SIGTTIN)
  1875. | (1 << SIGTTOU)
  1876. | (1 << SIGTSTP)
  1877. #endif
  1878. ,
  1879. };
  1880. static void record_pending_signo(int sig)
  1881. {
  1882. sigaddset(&G.pending_set, sig);
  1883. #if ENABLE_FEATURE_EDITING
  1884. if (sig != SIGCHLD
  1885. || (G_traps && G_traps[SIGCHLD] && G_traps[SIGCHLD][0])
  1886. /* ^^^ if SIGCHLD, interrupt line reading only if it has a trap */
  1887. ) {
  1888. bb_got_signal = sig; /* for read_line_input: "we got a signal" */
  1889. }
  1890. #endif
  1891. #if ENABLE_HUSH_FAST
  1892. if (sig == SIGCHLD) {
  1893. G.count_SIGCHLD++;
  1894. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1895. }
  1896. #endif
  1897. }
  1898. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1899. {
  1900. struct sigaction old_sa;
  1901. /* We could use signal() to install handlers... almost:
  1902. * except that we need to mask ALL signals while handlers run.
  1903. * I saw signal nesting in strace, race window isn't small.
  1904. * SA_RESTART is also needed, but in Linux, signal()
  1905. * sets SA_RESTART too.
  1906. */
  1907. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1908. /* sigfillset(&G.sa.sa_mask); - already done */
  1909. /* G.sa.sa_flags = SA_RESTART; - already done */
  1910. G.sa.sa_handler = handler;
  1911. sigaction(sig, &G.sa, &old_sa);
  1912. return old_sa.sa_handler;
  1913. }
  1914. static void hush_exit(int exitcode) NORETURN;
  1915. static void restore_ttypgrp_and__exit(void) NORETURN;
  1916. static void restore_ttypgrp_and__exit(void)
  1917. {
  1918. /* xfunc has failed! die die die */
  1919. /* no EXIT traps, this is an escape hatch! */
  1920. G.exiting = 1;
  1921. hush_exit(xfunc_error_retval);
  1922. }
  1923. #if ENABLE_HUSH_JOB
  1924. /* Needed only on some libc:
  1925. * It was observed that on exit(), fgetc'ed buffered data
  1926. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1927. * With the net effect that even after fork(), not vfork(),
  1928. * exit() in NOEXECed applet in "sh SCRIPT":
  1929. * noexec_applet_here
  1930. * echo END_OF_SCRIPT
  1931. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1932. * This makes "echo END_OF_SCRIPT" executed twice.
  1933. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1934. * and in `cmd` handling.
  1935. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1936. */
  1937. static void fflush_and__exit(void) NORETURN;
  1938. static void fflush_and__exit(void)
  1939. {
  1940. fflush_all();
  1941. _exit(xfunc_error_retval);
  1942. }
  1943. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1944. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1945. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1946. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1947. /* Restores tty foreground process group, and exits.
  1948. * May be called as signal handler for fatal signal
  1949. * (will resend signal to itself, producing correct exit state)
  1950. * or called directly with -EXITCODE.
  1951. * We also call it if xfunc is exiting.
  1952. */
  1953. static void sigexit(int sig) NORETURN;
  1954. static void sigexit(int sig)
  1955. {
  1956. /* Careful: we can end up here after [v]fork. Do not restore
  1957. * tty pgrp then, only top-level shell process does that */
  1958. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1959. /* Disable all signals: job control, SIGPIPE, etc.
  1960. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1961. */
  1962. sigprocmask_allsigs(SIG_BLOCK);
  1963. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1964. }
  1965. /* Not a signal, just exit */
  1966. if (sig <= 0)
  1967. _exit(- sig);
  1968. kill_myself_with_sig(sig); /* does not return */
  1969. }
  1970. #else
  1971. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1972. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1973. #endif
  1974. static sighandler_t pick_sighandler(unsigned sig)
  1975. {
  1976. sighandler_t handler = SIG_DFL;
  1977. if (sig < sizeof(unsigned)*8) {
  1978. unsigned sigmask = (1 << sig);
  1979. #if ENABLE_HUSH_JOB
  1980. /* is sig fatal? */
  1981. if (G_fatal_sig_mask & sigmask)
  1982. handler = sigexit;
  1983. else
  1984. #endif
  1985. /* sig has special handling? */
  1986. if (G.special_sig_mask & sigmask) {
  1987. handler = record_pending_signo;
  1988. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1989. * in order to ignore them: they will be raised
  1990. * in an endless loop when we try to do some
  1991. * terminal ioctls! We do have to _ignore_ these.
  1992. */
  1993. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1994. handler = SIG_IGN;
  1995. }
  1996. }
  1997. return handler;
  1998. }
  1999. /* Restores tty foreground process group, and exits. */
  2000. static void hush_exit(int exitcode)
  2001. {
  2002. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  2003. save_history(G.line_input_state); /* may be NULL */
  2004. #endif
  2005. fflush_all();
  2006. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  2007. char *argv[3];
  2008. /* argv[0] is unused */
  2009. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  2010. argv[2] = NULL;
  2011. G.exiting = 1; /* prevent EXIT trap recursion */
  2012. /* Note: G_traps[0] is not cleared!
  2013. * "trap" will still show it, if executed
  2014. * in the handler */
  2015. builtin_eval(argv);
  2016. }
  2017. #if ENABLE_FEATURE_CLEAN_UP
  2018. {
  2019. struct variable *cur_var;
  2020. if (G.cwd != bb_msg_unknown)
  2021. free((char*)G.cwd);
  2022. cur_var = G.top_var;
  2023. while (cur_var) {
  2024. struct variable *tmp = cur_var;
  2025. if (!cur_var->max_len)
  2026. free(cur_var->varstr);
  2027. cur_var = cur_var->next;
  2028. free(tmp);
  2029. }
  2030. }
  2031. #endif
  2032. fflush_all();
  2033. #if ENABLE_HUSH_JOB
  2034. sigexit(- (exitcode & 0xff));
  2035. #else
  2036. _exit(exitcode);
  2037. #endif
  2038. }
  2039. //TODO: return a mask of ALL handled sigs?
  2040. static int check_and_run_traps(void)
  2041. {
  2042. int last_sig = 0;
  2043. while (1) {
  2044. int sig;
  2045. if (sigisemptyset(&G.pending_set))
  2046. break;
  2047. sig = 0;
  2048. do {
  2049. sig++;
  2050. if (sigismember(&G.pending_set, sig)) {
  2051. sigdelset(&G.pending_set, sig);
  2052. goto got_sig;
  2053. }
  2054. } while (sig < NSIG);
  2055. break;
  2056. got_sig:
  2057. #if ENABLE_HUSH_TRAP
  2058. if (G_traps && G_traps[sig]) {
  2059. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2060. if (G_traps[sig][0]) {
  2061. /* We have user-defined handler */
  2062. smalluint save_rcode;
  2063. int save_pre;
  2064. char *argv[3];
  2065. /* argv[0] is unused */
  2066. argv[1] = xstrdup(G_traps[sig]);
  2067. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2068. argv[2] = NULL;
  2069. save_pre = G.pre_trap_exitcode;
  2070. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2071. builtin_eval(argv);
  2072. free(argv[1]);
  2073. G.pre_trap_exitcode = save_pre;
  2074. G.last_exitcode = save_rcode;
  2075. # if ENABLE_HUSH_FUNCTIONS
  2076. if (G.return_exitcode >= 0) {
  2077. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2078. G.last_exitcode = G.return_exitcode;
  2079. }
  2080. # endif
  2081. last_sig = sig;
  2082. } /* else: "" trap, ignoring signal */
  2083. continue;
  2084. }
  2085. #endif
  2086. /* not a trap: special action */
  2087. switch (sig) {
  2088. case SIGINT:
  2089. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2090. G.flag_SIGINT = 1;
  2091. last_sig = sig;
  2092. break;
  2093. #if ENABLE_HUSH_JOB
  2094. case SIGHUP: {
  2095. /* if (G_interactive_fd) - no need to check, the handler
  2096. * is only installed if we *are* interactive */
  2097. {
  2098. /* bash compat: "Before exiting, an interactive
  2099. * shell resends the SIGHUP to all jobs, running
  2100. * or stopped. Stopped jobs are sent SIGCONT
  2101. * to ensure that they receive the SIGHUP."
  2102. */
  2103. struct pipe *job;
  2104. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2105. /* bash is observed to signal whole process groups,
  2106. * not individual processes */
  2107. for (job = G.job_list; job; job = job->next) {
  2108. if (job->pgrp <= 0)
  2109. continue;
  2110. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2111. if (kill(- job->pgrp, SIGHUP) == 0)
  2112. kill(- job->pgrp, SIGCONT);
  2113. }
  2114. }
  2115. /* this restores tty pgrp, then kills us with SIGHUP */
  2116. sigexit(SIGHUP);
  2117. }
  2118. #endif
  2119. #if ENABLE_HUSH_FAST
  2120. case SIGCHLD:
  2121. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2122. G.count_SIGCHLD++;
  2123. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2124. /* Note:
  2125. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2126. * This simplifies wait builtin a bit.
  2127. */
  2128. break;
  2129. #endif
  2130. default: /* ignored: */
  2131. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2132. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2133. /* Note:
  2134. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2135. * Example: wait is not interrupted by TERM
  2136. * in interactive shell, because TERM is ignored.
  2137. */
  2138. break;
  2139. }
  2140. }
  2141. return last_sig;
  2142. }
  2143. /*
  2144. * Shell and environment variable support
  2145. */
  2146. static const char *get_cwd(int force)
  2147. {
  2148. if (force || G.cwd == NULL) {
  2149. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2150. * we must not try to free(bb_msg_unknown) */
  2151. if (G.cwd == bb_msg_unknown)
  2152. G.cwd = NULL;
  2153. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2154. if (!G.cwd)
  2155. G.cwd = bb_msg_unknown;
  2156. }
  2157. return G.cwd;
  2158. }
  2159. static struct variable **get_ptr_to_local_var(const char *name)
  2160. {
  2161. struct variable **pp;
  2162. struct variable *cur;
  2163. pp = &G.top_var;
  2164. while ((cur = *pp) != NULL) {
  2165. if (varcmp(cur->varstr, name) == 0)
  2166. return pp;
  2167. pp = &cur->next;
  2168. }
  2169. return NULL;
  2170. }
  2171. static const char* FAST_FUNC get_local_var_value(const char *name)
  2172. {
  2173. struct variable **vpp;
  2174. if (G.expanded_assignments) {
  2175. char **cpp = G.expanded_assignments;
  2176. while (*cpp) {
  2177. char *cp = *cpp;
  2178. if (varcmp(cp, name) == 0)
  2179. return strchr(cp, '=') + 1;
  2180. cpp++;
  2181. }
  2182. }
  2183. vpp = get_ptr_to_local_var(name);
  2184. if (vpp)
  2185. return strchr((*vpp)->varstr, '=') + 1;
  2186. if (strcmp(name, "PPID") == 0)
  2187. return utoa(G.root_ppid);
  2188. // bash compat: UID? EUID?
  2189. #if ENABLE_HUSH_RANDOM_SUPPORT
  2190. if (strcmp(name, "RANDOM") == 0)
  2191. return utoa(next_random(&G.random_gen));
  2192. #endif
  2193. #if ENABLE_HUSH_LINENO_VAR
  2194. if (strcmp(name, "LINENO") == 0)
  2195. return utoa(G.execute_lineno);
  2196. #endif
  2197. #if BASH_EPOCH_VARS
  2198. {
  2199. const char *fmt = NULL;
  2200. if (strcmp(name, "EPOCHSECONDS") == 0)
  2201. fmt = "%llu";
  2202. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2203. fmt = "%llu.%06u";
  2204. if (fmt) {
  2205. struct timeval tv;
  2206. xgettimeofday(&tv);
  2207. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2208. (unsigned)tv.tv_usec);
  2209. return G.epoch_buf;
  2210. }
  2211. }
  2212. #endif
  2213. return NULL;
  2214. }
  2215. #if ENABLE_HUSH_GETOPTS
  2216. static void handle_changed_special_names(const char *name)
  2217. {
  2218. if (varcmp(name, "OPTIND") == 0) {
  2219. G.getopt_count = 0;
  2220. return;
  2221. }
  2222. }
  2223. #else
  2224. /* Do not even bother evaluating arguments */
  2225. # define handle_changed_special_names(...) ((void)0)
  2226. #endif
  2227. /* str holds "NAME=VAL" and is expected to be malloced.
  2228. * We take ownership of it.
  2229. */
  2230. #define SETFLAG_EXPORT (1 << 0)
  2231. #define SETFLAG_UNEXPORT (1 << 1)
  2232. #define SETFLAG_MAKE_RO (1 << 2)
  2233. #define SETFLAG_VARLVL_SHIFT 3
  2234. static int set_local_var(char *str, unsigned flags)
  2235. {
  2236. struct variable **cur_pp;
  2237. struct variable *cur;
  2238. char *free_me = NULL;
  2239. char *eq_sign;
  2240. int name_len;
  2241. int retval;
  2242. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2243. eq_sign = strchr(str, '=');
  2244. if (HUSH_DEBUG && !eq_sign)
  2245. bb_simple_error_msg_and_die("BUG in setvar");
  2246. name_len = eq_sign - str + 1; /* including '=' */
  2247. cur_pp = &G.top_var;
  2248. while ((cur = *cur_pp) != NULL) {
  2249. if (strncmp(cur->varstr, str, name_len) != 0) {
  2250. cur_pp = &cur->next;
  2251. continue;
  2252. }
  2253. /* We found an existing var with this name */
  2254. if (cur->flg_read_only) {
  2255. bb_error_msg("%s: readonly variable", str);
  2256. free(str);
  2257. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2258. //but export per se succeeds (does put the var in env). We don't mimic that.
  2259. return -1;
  2260. }
  2261. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2262. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2263. *eq_sign = '\0';
  2264. unsetenv(str);
  2265. *eq_sign = '=';
  2266. }
  2267. if (cur->var_nest_level < local_lvl) {
  2268. /* bash 3.2.33(1) and exported vars:
  2269. * # export z=z
  2270. * # f() { local z=a; env | grep ^z; }
  2271. * # f
  2272. * z=a
  2273. * # env | grep ^z
  2274. * z=z
  2275. */
  2276. if (cur->flg_export)
  2277. flags |= SETFLAG_EXPORT;
  2278. /* New variable is local ("local VAR=VAL" or
  2279. * "VAR=VAL cmd")
  2280. * and existing one is global, or local
  2281. * on a lower level that new one.
  2282. * Remove it from global variable list:
  2283. */
  2284. *cur_pp = cur->next;
  2285. if (G.shadowed_vars_pp) {
  2286. /* Save in "shadowed" list */
  2287. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2288. cur->flg_export ? "exported " : "",
  2289. cur->varstr, cur->var_nest_level, str, local_lvl
  2290. );
  2291. cur->next = *G.shadowed_vars_pp;
  2292. *G.shadowed_vars_pp = cur;
  2293. } else {
  2294. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2295. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2296. cur->flg_export ? "exported " : "",
  2297. cur->varstr, cur->var_nest_level, str, local_lvl
  2298. );
  2299. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2300. free_me = cur->varstr; /* then free it later */
  2301. free(cur);
  2302. }
  2303. break;
  2304. }
  2305. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2306. debug_printf_env("assignement '%s' does not change anything\n", str);
  2307. free_and_exp:
  2308. free(str);
  2309. goto exp;
  2310. }
  2311. /* Replace the value in the found "struct variable" */
  2312. if (cur->max_len != 0) {
  2313. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2314. /* This one is from startup env, reuse space */
  2315. debug_printf_env("reusing startup env for '%s'\n", str);
  2316. strcpy(cur->varstr, str);
  2317. goto free_and_exp;
  2318. }
  2319. /* Can't reuse */
  2320. cur->max_len = 0;
  2321. goto set_str_and_exp;
  2322. }
  2323. /* max_len == 0 signifies "malloced" var, which we can
  2324. * (and have to) free. But we can't free(cur->varstr) here:
  2325. * if cur->flg_export is 1, it is in the environment.
  2326. * We should either unsetenv+free, or wait until putenv,
  2327. * then putenv(new)+free(old).
  2328. */
  2329. free_me = cur->varstr;
  2330. goto set_str_and_exp;
  2331. }
  2332. /* Not found or shadowed - create new variable struct */
  2333. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2334. cur = xzalloc(sizeof(*cur));
  2335. cur->var_nest_level = local_lvl;
  2336. cur->next = *cur_pp;
  2337. *cur_pp = cur;
  2338. set_str_and_exp:
  2339. cur->varstr = str;
  2340. exp:
  2341. #if !BB_MMU || ENABLE_HUSH_READONLY
  2342. if (flags & SETFLAG_MAKE_RO) {
  2343. cur->flg_read_only = 1;
  2344. }
  2345. #endif
  2346. if (flags & SETFLAG_EXPORT)
  2347. cur->flg_export = 1;
  2348. retval = 0;
  2349. if (cur->flg_export) {
  2350. if (flags & SETFLAG_UNEXPORT) {
  2351. cur->flg_export = 0;
  2352. /* unsetenv was already done */
  2353. } else {
  2354. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2355. retval = putenv(cur->varstr);
  2356. /* fall through to "free(free_me)" -
  2357. * only now we can free old exported malloced string
  2358. */
  2359. }
  2360. }
  2361. free(free_me);
  2362. handle_changed_special_names(cur->varstr);
  2363. return retval;
  2364. }
  2365. static int set_local_var0(char *str)
  2366. {
  2367. return set_local_var(str, 0);
  2368. }
  2369. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2370. {
  2371. char *var = xasprintf("%s=%s", name, val);
  2372. set_local_var0(var);
  2373. }
  2374. /* Used at startup and after each cd */
  2375. static void set_pwd_var(unsigned flag)
  2376. {
  2377. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2378. }
  2379. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2380. static int unset_local_var(const char *name)
  2381. {
  2382. struct variable *cur;
  2383. struct variable **cur_pp;
  2384. cur_pp = &G.top_var;
  2385. while ((cur = *cur_pp) != NULL) {
  2386. if (varcmp(cur->varstr, name) == 0) {
  2387. if (cur->flg_read_only) {
  2388. bb_error_msg("%s: readonly variable", name);
  2389. return EXIT_FAILURE;
  2390. }
  2391. *cur_pp = cur->next;
  2392. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2393. bb_unsetenv(cur->varstr);
  2394. if (!cur->max_len)
  2395. free(cur->varstr);
  2396. free(cur);
  2397. break;
  2398. }
  2399. cur_pp = &cur->next;
  2400. }
  2401. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2402. handle_changed_special_names(name);
  2403. return EXIT_SUCCESS;
  2404. }
  2405. #endif
  2406. /*
  2407. * Helpers for "var1=val1 var2=val2 cmd" feature
  2408. */
  2409. static void add_vars(struct variable *var)
  2410. {
  2411. struct variable *next;
  2412. while (var) {
  2413. next = var->next;
  2414. var->next = G.top_var;
  2415. G.top_var = var;
  2416. if (var->flg_export) {
  2417. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2418. putenv(var->varstr);
  2419. } else {
  2420. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2421. }
  2422. var = next;
  2423. }
  2424. }
  2425. /* We put strings[i] into variable table and possibly putenv them.
  2426. * If variable is read only, we can free the strings[i]
  2427. * which attempts to overwrite it.
  2428. * The strings[] vector itself is freed.
  2429. */
  2430. static void set_vars_and_save_old(char **strings)
  2431. {
  2432. char **s;
  2433. if (!strings)
  2434. return;
  2435. s = strings;
  2436. while (*s) {
  2437. struct variable *var_p;
  2438. struct variable **var_pp;
  2439. char *eq;
  2440. eq = strchr(*s, '=');
  2441. if (HUSH_DEBUG && !eq)
  2442. bb_simple_error_msg_and_die("BUG in varexp4");
  2443. var_pp = get_ptr_to_local_var(*s);
  2444. if (var_pp) {
  2445. var_p = *var_pp;
  2446. if (var_p->flg_read_only) {
  2447. char **p;
  2448. bb_error_msg("%s: readonly variable", *s);
  2449. /*
  2450. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2451. * If VAR is readonly, leaving it in the list
  2452. * after asssignment error (msg above)
  2453. * causes doubled error message later, on unset.
  2454. */
  2455. debug_printf_env("removing/freeing '%s' element\n", *s);
  2456. free(*s);
  2457. p = s;
  2458. do { *p = p[1]; p++; } while (*p);
  2459. goto next;
  2460. }
  2461. /* below, set_local_var() with nest level will
  2462. * "shadow" (remove) this variable from
  2463. * global linked list.
  2464. */
  2465. }
  2466. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2467. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2468. s++;
  2469. next: ;
  2470. }
  2471. free(strings);
  2472. }
  2473. /*
  2474. * Unicode helper
  2475. */
  2476. static void reinit_unicode_for_hush(void)
  2477. {
  2478. /* Unicode support should be activated even if LANG is set
  2479. * _during_ shell execution, not only if it was set when
  2480. * shell was started. Therefore, re-check LANG every time:
  2481. */
  2482. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2483. || ENABLE_UNICODE_USING_LOCALE
  2484. ) {
  2485. const char *s = get_local_var_value("LC_ALL");
  2486. if (!s) s = get_local_var_value("LC_CTYPE");
  2487. if (!s) s = get_local_var_value("LANG");
  2488. reinit_unicode(s);
  2489. }
  2490. }
  2491. /*
  2492. * in_str support (strings, and "strings" read from files).
  2493. */
  2494. #if ENABLE_HUSH_INTERACTIVE
  2495. /* To test correct lineedit/interactive behavior, type from command line:
  2496. * echo $P\
  2497. * \
  2498. * AT\
  2499. * H\
  2500. * \
  2501. * It exercises a lot of corner cases.
  2502. */
  2503. static const char *setup_prompt_string(void)
  2504. {
  2505. const char *prompt_str;
  2506. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2507. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2508. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2509. if (!prompt_str)
  2510. prompt_str = "";
  2511. # else
  2512. prompt_str = "> "; /* if PS2, else... */
  2513. if (G.promptmode == 0) { /* PS1 */
  2514. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2515. free(G.PS1);
  2516. /* bash uses $PWD value, even if it is set by user.
  2517. * It uses current dir only if PWD is unset.
  2518. * We always use current dir. */
  2519. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2520. }
  2521. # endif
  2522. debug_printf("prompt_str '%s'\n", prompt_str);
  2523. return prompt_str;
  2524. }
  2525. static int get_user_input(struct in_str *i)
  2526. {
  2527. # if ENABLE_FEATURE_EDITING
  2528. /* In EDITING case, this function reads next input line,
  2529. * saves it in i->p, then returns 1st char of it.
  2530. */
  2531. int r;
  2532. const char *prompt_str;
  2533. prompt_str = setup_prompt_string();
  2534. for (;;) {
  2535. reinit_unicode_for_hush();
  2536. G.flag_SIGINT = 0;
  2537. bb_got_signal = 0;
  2538. if (!sigisemptyset(&G.pending_set)) {
  2539. /* Whoops, already got a signal, do not call read_line_input */
  2540. bb_got_signal = r = -1;
  2541. } else {
  2542. /* For shell, LI_INTERRUPTIBLE is set:
  2543. * read_line_input will abort on either
  2544. * getting EINTR in poll() and bb_got_signal became != 0,
  2545. * or if it sees bb_got_signal != 0
  2546. * (IOW: if signal arrives before poll() is reached).
  2547. * Interactive testcases:
  2548. * (while kill -INT $$; do sleep 1; done) &
  2549. * #^^^ prints ^C, prints prompt, repeats
  2550. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  2551. * #^^^ prints ^C, prints "I", prints prompt, repeats
  2552. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  2553. * #^^^ prints "T", prints prompt, repeats
  2554. * #(bash 5.0.17 exits after first "T", looks like a bug)
  2555. */
  2556. r = read_line_input(G.line_input_state, prompt_str,
  2557. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2558. );
  2559. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2560. if (r == 0)
  2561. raise(SIGINT);
  2562. }
  2563. /* bash prints ^C (before running a trap, if any)
  2564. * both on keyboard ^C and on real SIGINT (non-kbd generated).
  2565. */
  2566. if (sigismember(&G.pending_set, SIGINT)) {
  2567. write(STDOUT_FILENO, "^C\n", 3);
  2568. G.last_exitcode = 128 | SIGINT;
  2569. }
  2570. check_and_run_traps();
  2571. if (r == 0) /* keyboard ^C? */
  2572. continue; /* go back, read another input line */
  2573. if (r > 0) /* normal input? (no ^C, no ^D, no signals) */
  2574. break;
  2575. if (!bb_got_signal) {
  2576. /* r < 0: ^D/EOF/error detected (but not signal) */
  2577. /* ^D on interactive input goes to next line before exiting: */
  2578. write(STDOUT_FILENO, "\n", 1);
  2579. i->p = NULL;
  2580. i->peek_buf[0] = r = EOF;
  2581. return r;
  2582. }
  2583. /* it was a signal: go back, read another input line */
  2584. }
  2585. i->p = G.user_input_buf;
  2586. return (unsigned char)*i->p++;
  2587. # else
  2588. /* In !EDITING case, this function gets called for every char.
  2589. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2590. */
  2591. int r;
  2592. for (;;) {
  2593. G.flag_SIGINT = 0;
  2594. if (i->last_char == '\0' || i->last_char == '\n') {
  2595. const char *prompt_str = setup_prompt_string();
  2596. /* Why check_and_run_traps here? Try this interactively:
  2597. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2598. * $ <[enter], repeatedly...>
  2599. * Without check_and_run_traps, handler never runs.
  2600. */
  2601. check_and_run_traps();
  2602. fputs_stdout(prompt_str);
  2603. fflush_all();
  2604. }
  2605. r = hfgetc(i->file);
  2606. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2607. * no ^C masking happens during fgetc, no special code for ^C:
  2608. * it generates SIGINT as usual.
  2609. */
  2610. check_and_run_traps();
  2611. if (r != '\0' && !G.flag_SIGINT)
  2612. break;
  2613. if (G.flag_SIGINT) {
  2614. /* ^C or SIGINT: repeat */
  2615. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2616. /* kernel prints "^C" itself, just print newline: */
  2617. write(STDOUT_FILENO, "\n", 1);
  2618. G.last_exitcode = 128 | SIGINT;
  2619. }
  2620. }
  2621. return r;
  2622. # endif
  2623. }
  2624. /* This is the magic location that prints prompts
  2625. * and gets data back from the user */
  2626. static int fgetc_interactive(struct in_str *i)
  2627. {
  2628. int ch;
  2629. /* If it's interactive stdin, get new line. */
  2630. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2631. /* Returns first char (or EOF), the rest is in i->p[] */
  2632. ch = get_user_input(i);
  2633. G.promptmode = 1; /* PS2 */
  2634. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2635. } else {
  2636. /* Not stdin: script file, sourced file, etc */
  2637. do ch = hfgetc(i->file); while (ch == '\0');
  2638. }
  2639. return ch;
  2640. }
  2641. #else /* !INTERACTIVE */
  2642. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2643. {
  2644. int ch;
  2645. do ch = hfgetc(i->file); while (ch == '\0');
  2646. return ch;
  2647. }
  2648. #endif /* !INTERACTIVE */
  2649. static int i_getch(struct in_str *i)
  2650. {
  2651. int ch;
  2652. if (!i->file) {
  2653. /* string-based in_str */
  2654. ch = (unsigned char)*i->p;
  2655. if (ch != '\0') {
  2656. i->p++;
  2657. i->last_char = ch;
  2658. #if ENABLE_HUSH_LINENO_VAR
  2659. if (ch == '\n') {
  2660. G.parse_lineno++;
  2661. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2662. }
  2663. #endif
  2664. return ch;
  2665. }
  2666. return EOF;
  2667. }
  2668. /* FILE-based in_str */
  2669. #if ENABLE_FEATURE_EDITING
  2670. /* This can be stdin, check line editing char[] buffer */
  2671. if (i->p && *i->p != '\0') {
  2672. ch = (unsigned char)*i->p++;
  2673. goto out;
  2674. }
  2675. #endif
  2676. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2677. ch = i->peek_buf[0];
  2678. if (ch != 0) {
  2679. int ch2 = i->peek_buf[1];
  2680. i->peek_buf[0] = ch2;
  2681. if (ch2 == 0) /* very likely, avoid redundant write */
  2682. goto out;
  2683. i->peek_buf[1] = 0;
  2684. goto out;
  2685. }
  2686. ch = fgetc_interactive(i);
  2687. out:
  2688. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2689. i->last_char = ch;
  2690. #if ENABLE_HUSH_LINENO_VAR
  2691. if (ch == '\n') {
  2692. G.parse_lineno++;
  2693. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2694. }
  2695. #endif
  2696. return ch;
  2697. }
  2698. static int i_peek(struct in_str *i)
  2699. {
  2700. int ch;
  2701. if (!i->file) {
  2702. /* string-based in_str */
  2703. /* Doesn't report EOF on NUL. None of the callers care. */
  2704. return (unsigned char)*i->p;
  2705. }
  2706. /* FILE-based in_str */
  2707. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2708. /* This can be stdin, check line editing char[] buffer */
  2709. if (i->p && *i->p != '\0')
  2710. return (unsigned char)*i->p;
  2711. #endif
  2712. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2713. ch = i->peek_buf[0];
  2714. if (ch != 0)
  2715. return ch;
  2716. /* Need to get a new char */
  2717. ch = fgetc_interactive(i);
  2718. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2719. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2720. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2721. if (i->p) {
  2722. i->p -= 1;
  2723. return ch;
  2724. }
  2725. #endif
  2726. i->peek_buf[0] = ch;
  2727. /*i->peek_buf[1] = 0; - already is */
  2728. return ch;
  2729. }
  2730. /* Only ever called if i_peek() was called, and did not return EOF.
  2731. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2732. * not end-of-line. Therefore we never need to read a new editing line here.
  2733. */
  2734. static int i_peek2(struct in_str *i)
  2735. {
  2736. int ch;
  2737. /* There are two cases when i->p[] buffer exists.
  2738. * (1) it's a string in_str.
  2739. * (2) It's a file, and we have a saved line editing buffer.
  2740. * In both cases, we know that i->p[0] exists and not NUL, and
  2741. * the peek2 result is in i->p[1].
  2742. */
  2743. if (i->p)
  2744. return (unsigned char)i->p[1];
  2745. /* Now we know it is a file-based in_str. */
  2746. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2747. /* Is there 2nd char? */
  2748. ch = i->peek_buf[1];
  2749. if (ch == 0) {
  2750. /* We did not read it yet, get it now */
  2751. do ch = hfgetc(i->file); while (ch == '\0');
  2752. i->peek_buf[1] = ch;
  2753. }
  2754. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2755. return ch;
  2756. }
  2757. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2758. {
  2759. for (;;) {
  2760. int ch, ch2;
  2761. ch = i_getch(input);
  2762. if (ch != '\\')
  2763. return ch;
  2764. ch2 = i_peek(input);
  2765. if (ch2 != '\n')
  2766. return ch;
  2767. /* backslash+newline, skip it */
  2768. i_getch(input);
  2769. }
  2770. }
  2771. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2772. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2773. */
  2774. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2775. {
  2776. for (;;) {
  2777. int ch, ch2;
  2778. ch = i_peek(input);
  2779. if (ch != '\\')
  2780. return ch;
  2781. ch2 = i_peek2(input);
  2782. if (ch2 != '\n')
  2783. return ch;
  2784. /* backslash+newline, skip it */
  2785. i_getch(input);
  2786. i_getch(input);
  2787. }
  2788. }
  2789. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2790. {
  2791. memset(i, 0, sizeof(*i));
  2792. i->file = fp;
  2793. /* i->p = NULL; */
  2794. }
  2795. static void setup_string_in_str(struct in_str *i, const char *s)
  2796. {
  2797. memset(i, 0, sizeof(*i));
  2798. /*i->file = NULL */;
  2799. i->p = s;
  2800. }
  2801. /*
  2802. * o_string support
  2803. */
  2804. #define B_CHUNK (32 * sizeof(char*))
  2805. static void o_reset_to_empty_unquoted(o_string *o)
  2806. {
  2807. o->length = 0;
  2808. o->has_quoted_part = 0;
  2809. if (o->data)
  2810. o->data[0] = '\0';
  2811. }
  2812. static void o_free_and_set_NULL(o_string *o)
  2813. {
  2814. free(o->data);
  2815. memset(o, 0, sizeof(*o));
  2816. }
  2817. static ALWAYS_INLINE void o_free(o_string *o)
  2818. {
  2819. free(o->data);
  2820. }
  2821. static void o_grow_by(o_string *o, int len)
  2822. {
  2823. if (o->length + len > o->maxlen) {
  2824. o->maxlen += (2 * len) | (B_CHUNK-1);
  2825. o->data = xrealloc(o->data, 1 + o->maxlen);
  2826. }
  2827. }
  2828. static void o_addchr(o_string *o, int ch)
  2829. {
  2830. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2831. if (o->length < o->maxlen) {
  2832. /* likely. avoid o_grow_by() call */
  2833. add:
  2834. o->data[o->length] = ch;
  2835. o->length++;
  2836. o->data[o->length] = '\0';
  2837. return;
  2838. }
  2839. o_grow_by(o, 1);
  2840. goto add;
  2841. }
  2842. #if 0
  2843. /* Valid only if we know o_string is not empty */
  2844. static void o_delchr(o_string *o)
  2845. {
  2846. o->length--;
  2847. o->data[o->length] = '\0';
  2848. }
  2849. #endif
  2850. static void o_addblock(o_string *o, const char *str, int len)
  2851. {
  2852. o_grow_by(o, len);
  2853. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2854. o->length += len;
  2855. }
  2856. static void o_addstr(o_string *o, const char *str)
  2857. {
  2858. o_addblock(o, str, strlen(str));
  2859. }
  2860. static void o_addstr_with_NUL(o_string *o, const char *str)
  2861. {
  2862. o_addblock(o, str, strlen(str) + 1);
  2863. }
  2864. #if !BB_MMU
  2865. static void nommu_addchr(o_string *o, int ch)
  2866. {
  2867. if (o)
  2868. o_addchr(o, ch);
  2869. }
  2870. #else
  2871. # define nommu_addchr(o, str) ((void)0)
  2872. #endif
  2873. #if ENABLE_HUSH_MODE_X
  2874. static void x_mode_addchr(int ch)
  2875. {
  2876. o_addchr(&G.x_mode_buf, ch);
  2877. }
  2878. static void x_mode_addstr(const char *str)
  2879. {
  2880. o_addstr(&G.x_mode_buf, str);
  2881. }
  2882. static void x_mode_addblock(const char *str, int len)
  2883. {
  2884. o_addblock(&G.x_mode_buf, str, len);
  2885. }
  2886. static void x_mode_prefix(void)
  2887. {
  2888. int n = G.x_mode_depth;
  2889. do x_mode_addchr('+'); while (--n >= 0);
  2890. }
  2891. static void x_mode_flush(void)
  2892. {
  2893. int len = G.x_mode_buf.length;
  2894. if (len <= 0)
  2895. return;
  2896. if (G.x_mode_fd > 0) {
  2897. G.x_mode_buf.data[len] = '\n';
  2898. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2899. }
  2900. G.x_mode_buf.length = 0;
  2901. }
  2902. #endif
  2903. /*
  2904. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2905. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2906. * Apparently, on unquoted $v bash still does globbing
  2907. * ("v='*.txt'; echo $v" prints all .txt files),
  2908. * but NOT brace expansion! Thus, there should be TWO independent
  2909. * quoting mechanisms on $v expansion side: one protects
  2910. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2911. * We have only second one.
  2912. */
  2913. #if ENABLE_HUSH_BRACE_EXPANSION
  2914. # define MAYBE_BRACES "{}"
  2915. #else
  2916. # define MAYBE_BRACES ""
  2917. #endif
  2918. /* My analysis of quoting semantics tells me that state information
  2919. * is associated with a destination, not a source.
  2920. */
  2921. static void o_addqchr(o_string *o, int ch)
  2922. {
  2923. int sz = 1;
  2924. /* '-' is included because of this case:
  2925. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2926. */
  2927. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2928. if (found)
  2929. sz++;
  2930. o_grow_by(o, sz);
  2931. if (found) {
  2932. o->data[o->length] = '\\';
  2933. o->length++;
  2934. }
  2935. o->data[o->length] = ch;
  2936. o->length++;
  2937. o->data[o->length] = '\0';
  2938. }
  2939. static void o_addQchr(o_string *o, int ch)
  2940. {
  2941. int sz = 1;
  2942. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2943. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2944. ) {
  2945. sz++;
  2946. o->data[o->length] = '\\';
  2947. o->length++;
  2948. }
  2949. o_grow_by(o, sz);
  2950. o->data[o->length] = ch;
  2951. o->length++;
  2952. o->data[o->length] = '\0';
  2953. }
  2954. static void o_addqblock(o_string *o, const char *str, int len)
  2955. {
  2956. while (len) {
  2957. char ch;
  2958. int sz;
  2959. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2960. if (ordinary_cnt > len) /* paranoia */
  2961. ordinary_cnt = len;
  2962. o_addblock(o, str, ordinary_cnt);
  2963. if (ordinary_cnt == len)
  2964. return; /* NUL is already added by o_addblock */
  2965. str += ordinary_cnt;
  2966. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2967. ch = *str++;
  2968. sz = 1;
  2969. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2970. sz++;
  2971. o->data[o->length] = '\\';
  2972. o->length++;
  2973. }
  2974. o_grow_by(o, sz);
  2975. o->data[o->length] = ch;
  2976. o->length++;
  2977. }
  2978. o->data[o->length] = '\0';
  2979. }
  2980. static void o_addQblock(o_string *o, const char *str, int len)
  2981. {
  2982. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2983. o_addblock(o, str, len);
  2984. return;
  2985. }
  2986. o_addqblock(o, str, len);
  2987. }
  2988. static void o_addQstr(o_string *o, const char *str)
  2989. {
  2990. o_addQblock(o, str, strlen(str));
  2991. }
  2992. /* A special kind of o_string for $VAR and `cmd` expansion.
  2993. * It contains char* list[] at the beginning, which is grown in 16 element
  2994. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2995. * list[i] contains an INDEX (int!) into this string data.
  2996. * It means that if list[] needs to grow, data needs to be moved higher up
  2997. * but list[i]'s need not be modified.
  2998. * NB: remembering how many list[i]'s you have there is crucial.
  2999. * o_finalize_list() operation post-processes this structure - calculates
  3000. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  3001. */
  3002. #if DEBUG_EXPAND || DEBUG_GLOB
  3003. static void debug_print_list(const char *prefix, o_string *o, int n)
  3004. {
  3005. char **list = (char**)o->data;
  3006. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3007. int i = 0;
  3008. indent();
  3009. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  3010. prefix, list, n, string_start, o->length, o->maxlen,
  3011. !!(o->o_expflags & EXP_FLAG_GLOB),
  3012. o->has_quoted_part,
  3013. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  3014. while (i < n) {
  3015. indent();
  3016. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  3017. o->data + (int)(uintptr_t)list[i] + string_start,
  3018. o->data + (int)(uintptr_t)list[i] + string_start);
  3019. i++;
  3020. }
  3021. if (n) {
  3022. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  3023. indent();
  3024. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  3025. }
  3026. }
  3027. #else
  3028. # define debug_print_list(prefix, o, n) ((void)0)
  3029. #endif
  3030. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  3031. * in list[n] so that it points past last stored byte so far.
  3032. * It returns n+1. */
  3033. static int o_save_ptr_helper(o_string *o, int n)
  3034. {
  3035. char **list = (char**)o->data;
  3036. int string_start;
  3037. int string_len;
  3038. if (!o->has_empty_slot) {
  3039. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3040. string_len = o->length - string_start;
  3041. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  3042. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  3043. /* list[n] points to string_start, make space for 16 more pointers */
  3044. o->maxlen += 0x10 * sizeof(list[0]);
  3045. o->data = xrealloc(o->data, o->maxlen + 1);
  3046. list = (char**)o->data;
  3047. memmove(list + n + 0x10, list + n, string_len);
  3048. /*
  3049. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  3050. * check. (grep for -prev-ifs-check-).
  3051. * Ensure that argv[-1][last] is not garbage
  3052. * but zero bytes, to save index check there.
  3053. */
  3054. list[n + 0x10 - 1] = 0;
  3055. o->length += 0x10 * sizeof(list[0]);
  3056. } else {
  3057. debug_printf_list("list[%d]=%d string_start=%d\n",
  3058. n, string_len, string_start);
  3059. }
  3060. } else {
  3061. /* We have empty slot at list[n], reuse without growth */
  3062. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  3063. string_len = o->length - string_start;
  3064. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  3065. n, string_len, string_start);
  3066. o->has_empty_slot = 0;
  3067. }
  3068. o->has_quoted_part = 0;
  3069. list[n] = (char*)(uintptr_t)string_len;
  3070. return n + 1;
  3071. }
  3072. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  3073. static int o_get_last_ptr(o_string *o, int n)
  3074. {
  3075. char **list = (char**)o->data;
  3076. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3077. return ((int)(uintptr_t)list[n-1]) + string_start;
  3078. }
  3079. /*
  3080. * Globbing routines.
  3081. *
  3082. * Most words in commands need to be globbed, even ones which are
  3083. * (single or double) quoted. This stems from the possiblity of
  3084. * constructs like "abc"* and 'abc'* - these should be globbed.
  3085. * Having a different code path for fully-quoted strings ("abc",
  3086. * 'abc') would only help performance-wise, but we still need
  3087. * code for partially-quoted strings.
  3088. *
  3089. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3090. * the logic can't be "shell-syntax argument is first transformed
  3091. * to a string, then globbed, and if globbing does not match anything,
  3092. * it is used verbatim". Here are two examples where it fails:
  3093. *
  3094. * echo 'b\*'?
  3095. *
  3096. * The globbing can't be avoided (because of '?' at the end).
  3097. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3098. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3099. * - IOW: they "unbackslash" the glob pattern.
  3100. * Now, look at this:
  3101. *
  3102. * v='\\\*'; echo b$v?
  3103. *
  3104. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3105. * should be used as glob pattern with no changes. However, if glob
  3106. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3107. *
  3108. * ash implements this by having an encoded representation of the word
  3109. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3110. * Glob pattern is derived from it. If glob fails, the decision what result
  3111. * should be is made using that encoded representation. Not glob pattern.
  3112. */
  3113. #if ENABLE_HUSH_BRACE_EXPANSION
  3114. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3115. * first, it processes even {a} (no commas), second,
  3116. * I didn't manage to make it return strings when they don't match
  3117. * existing files. Need to re-implement it.
  3118. */
  3119. /* Helper */
  3120. static int glob_needed(const char *s)
  3121. {
  3122. while (*s) {
  3123. if (*s == '\\') {
  3124. if (!s[1])
  3125. return 0;
  3126. s += 2;
  3127. continue;
  3128. }
  3129. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3130. return 1;
  3131. s++;
  3132. }
  3133. return 0;
  3134. }
  3135. /* Return pointer to next closing brace or to comma */
  3136. static const char *next_brace_sub(const char *cp)
  3137. {
  3138. unsigned depth = 0;
  3139. cp++;
  3140. while (*cp != '\0') {
  3141. if (*cp == '\\') {
  3142. if (*++cp == '\0')
  3143. break;
  3144. cp++;
  3145. continue;
  3146. }
  3147. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3148. break;
  3149. if (*cp++ == '{')
  3150. depth++;
  3151. }
  3152. return *cp != '\0' ? cp : NULL;
  3153. }
  3154. /* Recursive brace globber. Note: may garble pattern[]. */
  3155. static int glob_brace(char *pattern, o_string *o, int n)
  3156. {
  3157. char *new_pattern_buf;
  3158. const char *begin;
  3159. const char *next;
  3160. const char *rest;
  3161. const char *p;
  3162. size_t rest_len;
  3163. debug_printf_glob("glob_brace('%s')\n", pattern);
  3164. begin = pattern;
  3165. while (1) {
  3166. if (*begin == '\0')
  3167. goto simple_glob;
  3168. if (*begin == '{') {
  3169. /* Find the first sub-pattern and at the same time
  3170. * find the rest after the closing brace */
  3171. next = next_brace_sub(begin);
  3172. if (next == NULL) {
  3173. /* An illegal expression */
  3174. goto simple_glob;
  3175. }
  3176. if (*next == '}') {
  3177. /* "{abc}" with no commas - illegal
  3178. * brace expr, disregard and skip it */
  3179. begin = next + 1;
  3180. continue;
  3181. }
  3182. break;
  3183. }
  3184. if (*begin == '\\' && begin[1] != '\0')
  3185. begin++;
  3186. begin++;
  3187. }
  3188. debug_printf_glob("begin:%s\n", begin);
  3189. debug_printf_glob("next:%s\n", next);
  3190. /* Now find the end of the whole brace expression */
  3191. rest = next;
  3192. while (*rest != '}') {
  3193. rest = next_brace_sub(rest);
  3194. if (rest == NULL) {
  3195. /* An illegal expression */
  3196. goto simple_glob;
  3197. }
  3198. debug_printf_glob("rest:%s\n", rest);
  3199. }
  3200. rest_len = strlen(++rest) + 1;
  3201. /* We are sure the brace expression is well-formed */
  3202. /* Allocate working buffer large enough for our work */
  3203. new_pattern_buf = xmalloc(strlen(pattern));
  3204. /* We have a brace expression. BEGIN points to the opening {,
  3205. * NEXT points past the terminator of the first element, and REST
  3206. * points past the final }. We will accumulate result names from
  3207. * recursive runs for each brace alternative in the buffer using
  3208. * GLOB_APPEND. */
  3209. p = begin + 1;
  3210. while (1) {
  3211. /* Construct the new glob expression */
  3212. memcpy(
  3213. mempcpy(
  3214. mempcpy(new_pattern_buf,
  3215. /* We know the prefix for all sub-patterns */
  3216. pattern, begin - pattern),
  3217. p, next - p),
  3218. rest, rest_len);
  3219. /* Note: glob_brace() may garble new_pattern_buf[].
  3220. * That's why we re-copy prefix every time (1st memcpy above).
  3221. */
  3222. n = glob_brace(new_pattern_buf, o, n);
  3223. if (*next == '}') {
  3224. /* We saw the last entry */
  3225. break;
  3226. }
  3227. p = next + 1;
  3228. next = next_brace_sub(next);
  3229. }
  3230. free(new_pattern_buf);
  3231. return n;
  3232. simple_glob:
  3233. {
  3234. int gr;
  3235. glob_t globdata;
  3236. memset(&globdata, 0, sizeof(globdata));
  3237. gr = glob(pattern, 0, NULL, &globdata);
  3238. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3239. if (gr != 0) {
  3240. if (gr == GLOB_NOMATCH) {
  3241. globfree(&globdata);
  3242. /* NB: garbles parameter */
  3243. unbackslash(pattern);
  3244. o_addstr_with_NUL(o, pattern);
  3245. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3246. return o_save_ptr_helper(o, n);
  3247. }
  3248. if (gr == GLOB_NOSPACE)
  3249. bb_die_memory_exhausted();
  3250. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3251. * but we didn't specify it. Paranoia again. */
  3252. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3253. }
  3254. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3255. char **argv = globdata.gl_pathv;
  3256. while (1) {
  3257. o_addstr_with_NUL(o, *argv);
  3258. n = o_save_ptr_helper(o, n);
  3259. argv++;
  3260. if (!*argv)
  3261. break;
  3262. }
  3263. }
  3264. globfree(&globdata);
  3265. }
  3266. return n;
  3267. }
  3268. /* Performs globbing on last list[],
  3269. * saving each result as a new list[].
  3270. */
  3271. static int perform_glob(o_string *o, int n)
  3272. {
  3273. char *pattern, *copy;
  3274. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3275. if (!o->data)
  3276. return o_save_ptr_helper(o, n);
  3277. pattern = o->data + o_get_last_ptr(o, n);
  3278. debug_printf_glob("glob pattern '%s'\n", pattern);
  3279. if (!glob_needed(pattern)) {
  3280. /* unbackslash last string in o in place, fix length */
  3281. o->length = unbackslash(pattern) - o->data;
  3282. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3283. return o_save_ptr_helper(o, n);
  3284. }
  3285. copy = xstrdup(pattern);
  3286. /* "forget" pattern in o */
  3287. o->length = pattern - o->data;
  3288. n = glob_brace(copy, o, n);
  3289. free(copy);
  3290. if (DEBUG_GLOB)
  3291. debug_print_list("perform_glob returning", o, n);
  3292. return n;
  3293. }
  3294. #else /* !HUSH_BRACE_EXPANSION */
  3295. /* Helper */
  3296. static int glob_needed(const char *s)
  3297. {
  3298. while (*s) {
  3299. if (*s == '\\') {
  3300. if (!s[1])
  3301. return 0;
  3302. s += 2;
  3303. continue;
  3304. }
  3305. if (*s == '*' || *s == '[' || *s == '?')
  3306. return 1;
  3307. s++;
  3308. }
  3309. return 0;
  3310. }
  3311. /* Performs globbing on last list[],
  3312. * saving each result as a new list[].
  3313. */
  3314. static int perform_glob(o_string *o, int n)
  3315. {
  3316. glob_t globdata;
  3317. int gr;
  3318. char *pattern;
  3319. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3320. if (!o->data)
  3321. return o_save_ptr_helper(o, n);
  3322. pattern = o->data + o_get_last_ptr(o, n);
  3323. debug_printf_glob("glob pattern '%s'\n", pattern);
  3324. if (!glob_needed(pattern)) {
  3325. literal:
  3326. /* unbackslash last string in o in place, fix length */
  3327. o->length = unbackslash(pattern) - o->data;
  3328. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3329. return o_save_ptr_helper(o, n);
  3330. }
  3331. memset(&globdata, 0, sizeof(globdata));
  3332. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3333. * If we glob "*.\*" and don't find anything, we need
  3334. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3335. * will return "*.\*"!
  3336. */
  3337. gr = glob(pattern, 0, NULL, &globdata);
  3338. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3339. if (gr != 0) {
  3340. if (gr == GLOB_NOMATCH) {
  3341. globfree(&globdata);
  3342. goto literal;
  3343. }
  3344. if (gr == GLOB_NOSPACE)
  3345. bb_die_memory_exhausted();
  3346. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3347. * but we didn't specify it. Paranoia again. */
  3348. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3349. }
  3350. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3351. char **argv = globdata.gl_pathv;
  3352. /* "forget" pattern in o */
  3353. o->length = pattern - o->data;
  3354. while (1) {
  3355. o_addstr_with_NUL(o, *argv);
  3356. n = o_save_ptr_helper(o, n);
  3357. argv++;
  3358. if (!*argv)
  3359. break;
  3360. }
  3361. }
  3362. globfree(&globdata);
  3363. if (DEBUG_GLOB)
  3364. debug_print_list("perform_glob returning", o, n);
  3365. return n;
  3366. }
  3367. #endif /* !HUSH_BRACE_EXPANSION */
  3368. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3369. * Otherwise, just finish current list[] and start new */
  3370. static int o_save_ptr(o_string *o, int n)
  3371. {
  3372. if (o->o_expflags & EXP_FLAG_GLOB) {
  3373. /* If o->has_empty_slot, list[n] was already globbed
  3374. * (if it was requested back then when it was filled)
  3375. * so don't do that again! */
  3376. if (!o->has_empty_slot)
  3377. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3378. }
  3379. return o_save_ptr_helper(o, n);
  3380. }
  3381. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3382. static char **o_finalize_list(o_string *o, int n)
  3383. {
  3384. char **list;
  3385. int string_start;
  3386. if (DEBUG_EXPAND)
  3387. debug_print_list("finalized", o, n);
  3388. debug_printf_expand("finalized n:%d\n", n);
  3389. list = (char**)o->data;
  3390. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3391. list[--n] = NULL;
  3392. while (n) {
  3393. n--;
  3394. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3395. }
  3396. return list;
  3397. }
  3398. static void free_pipe_list(struct pipe *pi);
  3399. /* Returns pi->next - next pipe in the list */
  3400. static struct pipe *free_pipe(struct pipe *pi)
  3401. {
  3402. struct pipe *next;
  3403. int i;
  3404. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3405. for (i = 0; i < pi->num_cmds; i++) {
  3406. struct command *command;
  3407. struct redir_struct *r, *rnext;
  3408. command = &pi->cmds[i];
  3409. debug_printf_clean(" command %d:\n", i);
  3410. if (command->argv) {
  3411. if (DEBUG_CLEAN) {
  3412. int a;
  3413. char **p;
  3414. for (a = 0, p = command->argv; *p; a++, p++) {
  3415. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3416. }
  3417. }
  3418. free_strings(command->argv);
  3419. //command->argv = NULL;
  3420. }
  3421. /* not "else if": on syntax error, we may have both! */
  3422. if (command->group) {
  3423. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3424. command->cmd_type);
  3425. free_pipe_list(command->group);
  3426. debug_printf_clean(" end group\n");
  3427. //command->group = NULL;
  3428. }
  3429. /* else is crucial here.
  3430. * If group != NULL, child_func is meaningless */
  3431. #if ENABLE_HUSH_FUNCTIONS
  3432. else if (command->child_func) {
  3433. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3434. command->child_func->parent_cmd = NULL;
  3435. }
  3436. #endif
  3437. #if !BB_MMU
  3438. free(command->group_as_string);
  3439. //command->group_as_string = NULL;
  3440. #endif
  3441. for (r = command->redirects; r; r = rnext) {
  3442. debug_printf_clean(" redirect %d%s",
  3443. r->rd_fd, redir_table[r->rd_type].descrip);
  3444. /* guard against the case >$FOO, where foo is unset or blank */
  3445. if (r->rd_filename) {
  3446. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3447. free(r->rd_filename);
  3448. //r->rd_filename = NULL;
  3449. }
  3450. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3451. rnext = r->next;
  3452. free(r);
  3453. }
  3454. //command->redirects = NULL;
  3455. }
  3456. free(pi->cmds); /* children are an array, they get freed all at once */
  3457. //pi->cmds = NULL;
  3458. #if ENABLE_HUSH_JOB
  3459. free(pi->cmdtext);
  3460. //pi->cmdtext = NULL;
  3461. #endif
  3462. next = pi->next;
  3463. free(pi);
  3464. return next;
  3465. }
  3466. static void free_pipe_list(struct pipe *pi)
  3467. {
  3468. while (pi) {
  3469. #if HAS_KEYWORDS
  3470. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3471. #endif
  3472. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3473. pi = free_pipe(pi);
  3474. }
  3475. }
  3476. /*
  3477. * Parsing routines
  3478. */
  3479. #ifndef debug_print_tree
  3480. static void debug_print_tree(struct pipe *pi, int lvl)
  3481. {
  3482. static const char *const PIPE[] ALIGN_PTR = {
  3483. [PIPE_SEQ] = "SEQ",
  3484. [PIPE_AND] = "AND",
  3485. [PIPE_OR ] = "OR" ,
  3486. [PIPE_BG ] = "BG" ,
  3487. };
  3488. static const char *RES[] = {
  3489. [RES_NONE ] = "NONE" ,
  3490. # if ENABLE_HUSH_IF
  3491. [RES_IF ] = "IF" ,
  3492. [RES_THEN ] = "THEN" ,
  3493. [RES_ELIF ] = "ELIF" ,
  3494. [RES_ELSE ] = "ELSE" ,
  3495. [RES_FI ] = "FI" ,
  3496. # endif
  3497. # if ENABLE_HUSH_LOOPS
  3498. [RES_FOR ] = "FOR" ,
  3499. [RES_WHILE] = "WHILE",
  3500. [RES_UNTIL] = "UNTIL",
  3501. [RES_DO ] = "DO" ,
  3502. [RES_DONE ] = "DONE" ,
  3503. # endif
  3504. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3505. [RES_IN ] = "IN" ,
  3506. # endif
  3507. # if ENABLE_HUSH_CASE
  3508. [RES_CASE ] = "CASE" ,
  3509. [RES_CASE_IN ] = "CASE_IN" ,
  3510. [RES_MATCH] = "MATCH",
  3511. [RES_CASE_BODY] = "CASE_BODY",
  3512. [RES_ESAC ] = "ESAC" ,
  3513. # endif
  3514. [RES_XXXX ] = "XXXX" ,
  3515. [RES_SNTX ] = "SNTX" ,
  3516. };
  3517. static const char *const CMDTYPE[] ALIGN_PTR = {
  3518. "{}",
  3519. "()",
  3520. "[noglob]",
  3521. # if ENABLE_HUSH_FUNCTIONS
  3522. "func()",
  3523. # endif
  3524. };
  3525. int pin, prn;
  3526. pin = 0;
  3527. while (pi) {
  3528. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3529. lvl*2, "",
  3530. pin,
  3531. pi->num_cmds,
  3532. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3533. RES[pi->res_word],
  3534. pi->followup, PIPE[pi->followup]
  3535. );
  3536. prn = 0;
  3537. while (prn < pi->num_cmds) {
  3538. struct command *command = &pi->cmds[prn];
  3539. char **argv = command->argv;
  3540. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3541. lvl*2, "", prn,
  3542. command->assignment_cnt);
  3543. # if ENABLE_HUSH_LINENO_VAR
  3544. fdprintf(2, " LINENO:%u", command->lineno);
  3545. # endif
  3546. if (command->group) {
  3547. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3548. CMDTYPE[command->cmd_type],
  3549. argv
  3550. # if !BB_MMU
  3551. , " group_as_string:", command->group_as_string
  3552. # else
  3553. , "", ""
  3554. # endif
  3555. );
  3556. debug_print_tree(command->group, lvl+1);
  3557. prn++;
  3558. continue;
  3559. }
  3560. if (argv) while (*argv) {
  3561. fdprintf(2, " '%s'", *argv);
  3562. argv++;
  3563. }
  3564. if (command->redirects)
  3565. fdprintf(2, " {redir}");
  3566. fdprintf(2, "\n");
  3567. prn++;
  3568. }
  3569. pi = pi->next;
  3570. pin++;
  3571. }
  3572. }
  3573. #endif /* debug_print_tree */
  3574. static struct pipe *new_pipe(void)
  3575. {
  3576. struct pipe *pi;
  3577. pi = xzalloc(sizeof(struct pipe));
  3578. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3579. return pi;
  3580. }
  3581. /* Command (member of a pipe) is complete, or we start a new pipe
  3582. * if ctx->command is NULL.
  3583. * No errors possible here.
  3584. */
  3585. static int done_command(struct parse_context *ctx)
  3586. {
  3587. /* The command is really already in the pipe structure, so
  3588. * advance the pipe counter and make a new, null command. */
  3589. struct pipe *pi = ctx->pipe;
  3590. struct command *command = ctx->command;
  3591. #if 0 /* Instead we emit error message at run time */
  3592. if (ctx->pending_redirect) {
  3593. /* For example, "cmd >" (no filename to redirect to) */
  3594. syntax_error("invalid redirect");
  3595. ctx->pending_redirect = NULL;
  3596. }
  3597. #endif
  3598. if (command) {
  3599. if (IS_NULL_CMD(command)) {
  3600. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3601. goto clear_and_ret;
  3602. }
  3603. pi->num_cmds++;
  3604. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3605. //debug_print_tree(ctx->list_head, 20);
  3606. } else {
  3607. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3608. }
  3609. /* Only real trickiness here is that the uncommitted
  3610. * command structure is not counted in pi->num_cmds. */
  3611. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3612. ctx->command = command = &pi->cmds[pi->num_cmds];
  3613. clear_and_ret:
  3614. memset(command, 0, sizeof(*command));
  3615. #if ENABLE_HUSH_LINENO_VAR
  3616. command->lineno = G.parse_lineno;
  3617. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3618. #endif
  3619. return pi->num_cmds; /* used only for 0/nonzero check */
  3620. }
  3621. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3622. {
  3623. int not_null;
  3624. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3625. /* Close previous command */
  3626. not_null = done_command(ctx);
  3627. #if HAS_KEYWORDS
  3628. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3629. ctx->ctx_inverted = 0;
  3630. ctx->pipe->res_word = ctx->ctx_res_w;
  3631. #endif
  3632. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3633. /* Necessary since && and || have precedence over &:
  3634. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3635. * in a backgrounded subshell.
  3636. */
  3637. struct pipe *pi;
  3638. struct command *command;
  3639. /* Is this actually this construct, all pipes end with && or ||? */
  3640. pi = ctx->list_head;
  3641. while (pi != ctx->pipe) {
  3642. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3643. goto no_conv;
  3644. pi = pi->next;
  3645. }
  3646. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3647. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3648. pi = xzalloc(sizeof(*pi));
  3649. pi->followup = PIPE_BG;
  3650. pi->num_cmds = 1;
  3651. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3652. command = &pi->cmds[0];
  3653. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3654. command->cmd_type = CMD_NORMAL;
  3655. command->group = ctx->list_head;
  3656. #if !BB_MMU
  3657. command->group_as_string = xstrndup(
  3658. ctx->as_string.data,
  3659. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3660. );
  3661. #endif
  3662. /* Replace all pipes in ctx with one newly created */
  3663. ctx->list_head = ctx->pipe = pi;
  3664. /* for cases like "cmd && &", do not be tricked by last command
  3665. * being null - the entire {...} & is NOT null! */
  3666. not_null = 1;
  3667. } else {
  3668. no_conv:
  3669. ctx->pipe->followup = type;
  3670. }
  3671. /* Without this check, even just <enter> on command line generates
  3672. * tree of three NOPs (!). Which is harmless but annoying.
  3673. * IOW: it is safe to do it unconditionally. */
  3674. if (not_null
  3675. #if ENABLE_HUSH_IF
  3676. || ctx->ctx_res_w == RES_FI
  3677. #endif
  3678. #if ENABLE_HUSH_LOOPS
  3679. || ctx->ctx_res_w == RES_DONE
  3680. || ctx->ctx_res_w == RES_FOR
  3681. || ctx->ctx_res_w == RES_IN
  3682. #endif
  3683. #if ENABLE_HUSH_CASE
  3684. || ctx->ctx_res_w == RES_ESAC
  3685. #endif
  3686. ) {
  3687. struct pipe *new_p;
  3688. debug_printf_parse("done_pipe: adding new pipe: "
  3689. "not_null:%d ctx->ctx_res_w:%d\n",
  3690. not_null, ctx->ctx_res_w);
  3691. new_p = new_pipe();
  3692. ctx->pipe->next = new_p;
  3693. ctx->pipe = new_p;
  3694. /* RES_THEN, RES_DO etc are "sticky" -
  3695. * they remain set for pipes inside if/while.
  3696. * This is used to control execution.
  3697. * RES_FOR and RES_IN are NOT sticky (needed to support
  3698. * cases where variable or value happens to match a keyword):
  3699. */
  3700. #if ENABLE_HUSH_LOOPS
  3701. if (ctx->ctx_res_w == RES_FOR
  3702. || ctx->ctx_res_w == RES_IN)
  3703. ctx->ctx_res_w = RES_NONE;
  3704. #endif
  3705. #if ENABLE_HUSH_CASE
  3706. if (ctx->ctx_res_w == RES_MATCH)
  3707. ctx->ctx_res_w = RES_CASE_BODY;
  3708. if (ctx->ctx_res_w == RES_CASE)
  3709. ctx->ctx_res_w = RES_CASE_IN;
  3710. #endif
  3711. ctx->command = NULL; /* trick done_command below */
  3712. /* Create the memory for command, roughly:
  3713. * ctx->pipe->cmds = new struct command;
  3714. * ctx->command = &ctx->pipe->cmds[0];
  3715. */
  3716. done_command(ctx);
  3717. //debug_print_tree(ctx->list_head, 10);
  3718. }
  3719. debug_printf_parse("done_pipe return\n");
  3720. }
  3721. static void initialize_context(struct parse_context *ctx)
  3722. {
  3723. memset(ctx, 0, sizeof(*ctx));
  3724. if (MAYBE_ASSIGNMENT != 0)
  3725. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3726. ctx->pipe = ctx->list_head = new_pipe();
  3727. /* Create the memory for command, roughly:
  3728. * ctx->pipe->cmds = new struct command;
  3729. * ctx->command = &ctx->pipe->cmds[0];
  3730. */
  3731. done_command(ctx);
  3732. }
  3733. /* If a reserved word is found and processed, parse context is modified
  3734. * and 1 is returned.
  3735. */
  3736. #if HAS_KEYWORDS
  3737. struct reserved_combo {
  3738. char literal[6];
  3739. unsigned char res;
  3740. unsigned char assignment_flag;
  3741. uint32_t flag;
  3742. };
  3743. enum {
  3744. FLAG_END = (1 << RES_NONE ),
  3745. # if ENABLE_HUSH_IF
  3746. FLAG_IF = (1 << RES_IF ),
  3747. FLAG_THEN = (1 << RES_THEN ),
  3748. FLAG_ELIF = (1 << RES_ELIF ),
  3749. FLAG_ELSE = (1 << RES_ELSE ),
  3750. FLAG_FI = (1 << RES_FI ),
  3751. # endif
  3752. # if ENABLE_HUSH_LOOPS
  3753. FLAG_FOR = (1 << RES_FOR ),
  3754. FLAG_WHILE = (1 << RES_WHILE),
  3755. FLAG_UNTIL = (1 << RES_UNTIL),
  3756. FLAG_DO = (1 << RES_DO ),
  3757. FLAG_DONE = (1 << RES_DONE ),
  3758. FLAG_IN = (1 << RES_IN ),
  3759. # endif
  3760. # if ENABLE_HUSH_CASE
  3761. FLAG_MATCH = (1 << RES_MATCH),
  3762. FLAG_ESAC = (1 << RES_ESAC ),
  3763. # endif
  3764. FLAG_START = (1 << RES_XXXX ),
  3765. };
  3766. static const struct reserved_combo* match_reserved_word(o_string *word)
  3767. {
  3768. /* Mostly a list of accepted follow-up reserved words.
  3769. * FLAG_END means we are done with the sequence, and are ready
  3770. * to turn the compound list into a command.
  3771. * FLAG_START means the word must start a new compound list.
  3772. */
  3773. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3774. # if ENABLE_HUSH_IF
  3775. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3776. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3777. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3778. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3779. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3780. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3781. # endif
  3782. # if ENABLE_HUSH_LOOPS
  3783. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3784. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3785. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3786. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3787. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3788. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3789. # endif
  3790. # if ENABLE_HUSH_CASE
  3791. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3792. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3793. # endif
  3794. };
  3795. const struct reserved_combo *r;
  3796. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3797. if (strcmp(word->data, r->literal) == 0)
  3798. return r;
  3799. }
  3800. return NULL;
  3801. }
  3802. /* Return NULL: not a keyword, else: keyword
  3803. */
  3804. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3805. {
  3806. # if ENABLE_HUSH_CASE
  3807. static const struct reserved_combo reserved_match = {
  3808. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3809. };
  3810. # endif
  3811. const struct reserved_combo *r;
  3812. if (ctx->word.has_quoted_part)
  3813. return 0;
  3814. r = match_reserved_word(&ctx->word);
  3815. if (!r)
  3816. return r; /* NULL */
  3817. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3818. # if ENABLE_HUSH_CASE
  3819. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3820. /* "case word IN ..." - IN part starts first MATCH part */
  3821. r = &reserved_match;
  3822. } else
  3823. # endif
  3824. if (r->flag == 0) { /* '!' */
  3825. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3826. syntax_error("! ! command");
  3827. ctx->ctx_res_w = RES_SNTX;
  3828. }
  3829. ctx->ctx_inverted = 1;
  3830. return r;
  3831. }
  3832. if (r->flag & FLAG_START) {
  3833. struct parse_context *old;
  3834. old = xmemdup(ctx, sizeof(*ctx));
  3835. debug_printf_parse("push stack %p\n", old);
  3836. initialize_context(ctx);
  3837. ctx->stack = old;
  3838. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3839. syntax_error_at(ctx->word.data);
  3840. ctx->ctx_res_w = RES_SNTX;
  3841. return r;
  3842. } else {
  3843. /* "{...} fi" is ok. "{...} if" is not
  3844. * Example:
  3845. * if { echo foo; } then { echo bar; } fi */
  3846. if (ctx->command->group)
  3847. done_pipe(ctx, PIPE_SEQ);
  3848. }
  3849. ctx->ctx_res_w = r->res;
  3850. ctx->old_flag = r->flag;
  3851. ctx->is_assignment = r->assignment_flag;
  3852. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3853. if (ctx->old_flag & FLAG_END) {
  3854. struct parse_context *old;
  3855. done_pipe(ctx, PIPE_SEQ);
  3856. debug_printf_parse("pop stack %p\n", ctx->stack);
  3857. old = ctx->stack;
  3858. old->command->group = ctx->list_head;
  3859. old->command->cmd_type = CMD_NORMAL;
  3860. # if !BB_MMU
  3861. /* At this point, the compound command's string is in
  3862. * ctx->as_string... except for the leading keyword!
  3863. * Consider this example: "echo a | if true; then echo a; fi"
  3864. * ctx->as_string will contain "true; then echo a; fi",
  3865. * with "if " remaining in old->as_string!
  3866. */
  3867. {
  3868. char *str;
  3869. int len = old->as_string.length;
  3870. /* Concatenate halves */
  3871. o_addstr(&old->as_string, ctx->as_string.data);
  3872. o_free(&ctx->as_string);
  3873. /* Find where leading keyword starts in first half */
  3874. str = old->as_string.data + len;
  3875. if (str > old->as_string.data)
  3876. str--; /* skip whitespace after keyword */
  3877. while (str > old->as_string.data && isalpha(str[-1]))
  3878. str--;
  3879. /* Ugh, we're done with this horrid hack */
  3880. old->command->group_as_string = xstrdup(str);
  3881. debug_printf_parse("pop, remembering as:'%s'\n",
  3882. old->command->group_as_string);
  3883. }
  3884. # endif
  3885. *ctx = *old; /* physical copy */
  3886. free(old);
  3887. }
  3888. return r;
  3889. }
  3890. #endif /* HAS_KEYWORDS */
  3891. /* Word is complete, look at it and update parsing context.
  3892. * Normal return is 0. Syntax errors return 1.
  3893. * Note: on return, word is reset, but not o_free'd!
  3894. */
  3895. static int done_word(struct parse_context *ctx)
  3896. {
  3897. struct command *command = ctx->command;
  3898. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3899. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3900. debug_printf_parse("done_word return 0: true null, ignored\n");
  3901. return 0;
  3902. }
  3903. if (ctx->pending_redirect) {
  3904. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3905. * only if run as "bash", not "sh" */
  3906. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3907. * "2.7 Redirection
  3908. * If the redirection operator is "<<" or "<<-", the word
  3909. * that follows the redirection operator shall be
  3910. * subjected to quote removal; it is unspecified whether
  3911. * any of the other expansions occur. For the other
  3912. * redirection operators, the word that follows the
  3913. * redirection operator shall be subjected to tilde
  3914. * expansion, parameter expansion, command substitution,
  3915. * arithmetic expansion, and quote removal.
  3916. * Pathname expansion shall not be performed
  3917. * on the word by a non-interactive shell; an interactive
  3918. * shell may perform it, but shall do so only when
  3919. * the expansion would result in one word."
  3920. */
  3921. //bash does not do parameter/command substitution or arithmetic expansion
  3922. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3923. // as written:
  3924. // <<EOF$t
  3925. // <<EOF$((1))
  3926. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3927. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3928. /* Cater for >\file case:
  3929. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3930. * Same with heredocs:
  3931. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3932. */
  3933. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3934. unbackslash(ctx->pending_redirect->rd_filename);
  3935. /* Is it <<"HEREDOC"? */
  3936. if (ctx->word.has_quoted_part) {
  3937. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3938. }
  3939. }
  3940. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3941. ctx->pending_redirect = NULL;
  3942. } else {
  3943. #if HAS_KEYWORDS
  3944. # if ENABLE_HUSH_CASE
  3945. if (ctx->ctx_dsemicolon
  3946. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3947. ) {
  3948. /* already done when ctx_dsemicolon was set to 1: */
  3949. /* ctx->ctx_res_w = RES_MATCH; */
  3950. ctx->ctx_dsemicolon = 0;
  3951. } else
  3952. # endif
  3953. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3954. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3955. && strcmp(ctx->word.data, "]]") == 0
  3956. ) {
  3957. /* allow "[[ ]] >file" etc */
  3958. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3959. } else
  3960. # endif
  3961. if (!command->argv /* if it's the first word... */
  3962. # if ENABLE_HUSH_LOOPS
  3963. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3964. && ctx->ctx_res_w != RES_IN
  3965. # endif
  3966. # if ENABLE_HUSH_CASE
  3967. && ctx->ctx_res_w != RES_CASE
  3968. # endif
  3969. ) {
  3970. const struct reserved_combo *reserved;
  3971. reserved = reserved_word(ctx);
  3972. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3973. if (reserved) {
  3974. # if ENABLE_HUSH_LINENO_VAR
  3975. /* Case:
  3976. * "while ...; do
  3977. * cmd ..."
  3978. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3979. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3980. */
  3981. if (0
  3982. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3983. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3984. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3985. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3986. ) {
  3987. done_pipe(ctx, PIPE_SEQ);
  3988. }
  3989. # endif
  3990. o_reset_to_empty_unquoted(&ctx->word);
  3991. debug_printf_parse("done_word return %d\n",
  3992. (ctx->ctx_res_w == RES_SNTX));
  3993. return (ctx->ctx_res_w == RES_SNTX);
  3994. }
  3995. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3996. if (strcmp(ctx->word.data, "[[") == 0) {
  3997. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3998. } else
  3999. # endif
  4000. # if defined(CMD_SINGLEWORD_NOGLOB)
  4001. if (0
  4002. /* In bash, local/export/readonly are special, args
  4003. * are assignments and therefore expansion of them
  4004. * should be "one-word" expansion:
  4005. * $ export i=`echo 'a b'` # one arg: "i=a b"
  4006. * compare with:
  4007. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  4008. * ls: cannot access i=a: No such file or directory
  4009. * ls: cannot access b: No such file or directory
  4010. * Note: bash 3.2.33(1) does this only if export word
  4011. * itself is not quoted:
  4012. * $ export i=`echo 'aaa bbb'`; echo "$i"
  4013. * aaa bbb
  4014. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  4015. * aaa
  4016. */
  4017. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  4018. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  4019. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  4020. ) {
  4021. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  4022. }
  4023. # else
  4024. { /* empty block to pair "if ... else" */ }
  4025. # endif
  4026. }
  4027. #endif /* HAS_KEYWORDS */
  4028. if (command->group) {
  4029. /* "{ echo foo; } echo bar" - bad */
  4030. syntax_error_at(ctx->word.data);
  4031. debug_printf_parse("done_word return 1: syntax error, "
  4032. "groups and arglists don't mix\n");
  4033. return 1;
  4034. }
  4035. /* If this word wasn't an assignment, next ones definitely
  4036. * can't be assignments. Even if they look like ones. */
  4037. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  4038. && ctx->is_assignment != WORD_IS_KEYWORD
  4039. ) {
  4040. ctx->is_assignment = NOT_ASSIGNMENT;
  4041. } else {
  4042. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  4043. command->assignment_cnt++;
  4044. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  4045. }
  4046. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  4047. ctx->is_assignment = MAYBE_ASSIGNMENT;
  4048. }
  4049. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  4050. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  4051. debug_print_strings("word appended to argv", command->argv);
  4052. }
  4053. #if ENABLE_HUSH_LOOPS
  4054. if (ctx->ctx_res_w == RES_FOR) {
  4055. if (ctx->word.has_quoted_part
  4056. || endofname(command->argv[0])[0] != '\0'
  4057. ) {
  4058. /* bash says just "not a valid identifier" */
  4059. syntax_error("bad for loop variable");
  4060. return 1;
  4061. }
  4062. /* Force FOR to have just one word (variable name) */
  4063. /* NB: basically, this makes hush see "for v in ..."
  4064. * syntax as if it is "for v; in ...". FOR and IN become
  4065. * two pipe structs in parse tree. */
  4066. done_pipe(ctx, PIPE_SEQ);
  4067. }
  4068. #endif
  4069. #if ENABLE_HUSH_CASE
  4070. /* Force CASE to have just one word */
  4071. if (ctx->ctx_res_w == RES_CASE) {
  4072. done_pipe(ctx, PIPE_SEQ);
  4073. }
  4074. #endif
  4075. o_reset_to_empty_unquoted(&ctx->word);
  4076. debug_printf_parse("done_word return 0\n");
  4077. return 0;
  4078. }
  4079. /* Peek ahead in the input to find out if we have a "&n" construct,
  4080. * as in "2>&1", that represents duplicating a file descriptor.
  4081. * Return:
  4082. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4083. * REDIRFD_SYNTAX_ERR if syntax error,
  4084. * REDIRFD_TO_FILE if no & was seen,
  4085. * or the number found.
  4086. */
  4087. #if BB_MMU
  4088. #define parse_redir_right_fd(as_string, input) \
  4089. parse_redir_right_fd(input)
  4090. #endif
  4091. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4092. {
  4093. int ch, d, ok;
  4094. ch = i_peek(input);
  4095. if (ch != '&')
  4096. return REDIRFD_TO_FILE;
  4097. ch = i_getch(input); /* get the & */
  4098. nommu_addchr(as_string, ch);
  4099. ch = i_peek(input);
  4100. if (ch == '-') {
  4101. ch = i_getch(input);
  4102. nommu_addchr(as_string, ch);
  4103. return REDIRFD_CLOSE;
  4104. }
  4105. d = 0;
  4106. ok = 0;
  4107. while (ch != EOF && isdigit(ch)) {
  4108. d = d*10 + (ch-'0');
  4109. ok = 1;
  4110. ch = i_getch(input);
  4111. nommu_addchr(as_string, ch);
  4112. ch = i_peek(input);
  4113. }
  4114. if (ok) return d;
  4115. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4116. bb_simple_error_msg("ambiguous redirect");
  4117. return REDIRFD_SYNTAX_ERR;
  4118. }
  4119. /* Return code is 0 normal, 1 if a syntax error is detected
  4120. */
  4121. static int parse_redirect(struct parse_context *ctx,
  4122. int fd,
  4123. redir_type style,
  4124. struct in_str *input)
  4125. {
  4126. struct command *command = ctx->command;
  4127. struct redir_struct *redir;
  4128. struct redir_struct **redirp;
  4129. int dup_num;
  4130. dup_num = REDIRFD_TO_FILE;
  4131. if (style != REDIRECT_HEREDOC) {
  4132. /* Check for a '>&1' type redirect */
  4133. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4134. if (dup_num == REDIRFD_SYNTAX_ERR)
  4135. return 1;
  4136. } else {
  4137. int ch = i_peek_and_eat_bkslash_nl(input);
  4138. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4139. if (dup_num) { /* <<-... */
  4140. ch = i_getch(input);
  4141. nommu_addchr(&ctx->as_string, ch);
  4142. ch = i_peek(input);
  4143. }
  4144. }
  4145. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4146. int ch = i_peek_and_eat_bkslash_nl(input);
  4147. if (ch == '|') {
  4148. /* >|FILE redirect ("clobbering" >).
  4149. * Since we do not support "set -o noclobber" yet,
  4150. * >| and > are the same for now. Just eat |.
  4151. */
  4152. ch = i_getch(input);
  4153. nommu_addchr(&ctx->as_string, ch);
  4154. }
  4155. }
  4156. /* Create a new redir_struct and append it to the linked list */
  4157. redirp = &command->redirects;
  4158. while ((redir = *redirp) != NULL) {
  4159. redirp = &(redir->next);
  4160. }
  4161. *redirp = redir = xzalloc(sizeof(*redir));
  4162. /* redir->next = NULL; */
  4163. /* redir->rd_filename = NULL; */
  4164. redir->rd_type = style;
  4165. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4166. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4167. redir_table[style].descrip);
  4168. redir->rd_dup = dup_num;
  4169. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4170. /* Erik had a check here that the file descriptor in question
  4171. * is legit; I postpone that to "run time"
  4172. * A "-" representation of "close me" shows up as a -3 here */
  4173. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4174. redir->rd_fd, redir->rd_dup);
  4175. } else {
  4176. #if 0 /* Instead we emit error message at run time */
  4177. if (ctx->pending_redirect) {
  4178. /* For example, "cmd > <file" */
  4179. syntax_error("invalid redirect");
  4180. }
  4181. #endif
  4182. /* Set ctx->pending_redirect, so we know what to do at the
  4183. * end of the next parsed word. */
  4184. ctx->pending_redirect = redir;
  4185. }
  4186. return 0;
  4187. }
  4188. /* If a redirect is immediately preceded by a number, that number is
  4189. * supposed to tell which file descriptor to redirect. This routine
  4190. * looks for such preceding numbers. In an ideal world this routine
  4191. * needs to handle all the following classes of redirects...
  4192. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4193. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4194. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4195. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4196. *
  4197. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4198. * "2.7 Redirection
  4199. * ... If n is quoted, the number shall not be recognized as part of
  4200. * the redirection expression. For example:
  4201. * echo \2>a
  4202. * writes the character 2 into file a"
  4203. * We are getting it right by setting ->has_quoted_part on any \<char>
  4204. *
  4205. * A -1 return means no valid number was found,
  4206. * the caller should use the appropriate default for this redirection.
  4207. */
  4208. static int redirect_opt_num(o_string *o)
  4209. {
  4210. int num;
  4211. if (o->data == NULL)
  4212. return -1;
  4213. num = bb_strtou(o->data, NULL, 10);
  4214. if (errno || num < 0)
  4215. return -1;
  4216. o_reset_to_empty_unquoted(o);
  4217. return num;
  4218. }
  4219. #if BB_MMU
  4220. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4221. fetch_till_str(input, word, skip_tabs)
  4222. #endif
  4223. static char *fetch_till_str(o_string *as_string,
  4224. struct in_str *input,
  4225. const char *word,
  4226. int heredoc_flags)
  4227. {
  4228. o_string heredoc = NULL_O_STRING;
  4229. unsigned past_EOL;
  4230. int prev = 0; /* not \ */
  4231. int ch;
  4232. /* Starting with "" is necessary for this case:
  4233. * cat <<EOF
  4234. *
  4235. * xxx
  4236. * EOF
  4237. */
  4238. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4239. goto jump_in;
  4240. while (1) {
  4241. ch = i_getch(input);
  4242. if (ch != EOF)
  4243. nommu_addchr(as_string, ch);
  4244. if (ch == '\n' || ch == EOF) {
  4245. check_heredoc_end:
  4246. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4247. /* End-of-line, and not a line continuation */
  4248. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4249. heredoc.data[past_EOL] = '\0';
  4250. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4251. return heredoc.data;
  4252. }
  4253. if (ch == '\n') {
  4254. /* This is a new line.
  4255. * Remember position and backslash-escaping status.
  4256. */
  4257. o_addchr(&heredoc, ch);
  4258. prev = ch;
  4259. jump_in:
  4260. past_EOL = heredoc.length;
  4261. /* Get 1st char of next line, possibly skipping leading tabs */
  4262. do {
  4263. ch = i_getch(input);
  4264. if (ch != EOF)
  4265. nommu_addchr(as_string, ch);
  4266. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4267. /* If this immediately ended the line,
  4268. * go back to end-of-line checks.
  4269. */
  4270. if (ch == '\n')
  4271. goto check_heredoc_end;
  4272. }
  4273. } else {
  4274. /* Backslash-line continuation in an unquoted
  4275. * heredoc. This does not need special handling
  4276. * for heredoc body (unquoted heredocs are
  4277. * expanded on "execution" and that would take
  4278. * care of this case too), but not the case
  4279. * of line continuation *in terminator*:
  4280. * cat <<EOF
  4281. * Ok1
  4282. * EO\
  4283. * F
  4284. */
  4285. heredoc.data[--heredoc.length] = '\0';
  4286. prev = 0; /* not '\' */
  4287. continue;
  4288. }
  4289. }
  4290. if (ch == EOF) {
  4291. o_free(&heredoc);
  4292. return NULL; /* error */
  4293. }
  4294. o_addchr(&heredoc, ch);
  4295. nommu_addchr(as_string, ch);
  4296. if (prev == '\\' && ch == '\\')
  4297. /* Correctly handle foo\\<eol> (not a line cont.) */
  4298. prev = 0; /* not '\' */
  4299. else
  4300. prev = ch;
  4301. }
  4302. }
  4303. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4304. * and load them all. There should be exactly heredoc_cnt of them.
  4305. */
  4306. #if BB_MMU
  4307. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4308. fetch_heredocs(pi, heredoc_cnt, input)
  4309. #endif
  4310. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4311. {
  4312. while (pi && heredoc_cnt) {
  4313. int i;
  4314. struct command *cmd = pi->cmds;
  4315. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4316. pi->num_cmds,
  4317. cmd->argv ? cmd->argv[0] : "NONE"
  4318. );
  4319. for (i = 0; i < pi->num_cmds; i++) {
  4320. struct redir_struct *redir = cmd->redirects;
  4321. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4322. i, cmd->argv ? cmd->argv[0] : "NONE");
  4323. while (redir) {
  4324. if (redir->rd_type == REDIRECT_HEREDOC) {
  4325. char *p;
  4326. redir->rd_type = REDIRECT_HEREDOC2;
  4327. /* redir->rd_dup is (ab)used to indicate <<- */
  4328. p = fetch_till_str(as_string, input,
  4329. redir->rd_filename, redir->rd_dup);
  4330. if (!p) {
  4331. syntax_error("unexpected EOF in here document");
  4332. return -1;
  4333. }
  4334. free(redir->rd_filename);
  4335. redir->rd_filename = p;
  4336. heredoc_cnt--;
  4337. }
  4338. redir = redir->next;
  4339. }
  4340. if (cmd->group) {
  4341. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4342. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4343. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4344. if (heredoc_cnt < 0)
  4345. return heredoc_cnt; /* error */
  4346. }
  4347. cmd++;
  4348. }
  4349. pi = pi->next;
  4350. }
  4351. return heredoc_cnt;
  4352. }
  4353. static int run_list(struct pipe *pi);
  4354. #if BB_MMU
  4355. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4356. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4357. #endif
  4358. static struct pipe *parse_stream(char **pstring,
  4359. int *heredoc_cnt_ptr,
  4360. struct in_str *input,
  4361. int end_trigger);
  4362. /* Returns number of heredocs not yet consumed,
  4363. * or -1 on error.
  4364. */
  4365. static int parse_group(struct parse_context *ctx,
  4366. struct in_str *input, int ch)
  4367. {
  4368. /* ctx->word contains characters seen prior to ( or {.
  4369. * Typically it's empty, but for function defs,
  4370. * it contains function name (without '()'). */
  4371. #if BB_MMU
  4372. # define as_string NULL
  4373. #else
  4374. char *as_string = NULL;
  4375. #endif
  4376. struct pipe *pipe_list;
  4377. int heredoc_cnt = 0;
  4378. int endch;
  4379. struct command *command = ctx->command;
  4380. debug_printf_parse("parse_group entered\n");
  4381. #if ENABLE_HUSH_FUNCTIONS
  4382. if (ch == '(' && !ctx->word.has_quoted_part) {
  4383. if (ctx->word.length)
  4384. if (done_word(ctx))
  4385. return -1;
  4386. if (!command->argv)
  4387. goto skip; /* (... */
  4388. if (command->argv[1]) { /* word word ... (... */
  4389. syntax_error_unexpected_ch('(');
  4390. return -1;
  4391. }
  4392. /* it is "word(..." or "word (..." */
  4393. do
  4394. ch = i_getch(input);
  4395. while (ch == ' ' || ch == '\t');
  4396. if (ch != ')') {
  4397. syntax_error_unexpected_ch(ch);
  4398. return -1;
  4399. }
  4400. nommu_addchr(&ctx->as_string, ch);
  4401. do
  4402. ch = i_getch(input);
  4403. while (ch == ' ' || ch == '\t' || ch == '\n');
  4404. if (ch != '{' && ch != '(') {
  4405. syntax_error_unexpected_ch(ch);
  4406. return -1;
  4407. }
  4408. //bash allows functions named "123", "..", "return"!
  4409. // if (endofname(command->argv[0])[0] != '\0') {
  4410. // syntax_error("bad function name");
  4411. // return -1;
  4412. // }
  4413. nommu_addchr(&ctx->as_string, ch);
  4414. command->cmd_type = CMD_FUNCDEF;
  4415. goto skip;
  4416. }
  4417. #endif
  4418. #if 0 /* Prevented by caller */
  4419. if (command->argv /* word [word]{... */
  4420. || ctx->word.length /* word{... */
  4421. || ctx->word.has_quoted_part /* ""{... */
  4422. ) {
  4423. syntax_error(NULL);
  4424. debug_printf_parse("parse_group return -1: "
  4425. "syntax error, groups and arglists don't mix\n");
  4426. return -1;
  4427. }
  4428. #endif
  4429. IF_HUSH_FUNCTIONS(skip:)
  4430. endch = '}';
  4431. if (ch == '(') {
  4432. endch = ')';
  4433. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4434. command->cmd_type = CMD_SUBSHELL;
  4435. } else {
  4436. /* bash does not allow "{echo...", requires whitespace */
  4437. ch = i_peek(input);
  4438. if (ch != ' ' && ch != '\t' && ch != '\n'
  4439. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4440. ) {
  4441. syntax_error_unexpected_ch(ch);
  4442. return -1;
  4443. }
  4444. if (ch != '(') {
  4445. ch = i_getch(input);
  4446. nommu_addchr(&ctx->as_string, ch);
  4447. }
  4448. }
  4449. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4450. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4451. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4452. #if !BB_MMU
  4453. if (as_string)
  4454. o_addstr(&ctx->as_string, as_string);
  4455. #endif
  4456. /* empty ()/{} or parse error? */
  4457. if (!pipe_list || pipe_list == ERR_PTR) {
  4458. /* parse_stream already emitted error msg */
  4459. if (!BB_MMU)
  4460. free(as_string);
  4461. debug_printf_parse("parse_group return -1: "
  4462. "parse_stream returned %p\n", pipe_list);
  4463. return -1;
  4464. }
  4465. #if !BB_MMU
  4466. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4467. command->group_as_string = as_string;
  4468. debug_printf_parse("end of group, remembering as:'%s'\n",
  4469. command->group_as_string);
  4470. #endif
  4471. #if ENABLE_HUSH_FUNCTIONS
  4472. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4473. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4474. struct command *cmd2;
  4475. cmd2 = xzalloc(sizeof(*cmd2));
  4476. cmd2->cmd_type = CMD_SUBSHELL;
  4477. cmd2->group = pipe_list;
  4478. # if !BB_MMU
  4479. //UNTESTED!
  4480. cmd2->group_as_string = command->group_as_string;
  4481. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4482. # endif
  4483. pipe_list = new_pipe();
  4484. pipe_list->cmds = cmd2;
  4485. pipe_list->num_cmds = 1;
  4486. }
  4487. #endif
  4488. command->group = pipe_list;
  4489. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4490. return heredoc_cnt;
  4491. /* command remains "open", available for possible redirects */
  4492. #undef as_string
  4493. }
  4494. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4495. /* Subroutines for copying $(...) and `...` things */
  4496. /* '...' */
  4497. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4498. {
  4499. while (1) {
  4500. int ch = i_getch(input);
  4501. if (ch == EOF) {
  4502. syntax_error_unterm_ch('\'');
  4503. return 0;
  4504. }
  4505. if (ch == '\'')
  4506. return 1;
  4507. o_addchr(dest, ch);
  4508. }
  4509. }
  4510. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4511. {
  4512. while (1) {
  4513. int ch = i_getch(input);
  4514. if (ch == EOF) {
  4515. syntax_error_unterm_ch('\'');
  4516. return 0;
  4517. }
  4518. if (ch == '\'')
  4519. return 1;
  4520. o_addqchr(dest, ch);
  4521. }
  4522. }
  4523. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4524. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4525. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4526. {
  4527. while (1) {
  4528. int ch = i_getch(input);
  4529. if (ch == EOF) {
  4530. syntax_error_unterm_ch('"');
  4531. return 0;
  4532. }
  4533. if (ch == '"')
  4534. return 1;
  4535. if (ch == '\\') { /* \x. Copy both chars. */
  4536. o_addchr(dest, ch);
  4537. ch = i_getch(input);
  4538. }
  4539. o_addchr(dest, ch);
  4540. if (ch == '`') {
  4541. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4542. return 0;
  4543. o_addchr(dest, ch);
  4544. continue;
  4545. }
  4546. //if (ch == '$') ...
  4547. }
  4548. }
  4549. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4550. * \` quoting.
  4551. * "Within the backquoted style of command substitution, backslash
  4552. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4553. * The search for the matching backquote shall be satisfied by the first
  4554. * backquote found without a preceding backslash; during this search,
  4555. * if a non-escaped backquote is encountered within a shell comment,
  4556. * a here-document, an embedded command substitution of the $(command)
  4557. * form, or a quoted string, undefined results occur. A single-quoted
  4558. * or double-quoted string that begins, but does not end, within the
  4559. * "`...`" sequence produces undefined results."
  4560. * Example Output
  4561. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4562. */
  4563. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4564. {
  4565. while (1) {
  4566. int ch = i_getch(input);
  4567. if (ch == '`')
  4568. return 1;
  4569. if (ch == '\\') {
  4570. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4571. ch = i_getch(input);
  4572. if (ch != '`'
  4573. && ch != '$'
  4574. && ch != '\\'
  4575. && (!in_dquote || ch != '"')
  4576. ) {
  4577. o_addchr(dest, '\\');
  4578. }
  4579. }
  4580. if (ch == EOF) {
  4581. syntax_error_unterm_ch('`');
  4582. return 0;
  4583. }
  4584. o_addchr(dest, ch);
  4585. }
  4586. }
  4587. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4588. * quoting and nested ()s.
  4589. * "With the $(command) style of command substitution, all characters
  4590. * following the open parenthesis to the matching closing parenthesis
  4591. * constitute the command. Any valid shell script can be used for command,
  4592. * except a script consisting solely of redirections which produces
  4593. * unspecified results."
  4594. * Example Output
  4595. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4596. * echo $(echo 'TEST)' BEST) TEST) BEST
  4597. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4598. *
  4599. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4600. * can contain arbitrary constructs, just like $(cmd).
  4601. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4602. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4603. */
  4604. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4605. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4606. {
  4607. int ch;
  4608. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4609. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4610. char end_char2 = end_ch >> 8;
  4611. # endif
  4612. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4613. # if ENABLE_HUSH_INTERACTIVE
  4614. G.promptmode = 1; /* PS2 */
  4615. # endif
  4616. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4617. while (1) {
  4618. ch = i_getch(input);
  4619. if (ch == EOF) {
  4620. syntax_error_unterm_ch(end_ch);
  4621. return 0;
  4622. }
  4623. if (ch == end_ch
  4624. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4625. || ch == end_char2
  4626. # endif
  4627. ) {
  4628. if (!dbl)
  4629. break;
  4630. /* we look for closing )) of $((EXPR)) */
  4631. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4632. i_getch(input); /* eat second ')' */
  4633. break;
  4634. }
  4635. }
  4636. o_addchr(dest, ch);
  4637. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4638. if (ch == '(' || ch == '{') {
  4639. ch = (ch == '(' ? ')' : '}');
  4640. if (!add_till_closing_bracket(dest, input, ch))
  4641. return 0;
  4642. o_addchr(dest, ch);
  4643. continue;
  4644. }
  4645. if (ch == '\'') {
  4646. if (!add_till_single_quote(dest, input))
  4647. return 0;
  4648. o_addchr(dest, ch);
  4649. continue;
  4650. }
  4651. if (ch == '"') {
  4652. if (!add_till_double_quote(dest, input))
  4653. return 0;
  4654. o_addchr(dest, ch);
  4655. continue;
  4656. }
  4657. if (ch == '`') {
  4658. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4659. return 0;
  4660. o_addchr(dest, ch);
  4661. continue;
  4662. }
  4663. if (ch == '\\') {
  4664. /* \x. Copy verbatim. Important for \(, \) */
  4665. ch = i_getch(input);
  4666. if (ch == EOF) {
  4667. syntax_error_unterm_ch(end_ch);
  4668. return 0;
  4669. }
  4670. # if 0
  4671. if (ch == '\n') {
  4672. /* "backslash+newline", ignore both */
  4673. o_delchr(dest); /* undo insertion of '\' */
  4674. continue;
  4675. }
  4676. # endif
  4677. o_addchr(dest, ch);
  4678. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4679. continue;
  4680. }
  4681. }
  4682. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4683. return ch;
  4684. }
  4685. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4686. #if BASH_DOLLAR_SQUOTE
  4687. /* Return code: 1 for "found and parsed", 0 for "seen something else" */
  4688. # if BB_MMU
  4689. #define parse_dollar_squote(as_string, dest, input) \
  4690. parse_dollar_squote(dest, input)
  4691. #define as_string NULL
  4692. # endif
  4693. static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
  4694. {
  4695. int start;
  4696. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4697. debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
  4698. if (ch != '\'')
  4699. return 0;
  4700. dest->has_quoted_part = 1;
  4701. start = dest->length;
  4702. ch = i_getch(input); /* eat ' */
  4703. nommu_addchr(as_string, ch);
  4704. while (1) {
  4705. ch = i_getch(input);
  4706. nommu_addchr(as_string, ch);
  4707. if (ch == EOF) {
  4708. syntax_error_unterm_ch('\'');
  4709. return 0;
  4710. }
  4711. if (ch == '\'')
  4712. break;
  4713. if (ch == SPECIAL_VAR_SYMBOL) {
  4714. /* Convert raw ^C to corresponding special variable reference */
  4715. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4716. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4717. /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
  4718. } else if (ch == '\\') {
  4719. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  4720. ch = i_getch(input);
  4721. nommu_addchr(as_string, ch);
  4722. if (strchr(C_escapes, ch)) {
  4723. char buf[4];
  4724. char *p = buf;
  4725. int cnt = 2;
  4726. buf[0] = ch;
  4727. if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
  4728. do {
  4729. ch = i_peek(input);
  4730. if ((unsigned char)(ch - '0') > 7)
  4731. break;
  4732. *++p = ch = i_getch(input);
  4733. nommu_addchr(as_string, ch);
  4734. } while (--cnt != 0);
  4735. } else if (ch == 'x') { /* \xHH */
  4736. do {
  4737. ch = i_peek(input);
  4738. if (!isxdigit(ch))
  4739. break;
  4740. *++p = ch = i_getch(input);
  4741. nommu_addchr(as_string, ch);
  4742. } while (--cnt != 0);
  4743. if (cnt == 2) { /* \x but next char is "bad" */
  4744. ch = 'x';
  4745. goto unrecognized;
  4746. }
  4747. } /* else simple seq like \\ or \t */
  4748. *++p = '\0';
  4749. p = buf;
  4750. ch = bb_process_escape_sequence((void*)&p);
  4751. //bb_error_msg("buf:'%s' ch:%x", buf, ch);
  4752. if (ch == '\0')
  4753. continue; /* bash compat: $'...\0...' emits nothing */
  4754. } else { /* unrecognized "\z": encode both chars unless ' or " */
  4755. if (ch != '\'' && ch != '"') {
  4756. unrecognized:
  4757. o_addqchr(dest, '\\');
  4758. }
  4759. }
  4760. } /* if (\...) */
  4761. o_addqchr(dest, ch);
  4762. }
  4763. if (dest->length == start) {
  4764. /* $'', $'\0', $'\000\x00' and the like */
  4765. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4766. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4767. }
  4768. return 1;
  4769. # undef as_string
  4770. }
  4771. #else
  4772. # define parse_dollar_squote(as_string, dest, input) 0
  4773. #endif /* BASH_DOLLAR_SQUOTE */
  4774. /* Return code: 0 for OK, 1 for syntax error */
  4775. #if BB_MMU
  4776. #define parse_dollar(as_string, dest, input, quote_mask) \
  4777. parse_dollar(dest, input, quote_mask)
  4778. #define as_string NULL
  4779. #endif
  4780. static int parse_dollar(o_string *as_string,
  4781. o_string *dest,
  4782. struct in_str *input, unsigned char quote_mask)
  4783. {
  4784. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4785. debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
  4786. if (isalpha(ch)) {
  4787. make_var:
  4788. ch = i_getch(input);
  4789. nommu_addchr(as_string, ch);
  4790. /*make_var1:*/
  4791. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4792. while (1) {
  4793. debug_printf_parse(": '%c'\n", ch);
  4794. o_addchr(dest, ch | quote_mask);
  4795. quote_mask = 0;
  4796. ch = i_peek_and_eat_bkslash_nl(input);
  4797. if (!isalnum(ch) && ch != '_') {
  4798. /* End of variable name reached */
  4799. break;
  4800. }
  4801. ch = i_getch(input);
  4802. nommu_addchr(as_string, ch);
  4803. }
  4804. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4805. } else if (isdigit(ch)) {
  4806. make_one_char_var:
  4807. ch = i_getch(input);
  4808. nommu_addchr(as_string, ch);
  4809. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4810. debug_printf_parse(": '%c'\n", ch);
  4811. o_addchr(dest, ch | quote_mask);
  4812. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4813. } else switch (ch) {
  4814. case '$': /* pid */
  4815. case '!': /* last bg pid */
  4816. case '?': /* last exit code */
  4817. case '#': /* number of args */
  4818. case '*': /* args */
  4819. case '@': /* args */
  4820. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4821. goto make_one_char_var;
  4822. case '{': {
  4823. char len_single_ch;
  4824. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4825. ch = i_getch(input); /* eat '{' */
  4826. nommu_addchr(as_string, ch);
  4827. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4828. /* It should be ${?}, or ${#var},
  4829. * or even ${?+subst} - operator acting on a special variable,
  4830. * or the beginning of variable name.
  4831. */
  4832. if (ch == EOF
  4833. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4834. ) {
  4835. bad_dollar_syntax:
  4836. syntax_error_unterm_str("${name}");
  4837. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4838. return 0;
  4839. }
  4840. nommu_addchr(as_string, ch);
  4841. len_single_ch = ch;
  4842. ch |= quote_mask;
  4843. /* It's possible to just call add_till_closing_bracket() at this point.
  4844. * However, this regresses some of our testsuite cases
  4845. * which check invalid constructs like ${%}.
  4846. * Oh well... let's check that the var name part is fine... */
  4847. if (isdigit(len_single_ch)
  4848. || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
  4849. ) {
  4850. /* Execution engine uses plain xatoi_positive()
  4851. * to interpret ${NNN} and {#NNN},
  4852. * check syntax here in the parser.
  4853. * (bash does not support expressions in ${#NN},
  4854. * e.g. ${#$var} and {#1:+WORD} are not supported).
  4855. */
  4856. unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
  4857. while (1) {
  4858. o_addchr(dest, ch);
  4859. debug_printf_parse(": '%c'\n", ch);
  4860. ch = i_getch_and_eat_bkslash_nl(input);
  4861. nommu_addchr(as_string, ch);
  4862. if (ch == '}')
  4863. break;
  4864. if (--cnt == 0)
  4865. goto bad_dollar_syntax;
  4866. if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
  4867. /* ${NN<op>...} is valid */
  4868. goto eat_until_closing;
  4869. if (!isdigit(ch))
  4870. goto bad_dollar_syntax;
  4871. }
  4872. } else
  4873. while (1) {
  4874. unsigned pos;
  4875. o_addchr(dest, ch);
  4876. debug_printf_parse(": '%c'\n", ch);
  4877. ch = i_getch(input);
  4878. nommu_addchr(as_string, ch);
  4879. if (ch == '}')
  4880. break;
  4881. if (!isalnum(ch) && ch != '_') {
  4882. unsigned end_ch;
  4883. unsigned char last_ch;
  4884. /* handle parameter expansions
  4885. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4886. */
  4887. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4888. if (len_single_ch != '#'
  4889. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4890. || i_peek(input) != '}'
  4891. ) {
  4892. goto bad_dollar_syntax;
  4893. }
  4894. /* else: it's "length of C" ${#C} op,
  4895. * where C is a single char
  4896. * special var name, e.g. ${#!}.
  4897. */
  4898. }
  4899. eat_until_closing:
  4900. /* Eat everything until closing '}' (or ':') */
  4901. end_ch = '}';
  4902. if (BASH_SUBSTR
  4903. && ch == ':'
  4904. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4905. ) {
  4906. /* It's ${var:N[:M]} thing */
  4907. end_ch = '}' * 0x100 + ':';
  4908. }
  4909. if (BASH_PATTERN_SUBST
  4910. && ch == '/'
  4911. ) {
  4912. /* It's ${var/[/]pattern[/repl]} thing */
  4913. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4914. i_getch(input);
  4915. nommu_addchr(as_string, '/');
  4916. ch = '\\';
  4917. }
  4918. end_ch = '}' * 0x100 + '/';
  4919. }
  4920. o_addchr(dest, ch);
  4921. /* The pattern can't be empty.
  4922. * IOW: if the first char after "${v//" is a slash,
  4923. * it does not terminate the pattern - it's the first char of the pattern:
  4924. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4925. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4926. */
  4927. if (i_peek(input) == '/') {
  4928. o_addchr(dest, i_getch(input));
  4929. }
  4930. again:
  4931. if (!BB_MMU)
  4932. pos = dest->length;
  4933. #if ENABLE_HUSH_DOLLAR_OPS
  4934. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4935. if (last_ch == 0) /* error? */
  4936. return 0;
  4937. #else
  4938. # error Simple code to only allow ${var} is not implemented
  4939. #endif
  4940. if (as_string) {
  4941. o_addstr(as_string, dest->data + pos);
  4942. o_addchr(as_string, last_ch);
  4943. }
  4944. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4945. && (end_ch & 0xff00)
  4946. ) {
  4947. /* close the first block: */
  4948. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4949. /* while parsing N from ${var:N[:M]}
  4950. * or pattern from ${var/[/]pattern[/repl]} */
  4951. if ((end_ch & 0xff) == last_ch) {
  4952. /* got ':' or '/'- parse the rest */
  4953. end_ch = '}';
  4954. goto again;
  4955. }
  4956. /* got '}' */
  4957. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4958. /* it's ${var:N} - emulate :999999999 */
  4959. o_addstr(dest, "999999999");
  4960. } /* else: it's ${var/[/]pattern} */
  4961. }
  4962. break;
  4963. }
  4964. len_single_ch = 0; /* it can't be ${#C} op */
  4965. }
  4966. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4967. break;
  4968. }
  4969. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4970. case '(': {
  4971. unsigned pos;
  4972. ch = i_getch(input);
  4973. nommu_addchr(as_string, ch);
  4974. # if ENABLE_FEATURE_SH_MATH
  4975. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4976. ch = i_getch(input);
  4977. nommu_addchr(as_string, ch);
  4978. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4979. o_addchr(dest, quote_mask | '+');
  4980. if (!BB_MMU)
  4981. pos = dest->length;
  4982. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4983. return 0; /* error */
  4984. if (as_string) {
  4985. o_addstr(as_string, dest->data + pos);
  4986. o_addchr(as_string, ')');
  4987. o_addchr(as_string, ')');
  4988. }
  4989. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4990. break;
  4991. }
  4992. # endif
  4993. # if ENABLE_HUSH_TICK
  4994. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4995. o_addchr(dest, quote_mask | '`');
  4996. if (!BB_MMU)
  4997. pos = dest->length;
  4998. if (!add_till_closing_bracket(dest, input, ')'))
  4999. return 0; /* error */
  5000. if (as_string) {
  5001. o_addstr(as_string, dest->data + pos);
  5002. o_addchr(as_string, ')');
  5003. }
  5004. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5005. # endif
  5006. break;
  5007. }
  5008. #endif
  5009. case '_':
  5010. goto make_var;
  5011. #if 0
  5012. /* TODO: $_: */
  5013. /* $_ Shell or shell script name; or last argument of last command
  5014. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  5015. * but in command's env, set to full pathname used to invoke it */
  5016. ch = i_getch(input);
  5017. nommu_addchr(as_string, ch);
  5018. ch = i_peek_and_eat_bkslash_nl(input);
  5019. if (isalnum(ch)) { /* it's $_name or $_123 */
  5020. ch = '_';
  5021. goto make_var1;
  5022. }
  5023. /* else: it's $_ */
  5024. #endif
  5025. default:
  5026. o_addQchr(dest, '$');
  5027. }
  5028. debug_printf_parse("parse_dollar return 1 (ok)\n");
  5029. return 1;
  5030. #undef as_string
  5031. }
  5032. #if BB_MMU
  5033. #define encode_string(as_string, dest, input, dquote_end) \
  5034. encode_string(dest, input, dquote_end)
  5035. #define as_string NULL
  5036. #endif
  5037. static int encode_string(o_string *as_string,
  5038. o_string *dest,
  5039. struct in_str *input,
  5040. int dquote_end)
  5041. {
  5042. int ch;
  5043. int next;
  5044. again:
  5045. ch = i_getch(input);
  5046. if (ch != EOF)
  5047. nommu_addchr(as_string, ch);
  5048. if (ch == dquote_end) { /* may be only '"' or EOF */
  5049. debug_printf_parse("encode_string return 1 (ok)\n");
  5050. return 1;
  5051. }
  5052. /* note: can't move it above ch == dquote_end check! */
  5053. if (ch == EOF) {
  5054. syntax_error_unterm_ch('"');
  5055. return 0; /* error */
  5056. }
  5057. next = '\0';
  5058. if (ch != '\n') {
  5059. next = i_peek(input);
  5060. }
  5061. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  5062. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5063. if (ch == '\\') {
  5064. if (next == EOF) {
  5065. /* Testcase: in interactive shell a file with
  5066. * echo "unterminated string\<eof>
  5067. * is sourced.
  5068. */
  5069. syntax_error_unterm_ch('"');
  5070. return 0; /* error */
  5071. }
  5072. /* bash:
  5073. * "The backslash retains its special meaning [in "..."]
  5074. * only when followed by one of the following characters:
  5075. * $, `, ", \, or <newline>. A double quote may be quoted
  5076. * within double quotes by preceding it with a backslash."
  5077. * NB: in (unquoted) heredoc, above does not apply to ",
  5078. * therefore we check for it by "next == dquote_end" cond.
  5079. */
  5080. if (next == dquote_end || strchr("$`\\\n", next)) {
  5081. ch = i_getch(input); /* eat next */
  5082. if (ch == '\n')
  5083. goto again; /* skip \<newline> */
  5084. } /* else: ch remains == '\\', and we double it below: */
  5085. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  5086. nommu_addchr(as_string, ch);
  5087. goto again;
  5088. }
  5089. if (ch == '$') {
  5090. //if (parse_dollar_squote(as_string, dest, input))
  5091. // goto again;
  5092. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  5093. debug_printf_parse("encode_string return 0: "
  5094. "parse_dollar returned 0 (error)\n");
  5095. return 0;
  5096. }
  5097. goto again;
  5098. }
  5099. #if ENABLE_HUSH_TICK
  5100. if (ch == '`') {
  5101. //unsigned pos = dest->length;
  5102. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5103. o_addchr(dest, 0x80 | '`');
  5104. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  5105. return 0; /* error */
  5106. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5107. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5108. goto again;
  5109. }
  5110. #endif
  5111. o_addQchr(dest, ch);
  5112. if (ch == SPECIAL_VAR_SYMBOL) {
  5113. /* Convert "^C" to corresponding special variable reference */
  5114. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  5115. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5116. }
  5117. goto again;
  5118. #undef as_string
  5119. }
  5120. /*
  5121. * Scan input until EOF or end_trigger char.
  5122. * Return a list of pipes to execute, or NULL on EOF
  5123. * or if end_trigger character is met.
  5124. * On syntax error, exit if shell is not interactive,
  5125. * reset parsing machinery and start parsing anew,
  5126. * or return ERR_PTR.
  5127. */
  5128. static struct pipe *parse_stream(char **pstring,
  5129. int *heredoc_cnt_ptr,
  5130. struct in_str *input,
  5131. int end_trigger)
  5132. {
  5133. struct parse_context ctx;
  5134. int heredoc_cnt;
  5135. /* Single-quote triggers a bypass of the main loop until its mate is
  5136. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  5137. */
  5138. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  5139. end_trigger ? end_trigger : 'X');
  5140. debug_enter();
  5141. initialize_context(&ctx);
  5142. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  5143. * Preventing this:
  5144. */
  5145. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  5146. /* We used to separate words on $IFS here. This was wrong.
  5147. * $IFS is used only for word splitting when $var is expanded,
  5148. * here we should use blank chars as separators, not $IFS
  5149. */
  5150. heredoc_cnt = 0;
  5151. while (1) {
  5152. const char *is_blank;
  5153. const char *is_special;
  5154. int ch;
  5155. int next;
  5156. int redir_fd;
  5157. redir_type redir_style;
  5158. ch = i_getch(input);
  5159. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5160. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5161. if (ch == EOF) {
  5162. struct pipe *pi;
  5163. if (heredoc_cnt) {
  5164. syntax_error_unterm_str("here document");
  5165. goto parse_error_exitcode1;
  5166. }
  5167. if (end_trigger == ')') {
  5168. syntax_error_unterm_ch('(');
  5169. goto parse_error_exitcode1;
  5170. }
  5171. if (end_trigger == '}') {
  5172. syntax_error_unterm_ch('{');
  5173. goto parse_error_exitcode1;
  5174. }
  5175. if (done_word(&ctx)) {
  5176. goto parse_error_exitcode1;
  5177. }
  5178. o_free_and_set_NULL(&ctx.word);
  5179. done_pipe(&ctx, PIPE_SEQ);
  5180. /* Do we sit inside of any if's, loops or case's? */
  5181. if (HAS_KEYWORDS
  5182. IF_HAS_KEYWORDS(&& (ctx.ctx_res_w != RES_NONE || ctx.old_flag != 0))
  5183. ) {
  5184. syntax_error_unterm_str("compound statement");
  5185. goto parse_error_exitcode1;
  5186. }
  5187. pi = ctx.list_head;
  5188. /* If we got nothing... */
  5189. /* (this makes bare "&" cmd a no-op.
  5190. * bash says: "syntax error near unexpected token '&'") */
  5191. if (pi->num_cmds == 0
  5192. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5193. ) {
  5194. free_pipe_list(pi);
  5195. pi = NULL;
  5196. }
  5197. #if !BB_MMU
  5198. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5199. if (pstring)
  5200. *pstring = ctx.as_string.data;
  5201. else
  5202. o_free(&ctx.as_string);
  5203. #endif
  5204. // heredoc_cnt must be 0 here anyway
  5205. //if (heredoc_cnt_ptr)
  5206. // *heredoc_cnt_ptr = heredoc_cnt;
  5207. debug_leave();
  5208. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5209. debug_printf_parse("parse_stream return %p: EOF\n", pi);
  5210. return pi;
  5211. }
  5212. /* Handle "'" and "\" first, as they won't play nice with
  5213. * i_peek_and_eat_bkslash_nl() anyway:
  5214. * echo z\\
  5215. * and
  5216. * echo '\
  5217. * '
  5218. * would break.
  5219. */
  5220. if (ch == '\\') {
  5221. ch = i_getch(input);
  5222. if (ch == '\n')
  5223. continue; /* drop \<newline>, get next char */
  5224. nommu_addchr(&ctx.as_string, '\\');
  5225. if (ch == SPECIAL_VAR_SYMBOL) {
  5226. nommu_addchr(&ctx.as_string, ch);
  5227. /* Convert \^C to corresponding special variable reference */
  5228. goto case_SPECIAL_VAR_SYMBOL;
  5229. }
  5230. o_addchr(&ctx.word, '\\');
  5231. if (ch == EOF) {
  5232. /* Testcase: eval 'echo Ok\' */
  5233. /* bash-4.3.43 was removing backslash,
  5234. * but 4.4.19 retains it, most other shells too
  5235. */
  5236. continue; /* get next char */
  5237. }
  5238. /* Example: echo Hello \2>file
  5239. * we need to know that word 2 is quoted
  5240. */
  5241. ctx.word.has_quoted_part = 1;
  5242. nommu_addchr(&ctx.as_string, ch);
  5243. o_addchr(&ctx.word, ch);
  5244. continue; /* get next char */
  5245. }
  5246. nommu_addchr(&ctx.as_string, ch);
  5247. if (ch == '\'') {
  5248. ctx.word.has_quoted_part = 1;
  5249. next = i_getch(input);
  5250. if (next == '\'' && !ctx.pending_redirect)
  5251. goto insert_empty_quoted_str_marker;
  5252. ch = next;
  5253. while (1) {
  5254. if (ch == EOF) {
  5255. syntax_error_unterm_ch('\'');
  5256. goto parse_error_exitcode1;
  5257. }
  5258. nommu_addchr(&ctx.as_string, ch);
  5259. if (ch == '\'')
  5260. break;
  5261. if (ch == SPECIAL_VAR_SYMBOL) {
  5262. /* Convert raw ^C to corresponding special variable reference */
  5263. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5264. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5265. }
  5266. o_addqchr(&ctx.word, ch);
  5267. ch = i_getch(input);
  5268. }
  5269. continue; /* get next char */
  5270. }
  5271. next = '\0';
  5272. if (ch != '\n')
  5273. next = i_peek_and_eat_bkslash_nl(input);
  5274. is_special = "{}<>&|();#" /* special outside of "str" */
  5275. "$\"" IF_HUSH_TICK("`") /* always special */
  5276. SPECIAL_VAR_SYMBOL_STR;
  5277. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5278. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5279. /* In [[ ]], {}<>&|() are not special */
  5280. is_special += 8;
  5281. } else
  5282. #endif
  5283. /* Are { and } special here? */
  5284. if (ctx.command->argv /* word [word]{... - non-special */
  5285. || ctx.word.length /* word{... - non-special */
  5286. || ctx.word.has_quoted_part /* ""{... - non-special */
  5287. || (next != ';' /* }; - special */
  5288. && next != ')' /* }) - special */
  5289. && next != '(' /* {( - special */
  5290. && next != '&' /* }& and }&& ... - special */
  5291. && next != '|' /* }|| ... - special */
  5292. && !strchr(defifs, next) /* {word - non-special */
  5293. )
  5294. ) {
  5295. /* They are not special, skip "{}" */
  5296. is_special += 2;
  5297. }
  5298. is_special = strchr(is_special, ch);
  5299. is_blank = strchr(defifs, ch);
  5300. if (!is_special && !is_blank) { /* ordinary char */
  5301. ordinary_char:
  5302. o_addQchr(&ctx.word, ch);
  5303. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5304. || ctx.is_assignment == WORD_IS_KEYWORD)
  5305. && ch == '='
  5306. && endofname(ctx.word.data)[0] == '='
  5307. ) {
  5308. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5309. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5310. }
  5311. continue;
  5312. }
  5313. if (is_blank) {
  5314. #if ENABLE_HUSH_LINENO_VAR
  5315. /* Case:
  5316. * "while ...; do<whitespace><newline>
  5317. * cmd ..."
  5318. * would think that "cmd" starts in <whitespace> -
  5319. * i.e., at the previous line.
  5320. * We need to skip all whitespace before newlines.
  5321. */
  5322. while (ch != '\n') {
  5323. next = i_peek(input);
  5324. if (next != ' ' && next != '\t' && next != '\n')
  5325. break; /* next char is not ws */
  5326. ch = i_getch(input);
  5327. }
  5328. /* ch == last eaten whitespace char */
  5329. #endif
  5330. if (done_word(&ctx)) {
  5331. goto parse_error_exitcode1;
  5332. }
  5333. if (ch == '\n') {
  5334. /* Is this a case when newline is simply ignored?
  5335. * Some examples:
  5336. * "cmd | <newline> cmd ..."
  5337. * "case ... in <newline> word) ..."
  5338. */
  5339. if (IS_NULL_CMD(ctx.command)
  5340. && ctx.word.length == 0
  5341. && !ctx.word.has_quoted_part
  5342. && heredoc_cnt == 0
  5343. ) {
  5344. /* This newline can be ignored. But...
  5345. * Without check #1, interactive shell
  5346. * ignores even bare <newline>,
  5347. * and shows the continuation prompt:
  5348. * ps1_prompt$ <enter>
  5349. * ps2> _ <=== wrong, should be ps1
  5350. * Without check #2, "cmd & <newline>"
  5351. * is similarly mistreated.
  5352. * (BTW, this makes "cmd & cmd"
  5353. * and "cmd && cmd" non-orthogonal.
  5354. * Really, ask yourself, why
  5355. * "cmd && <newline>" doesn't start
  5356. * cmd but waits for more input?
  5357. * The only reason is that it might be
  5358. * a "cmd1 && <nl> cmd2 &" construct,
  5359. * cmd1 may need to run in BG).
  5360. */
  5361. struct pipe *pi = ctx.list_head;
  5362. if (pi->num_cmds != 0 /* check #1 */
  5363. && pi->followup != PIPE_BG /* check #2 */
  5364. ) {
  5365. continue;
  5366. }
  5367. }
  5368. /* Treat newline as a command separator. */
  5369. done_pipe(&ctx, PIPE_SEQ);
  5370. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5371. if (heredoc_cnt) {
  5372. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5373. if (heredoc_cnt != 0)
  5374. goto parse_error_exitcode1;
  5375. }
  5376. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5377. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5378. ch = ';';
  5379. /* note: if (is_blank) continue;
  5380. * will still trigger for us */
  5381. }
  5382. }
  5383. /* "cmd}" or "cmd }..." without semicolon or &:
  5384. * } is an ordinary char in this case, even inside { cmd; }
  5385. * Pathological example: { ""}; } should exec "}" cmd
  5386. */
  5387. if (ch == '}') {
  5388. if (ctx.word.length != 0 /* word} */
  5389. || ctx.word.has_quoted_part /* ""} */
  5390. ) {
  5391. goto ordinary_char;
  5392. }
  5393. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5394. /* Generally, there should be semicolon: "cmd; }"
  5395. * However, bash allows to omit it if "cmd" is
  5396. * a group. Examples:
  5397. * { { echo 1; } }
  5398. * {(echo 1)}
  5399. * { echo 0 >&2 | { echo 1; } }
  5400. * { while false; do :; done }
  5401. * { case a in b) ;; esac }
  5402. */
  5403. if (ctx.command->group)
  5404. goto term_group;
  5405. goto ordinary_char;
  5406. }
  5407. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5408. /* Can't be an end of {cmd}, skip the check */
  5409. goto skip_end_trigger;
  5410. /* else: } does terminate a group */
  5411. }
  5412. term_group:
  5413. if (end_trigger && end_trigger == ch
  5414. && (ch != ';' || heredoc_cnt == 0)
  5415. #if ENABLE_HUSH_CASE
  5416. && (ch != ')'
  5417. || ctx.ctx_res_w != RES_MATCH
  5418. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5419. )
  5420. #endif
  5421. ) {
  5422. if (done_word(&ctx)) {
  5423. goto parse_error_exitcode1;
  5424. }
  5425. done_pipe(&ctx, PIPE_SEQ);
  5426. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5427. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5428. /* Do we sit outside of any if's, loops or case's? */
  5429. if (!HAS_KEYWORDS
  5430. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5431. ) {
  5432. o_free_and_set_NULL(&ctx.word);
  5433. #if !BB_MMU
  5434. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5435. if (pstring)
  5436. *pstring = ctx.as_string.data;
  5437. else
  5438. o_free(&ctx.as_string);
  5439. #endif
  5440. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5441. /* Example: bare "{ }", "()" */
  5442. G.last_exitcode = 2; /* bash compat */
  5443. syntax_error_unexpected_ch(ch);
  5444. goto parse_error;
  5445. }
  5446. if (heredoc_cnt_ptr)
  5447. *heredoc_cnt_ptr = heredoc_cnt;
  5448. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5449. debug_printf_parse("parse_stream return %p: "
  5450. "end_trigger char found\n",
  5451. ctx.list_head);
  5452. debug_leave();
  5453. return ctx.list_head;
  5454. }
  5455. }
  5456. if (is_blank)
  5457. continue;
  5458. /* Catch <, > before deciding whether this word is
  5459. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5460. switch (ch) {
  5461. case '>':
  5462. redir_fd = redirect_opt_num(&ctx.word);
  5463. if (done_word(&ctx)) {
  5464. goto parse_error_exitcode1;
  5465. }
  5466. redir_style = REDIRECT_OVERWRITE;
  5467. if (next == '>') {
  5468. redir_style = REDIRECT_APPEND;
  5469. ch = i_getch(input);
  5470. nommu_addchr(&ctx.as_string, ch);
  5471. }
  5472. #if 0
  5473. else if (next == '(') {
  5474. syntax_error(">(process) not supported");
  5475. goto parse_error_exitcode1;
  5476. }
  5477. #endif
  5478. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5479. goto parse_error_exitcode1;
  5480. continue; /* get next char */
  5481. case '<':
  5482. redir_fd = redirect_opt_num(&ctx.word);
  5483. if (done_word(&ctx)) {
  5484. goto parse_error_exitcode1;
  5485. }
  5486. redir_style = REDIRECT_INPUT;
  5487. if (next == '<') {
  5488. redir_style = REDIRECT_HEREDOC;
  5489. heredoc_cnt++;
  5490. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5491. ch = i_getch(input);
  5492. nommu_addchr(&ctx.as_string, ch);
  5493. } else if (next == '>') {
  5494. redir_style = REDIRECT_IO;
  5495. ch = i_getch(input);
  5496. nommu_addchr(&ctx.as_string, ch);
  5497. }
  5498. #if 0
  5499. else if (next == '(') {
  5500. syntax_error("<(process) not supported");
  5501. goto parse_error_exitcode1;
  5502. }
  5503. #endif
  5504. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5505. goto parse_error_exitcode1;
  5506. continue; /* get next char */
  5507. case '#':
  5508. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5509. /* skip "#comment" */
  5510. /* note: we do not add it to &ctx.as_string */
  5511. /* TODO: in bash:
  5512. * comment inside $() goes to the next \n, even inside quoted string (!):
  5513. * cmd "$(cmd2 #comment)" - syntax error
  5514. * cmd "`cmd2 #comment`" - ok
  5515. * We accept both (comment ends where command subst ends, in both cases).
  5516. */
  5517. while (1) {
  5518. ch = i_peek(input);
  5519. if (ch == '\n') {
  5520. nommu_addchr(&ctx.as_string, '\n');
  5521. break;
  5522. }
  5523. ch = i_getch(input);
  5524. if (ch == EOF)
  5525. break;
  5526. }
  5527. continue; /* get next char */
  5528. }
  5529. break;
  5530. }
  5531. skip_end_trigger:
  5532. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5533. /* check that we are not in word in "a=1 2>word b=1": */
  5534. && !ctx.pending_redirect
  5535. ) {
  5536. /* ch is a special char and thus this word
  5537. * cannot be an assignment */
  5538. ctx.is_assignment = NOT_ASSIGNMENT;
  5539. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5540. }
  5541. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5542. switch (ch) {
  5543. case_SPECIAL_VAR_SYMBOL:
  5544. case SPECIAL_VAR_SYMBOL:
  5545. /* Convert raw ^C to corresponding special variable reference */
  5546. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5547. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5548. /* fall through */
  5549. case '#':
  5550. /* non-comment #: "echo a#b" etc */
  5551. o_addchr(&ctx.word, ch);
  5552. continue; /* get next char */
  5553. case '$':
  5554. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5555. continue; /* get next char */
  5556. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5557. debug_printf_parse("parse_stream parse error: "
  5558. "parse_dollar returned 0 (error)\n");
  5559. goto parse_error_exitcode1;
  5560. }
  5561. continue; /* get next char */
  5562. case '"':
  5563. ctx.word.has_quoted_part = 1;
  5564. if (next == '"' && !ctx.pending_redirect) {
  5565. i_getch(input); /* eat second " */
  5566. insert_empty_quoted_str_marker:
  5567. nommu_addchr(&ctx.as_string, next);
  5568. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5569. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5570. continue; /* get next char */
  5571. }
  5572. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5573. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5574. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5575. goto parse_error_exitcode1;
  5576. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5577. continue; /* get next char */
  5578. #if ENABLE_HUSH_TICK
  5579. case '`': {
  5580. USE_FOR_NOMMU(unsigned pos;)
  5581. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5582. o_addchr(&ctx.word, '`');
  5583. USE_FOR_NOMMU(pos = ctx.word.length;)
  5584. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5585. goto parse_error_exitcode1;
  5586. # if !BB_MMU
  5587. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5588. o_addchr(&ctx.as_string, '`');
  5589. # endif
  5590. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5591. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5592. continue; /* get next char */
  5593. }
  5594. #endif
  5595. case ';':
  5596. #if ENABLE_HUSH_CASE
  5597. case_semi:
  5598. #endif
  5599. if (done_word(&ctx)) {
  5600. goto parse_error_exitcode1;
  5601. }
  5602. done_pipe(&ctx, PIPE_SEQ);
  5603. #if ENABLE_HUSH_CASE
  5604. /* Eat multiple semicolons, detect
  5605. * whether it means something special */
  5606. while (1) {
  5607. ch = i_peek_and_eat_bkslash_nl(input);
  5608. if (ch != ';')
  5609. break;
  5610. ch = i_getch(input);
  5611. nommu_addchr(&ctx.as_string, ch);
  5612. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5613. ctx.ctx_dsemicolon = 1;
  5614. ctx.ctx_res_w = RES_MATCH;
  5615. break;
  5616. }
  5617. }
  5618. #endif
  5619. new_cmd:
  5620. /* We just finished a cmd. New one may start
  5621. * with an assignment */
  5622. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5623. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5624. continue; /* get next char */
  5625. case '&':
  5626. if (done_word(&ctx)) {
  5627. goto parse_error_exitcode1;
  5628. }
  5629. if (next == '&') {
  5630. ch = i_getch(input);
  5631. nommu_addchr(&ctx.as_string, ch);
  5632. done_pipe(&ctx, PIPE_AND);
  5633. } else {
  5634. done_pipe(&ctx, PIPE_BG);
  5635. }
  5636. goto new_cmd;
  5637. case '|':
  5638. if (done_word(&ctx)) {
  5639. goto parse_error_exitcode1;
  5640. }
  5641. #if ENABLE_HUSH_CASE
  5642. if (ctx.ctx_res_w == RES_MATCH)
  5643. break; /* we are in case's "word | word)" */
  5644. #endif
  5645. if (next == '|') { /* || */
  5646. ch = i_getch(input);
  5647. nommu_addchr(&ctx.as_string, ch);
  5648. done_pipe(&ctx, PIPE_OR);
  5649. } else {
  5650. /* we could pick up a file descriptor choice here
  5651. * with redirect_opt_num(), but bash doesn't do it.
  5652. * "echo foo 2| cat" yields "foo 2". */
  5653. done_command(&ctx);
  5654. }
  5655. goto new_cmd;
  5656. case '(':
  5657. #if ENABLE_HUSH_CASE
  5658. /* "case... in [(]word)..." - skip '(' */
  5659. if (ctx.ctx_res_w == RES_MATCH
  5660. && ctx.command->argv == NULL /* not (word|(... */
  5661. && ctx.word.length == 0 /* not word(... */
  5662. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5663. ) {
  5664. continue; /* get next char */
  5665. }
  5666. #endif
  5667. /* fall through */
  5668. case '{': {
  5669. int n = parse_group(&ctx, input, ch);
  5670. if (n < 0) {
  5671. goto parse_error_exitcode1;
  5672. }
  5673. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5674. heredoc_cnt += n;
  5675. goto new_cmd;
  5676. }
  5677. case ')':
  5678. #if ENABLE_HUSH_CASE
  5679. if (ctx.ctx_res_w == RES_MATCH)
  5680. goto case_semi;
  5681. #endif
  5682. case '}':
  5683. /* proper use of this character is caught by end_trigger:
  5684. * if we see {, we call parse_group(..., end_trigger='}')
  5685. * and it will match } earlier (not here). */
  5686. G.last_exitcode = 2;
  5687. syntax_error_unexpected_ch(ch);
  5688. goto parse_error;
  5689. default:
  5690. if (HUSH_DEBUG)
  5691. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5692. }
  5693. } /* while (1) */
  5694. parse_error_exitcode1:
  5695. G.last_exitcode = 1;
  5696. parse_error:
  5697. {
  5698. struct parse_context *pctx;
  5699. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5700. /* Clean up allocated tree.
  5701. * Sample for finding leaks on syntax error recovery path.
  5702. * Run it from interactive shell, watch pmap `pidof hush`.
  5703. * while if false; then false; fi; do break; fi
  5704. * Samples to catch leaks at execution:
  5705. * while if (true | { true;}); then echo ok; fi; do break; done
  5706. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5707. */
  5708. pctx = &ctx;
  5709. do {
  5710. /* Update pipe/command counts,
  5711. * otherwise freeing may miss some */
  5712. done_pipe(pctx, PIPE_SEQ);
  5713. debug_printf_clean("freeing list %p from ctx %p\n",
  5714. pctx->list_head, pctx);
  5715. debug_print_tree(pctx->list_head, 0);
  5716. free_pipe_list(pctx->list_head);
  5717. debug_printf_clean("freed list %p\n", pctx->list_head);
  5718. #if !BB_MMU
  5719. o_free(&pctx->as_string);
  5720. #endif
  5721. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5722. if (pctx != &ctx) {
  5723. free(pctx);
  5724. }
  5725. IF_HAS_KEYWORDS(pctx = p2;)
  5726. } while (HAS_KEYWORDS && pctx);
  5727. o_free(&ctx.word);
  5728. #if !BB_MMU
  5729. if (pstring)
  5730. *pstring = NULL;
  5731. #endif
  5732. debug_leave();
  5733. return ERR_PTR;
  5734. }
  5735. }
  5736. /*
  5737. * Execution routines
  5738. */
  5739. /* Expansion can recurse, need forward decls: */
  5740. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5741. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5742. expand_string_to_string(str)
  5743. #endif
  5744. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5745. #if ENABLE_HUSH_TICK
  5746. static int process_command_subs(o_string *dest, const char *s);
  5747. #endif
  5748. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5749. /* expand_strvec_to_strvec() takes a list of strings, expands
  5750. * all variable references within and returns a pointer to
  5751. * a list of expanded strings, possibly with larger number
  5752. * of strings. (Think VAR="a b"; echo $VAR).
  5753. * This new list is allocated as a single malloc block.
  5754. * NULL-terminated list of char* pointers is at the beginning of it,
  5755. * followed by strings themselves.
  5756. * Caller can deallocate entire list by single free(list). */
  5757. /* A horde of its helpers come first: */
  5758. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5759. {
  5760. while (--len >= 0) {
  5761. char c = *str++;
  5762. #if ENABLE_HUSH_BRACE_EXPANSION
  5763. if (c == '{' || c == '}') {
  5764. /* { -> \{, } -> \} */
  5765. o_addchr(o, '\\');
  5766. /* And now we want to add { or } and continue:
  5767. * o_addchr(o, c);
  5768. * continue;
  5769. * luckily, just falling through achieves this.
  5770. */
  5771. }
  5772. #endif
  5773. o_addchr(o, c);
  5774. if (c == '\\') {
  5775. /* \z -> \\\z; \<eol> -> \\<eol> */
  5776. o_addchr(o, '\\');
  5777. if (len) {
  5778. len--;
  5779. o_addchr(o, '\\');
  5780. o_addchr(o, *str++);
  5781. }
  5782. }
  5783. }
  5784. }
  5785. /* Store given string, finalizing the word and starting new one whenever
  5786. * we encounter IFS char(s). This is used for expanding variable values.
  5787. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5788. * Return in output->ended_in_ifs:
  5789. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5790. */
  5791. static int expand_on_ifs(o_string *output, int n, const char *str)
  5792. {
  5793. int last_is_ifs = 0;
  5794. while (1) {
  5795. int word_len;
  5796. if (!*str) /* EOL - do not finalize word */
  5797. break;
  5798. word_len = strcspn(str, G.ifs);
  5799. if (word_len) {
  5800. /* We have WORD_LEN leading non-IFS chars */
  5801. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5802. o_addblock(output, str, word_len);
  5803. } else {
  5804. /* Protect backslashes against globbing up :)
  5805. * Example: "v='\*'; echo b$v" prints "b\*"
  5806. * (and does not try to glob on "*")
  5807. */
  5808. o_addblock_duplicate_backslash(output, str, word_len);
  5809. /*/ Why can't we do it easier? */
  5810. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5811. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5812. }
  5813. last_is_ifs = 0;
  5814. str += word_len;
  5815. if (!*str) /* EOL - do not finalize word */
  5816. break;
  5817. }
  5818. /* We know str here points to at least one IFS char */
  5819. last_is_ifs = 1;
  5820. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5821. if (!*str) /* EOL - do not finalize word */
  5822. break;
  5823. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5824. && strchr(G.ifs, *str) /* the second check would fail */
  5825. ) {
  5826. /* This is a non-whitespace $IFS char */
  5827. /* Skip it and IFS whitespace chars, start new word */
  5828. str++;
  5829. str += strspn(str, G.ifs_whitespace);
  5830. goto new_word;
  5831. }
  5832. /* Start new word... but not always! */
  5833. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5834. if (output->has_quoted_part
  5835. /*
  5836. * Case "v=' a'; echo $v":
  5837. * here nothing precedes the space in $v expansion,
  5838. * therefore we should not finish the word
  5839. * (IOW: if there *is* word to finalize, only then do it):
  5840. * It's okay if this accesses the byte before first argv[]:
  5841. * past call to o_save_ptr() cleared it to zero byte
  5842. * (grep for -prev-ifs-check-).
  5843. */
  5844. || output->data[output->length - 1]
  5845. ) {
  5846. new_word:
  5847. o_addchr(output, '\0');
  5848. debug_print_list("expand_on_ifs", output, n);
  5849. n = o_save_ptr(output, n);
  5850. }
  5851. }
  5852. output->ended_in_ifs = last_is_ifs;
  5853. debug_print_list("expand_on_ifs[1]", output, n);
  5854. return n;
  5855. }
  5856. /* Helper to expand $((...)) and heredoc body. These act as if
  5857. * they are in double quotes, with the exception that they are not :).
  5858. * Just the rules are similar: "expand only $var and `cmd`"
  5859. *
  5860. * Returns malloced string.
  5861. * As an optimization, we return NULL if expansion is not needed.
  5862. */
  5863. static char *encode_then_expand_string(const char *str)
  5864. {
  5865. char *exp_str;
  5866. struct in_str input;
  5867. o_string dest = NULL_O_STRING;
  5868. const char *cp;
  5869. cp = str;
  5870. for (;;) {
  5871. if (!*cp) return NULL; /* string has no special chars */
  5872. if (*cp == '$') break;
  5873. if (*cp == '\\') break;
  5874. #if ENABLE_HUSH_TICK
  5875. if (*cp == '`') break;
  5876. #endif
  5877. cp++;
  5878. }
  5879. /* We need to expand. Example:
  5880. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5881. */
  5882. setup_string_in_str(&input, str);
  5883. encode_string(NULL, &dest, &input, EOF);
  5884. //TODO: error check (encode_string returns 0 on error)?
  5885. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5886. exp_str = expand_string_to_string(dest.data,
  5887. EXP_FLAG_ESC_GLOB_CHARS,
  5888. /*unbackslash:*/ 1
  5889. );
  5890. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5891. o_free(&dest);
  5892. return exp_str;
  5893. }
  5894. static const char *first_special_char_in_vararg(const char *cp)
  5895. {
  5896. for (;;) {
  5897. if (!*cp) return NULL; /* string has no special chars */
  5898. if (*cp == '$') return cp;
  5899. if (*cp == '\\') return cp;
  5900. if (*cp == '\'') return cp;
  5901. if (*cp == '"') return cp;
  5902. #if ENABLE_HUSH_TICK
  5903. if (*cp == '`') return cp;
  5904. #endif
  5905. /* dquoted "${x:+ARG}" should not glob, therefore
  5906. * '*' et al require some non-literal processing: */
  5907. if (*cp == '*') return cp;
  5908. if (*cp == '?') return cp;
  5909. if (*cp == '[') return cp;
  5910. cp++;
  5911. }
  5912. }
  5913. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5914. * These can contain single- and double-quoted strings,
  5915. * and treated as if the ARG string is initially unquoted. IOW:
  5916. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5917. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5918. * (word splitting and globbing of the ${var...} result).
  5919. */
  5920. #if !BASH_PATTERN_SUBST
  5921. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5922. encode_then_expand_vararg(str, handle_squotes)
  5923. #endif
  5924. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5925. {
  5926. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5927. const int do_unbackslash = 0;
  5928. #endif
  5929. char *exp_str;
  5930. struct in_str input;
  5931. o_string dest = NULL_O_STRING;
  5932. if (!first_special_char_in_vararg(str)) {
  5933. /* string has no special chars */
  5934. return NULL;
  5935. }
  5936. setup_string_in_str(&input, str);
  5937. dest.data = xzalloc(1); /* start as "", not as NULL */
  5938. exp_str = NULL;
  5939. for (;;) {
  5940. int ch;
  5941. ch = i_getch(&input);
  5942. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5943. __func__, ch, ch, !!dest.o_expflags);
  5944. if (!dest.o_expflags) {
  5945. if (ch == EOF)
  5946. break;
  5947. if (handle_squotes && ch == '\'') {
  5948. if (!add_till_single_quote_dquoted(&dest, &input))
  5949. goto ret; /* error */
  5950. continue;
  5951. }
  5952. }
  5953. if (ch == EOF) {
  5954. syntax_error_unterm_ch('"');
  5955. goto ret; /* error */
  5956. }
  5957. if (ch == '"') {
  5958. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5959. continue;
  5960. }
  5961. if (ch == '\\') {
  5962. ch = i_getch(&input);
  5963. if (ch == EOF) {
  5964. //example? error message? syntax_error_unterm_ch('"');
  5965. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5966. goto ret;
  5967. }
  5968. o_addqchr(&dest, ch);
  5969. continue;
  5970. }
  5971. if (ch == '$') {
  5972. if (parse_dollar_squote(NULL, &dest, &input))
  5973. continue;
  5974. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5975. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5976. goto ret;
  5977. }
  5978. continue;
  5979. }
  5980. #if ENABLE_HUSH_TICK
  5981. if (ch == '`') {
  5982. //unsigned pos = dest->length;
  5983. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5984. o_addchr(&dest, 0x80 | '`');
  5985. if (!add_till_backquote(&dest, &input,
  5986. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5987. )
  5988. ) {
  5989. goto ret; /* error */
  5990. }
  5991. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5992. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5993. continue;
  5994. }
  5995. #endif
  5996. o_addQchr(&dest, ch);
  5997. } /* for (;;) */
  5998. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5999. exp_str = expand_string_to_string(dest.data,
  6000. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  6001. do_unbackslash
  6002. );
  6003. ret:
  6004. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  6005. o_free(&dest);
  6006. return exp_str;
  6007. }
  6008. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  6009. */
  6010. static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
  6011. char *str, int dquoted)
  6012. {
  6013. struct in_str input;
  6014. o_string dest = NULL_O_STRING;
  6015. if (!first_special_char_in_vararg(str)
  6016. && '\0' == str[strcspn(str, G.ifs)]
  6017. ) {
  6018. /* string has no special chars
  6019. * && string has no $IFS chars
  6020. */
  6021. if (dquoted) {
  6022. /* Prints 1 (quoted expansion is a "" word, not nothing):
  6023. * set -- "${notexist-}"; echo $#
  6024. */
  6025. output->has_quoted_part = 1;
  6026. }
  6027. return expand_vars_to_list(output, n, str);
  6028. }
  6029. setup_string_in_str(&input, str);
  6030. for (;;) {
  6031. int ch;
  6032. ch = i_getch(&input);
  6033. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  6034. __func__, ch, ch, dest.o_expflags);
  6035. if (!dest.o_expflags) {
  6036. if (ch == EOF)
  6037. break;
  6038. if (!dquoted && !(output->o_expflags & EXP_FLAG_SINGLEWORD) && strchr(G.ifs, ch)) {
  6039. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  6040. * do not assume we are at the start of the word (PREFIX above).
  6041. */
  6042. if (dest.data) {
  6043. n = expand_vars_to_list(output, n, dest.data);
  6044. o_free_and_set_NULL(&dest);
  6045. o_addchr(output, '\0');
  6046. n = o_save_ptr(output, n); /* create next word */
  6047. } else
  6048. if (output->length != o_get_last_ptr(output, n)
  6049. || output->has_quoted_part
  6050. ) {
  6051. /* For these cases:
  6052. * f() { for i; do echo "|$i|"; done; }; x=x
  6053. * f a${x:+ }b # 1st condition
  6054. * |a|
  6055. * |b|
  6056. * f ""${x:+ }b # 2nd condition
  6057. * ||
  6058. * |b|
  6059. */
  6060. o_addchr(output, '\0');
  6061. n = o_save_ptr(output, n); /* create next word */
  6062. }
  6063. continue;
  6064. }
  6065. if (!dquoted && ch == '\'') {
  6066. if (!add_till_single_quote_dquoted(&dest, &input))
  6067. goto ret; /* error */
  6068. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6069. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6070. continue;
  6071. }
  6072. }
  6073. if (ch == EOF) {
  6074. syntax_error_unterm_ch('"');
  6075. goto ret; /* error */
  6076. }
  6077. if (ch == '"') {
  6078. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  6079. if (dest.o_expflags) {
  6080. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6081. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6082. }
  6083. continue;
  6084. }
  6085. if (ch == '\\') {
  6086. ch = i_getch(&input);
  6087. if (ch == EOF) {
  6088. //example? error message? syntax_error_unterm_ch('"');
  6089. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  6090. goto ret;
  6091. }
  6092. o_addqchr(&dest, ch);
  6093. continue;
  6094. }
  6095. if (ch == '$') {
  6096. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6097. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6098. goto ret;
  6099. }
  6100. continue;
  6101. }
  6102. #if ENABLE_HUSH_TICK
  6103. if (ch == '`') {
  6104. //unsigned pos = dest->length;
  6105. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6106. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6107. if (!add_till_backquote(&dest, &input,
  6108. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6109. )
  6110. ) {
  6111. goto ret; /* error */
  6112. }
  6113. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6114. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6115. continue;
  6116. }
  6117. #endif
  6118. if (dquoted) {
  6119. /* Always glob-protect if in dquotes:
  6120. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6121. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6122. */
  6123. o_addqchr(&dest, ch);
  6124. } else {
  6125. /* Glob-protect only if char is quoted:
  6126. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6127. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6128. */
  6129. o_addQchr(&dest, ch);
  6130. }
  6131. } /* for (;;) */
  6132. if (dest.data) {
  6133. n = expand_vars_to_list(output, n, dest.data);
  6134. }
  6135. ret:
  6136. o_free(&dest);
  6137. return n;
  6138. }
  6139. #if ENABLE_FEATURE_SH_MATH
  6140. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6141. {
  6142. arith_state_t math_state;
  6143. arith_t res;
  6144. char *exp_str;
  6145. math_state.lookupvar = get_local_var_value;
  6146. math_state.setvar = set_local_var_from_halves;
  6147. //math_state.endofname = endofname;
  6148. exp_str = encode_then_expand_string(arg);
  6149. res = arith(&math_state, exp_str ? exp_str : arg);
  6150. free(exp_str);
  6151. if (errmsg_p)
  6152. *errmsg_p = math_state.errmsg;
  6153. if (math_state.errmsg)
  6154. msg_and_die_if_script(math_state.errmsg);
  6155. return res;
  6156. }
  6157. #endif
  6158. #if BASH_PATTERN_SUBST
  6159. /* ${var/[/]pattern[/repl]} helpers */
  6160. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6161. {
  6162. int first_escaped = (pattern[0] == '\\' && pattern[1]);
  6163. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6164. * as literal too (as it is semi-common, and easy to accomodate
  6165. * by just using str + 1).
  6166. */
  6167. int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
  6168. if ((pattern + first_escaped * 2)[sz] == '\0') {
  6169. /* Optimization for trivial patterns.
  6170. * Testcase for very slow replace (performs about 22k replaces):
  6171. * x=::::::::::::::::::::::
  6172. * 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}
  6173. * echo "${x//:/|}"
  6174. */
  6175. *size = sz + first_escaped;
  6176. return strstr(val, pattern + first_escaped);
  6177. }
  6178. while (1) {
  6179. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6180. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6181. if (end) {
  6182. *size = end - val;
  6183. return val;
  6184. }
  6185. if (*val == '\0')
  6186. return NULL;
  6187. /* Optimization: if "*pat" did not match the start of "string",
  6188. * we know that "tring", "ring" etc will not match too:
  6189. */
  6190. if (pattern[0] == '*')
  6191. return NULL;
  6192. val++;
  6193. }
  6194. }
  6195. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6196. {
  6197. char *result = NULL;
  6198. unsigned res_len = 0;
  6199. unsigned repl_len = strlen(repl);
  6200. /* Null pattern never matches, including if "var" is empty */
  6201. if (!pattern[0])
  6202. return result; /* NULL, no replaces happened */
  6203. while (1) {
  6204. int size;
  6205. char *s = strstr_pattern(val, pattern, &size);
  6206. if (!s)
  6207. break;
  6208. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6209. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6210. res_len += (s - val) + repl_len;
  6211. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6212. val = s + size;
  6213. if (exp_op == '/')
  6214. break;
  6215. }
  6216. if (*val && result) {
  6217. result = xrealloc(result, res_len + strlen(val) + 1);
  6218. strcpy(result + res_len, val);
  6219. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6220. }
  6221. debug_printf_varexp("result:'%s'\n", result);
  6222. return result;
  6223. }
  6224. #endif /* BASH_PATTERN_SUBST */
  6225. static int append_str_maybe_ifs_split(o_string *output, int n,
  6226. int first_ch, const char *val)
  6227. {
  6228. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6229. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6230. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6231. if (val && val[0])
  6232. n = expand_on_ifs(output, n, val);
  6233. } else { /* quoted "$VAR" */
  6234. output->has_quoted_part = 1;
  6235. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6236. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6237. if (val && val[0])
  6238. o_addQstr(output, val);
  6239. }
  6240. return n;
  6241. }
  6242. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6243. */
  6244. static NOINLINE int expand_one_var(o_string *output, int n,
  6245. int first_ch, char *arg, char **pp)
  6246. {
  6247. const char *val;
  6248. char *to_be_freed;
  6249. char *p;
  6250. char *var;
  6251. char exp_op;
  6252. char exp_save = exp_save; /* for compiler */
  6253. char *exp_saveptr; /* points to expansion operator */
  6254. char *exp_word = exp_word; /* for compiler */
  6255. char arg0;
  6256. val = NULL;
  6257. to_be_freed = NULL;
  6258. p = *pp;
  6259. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6260. var = arg;
  6261. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6262. arg0 = arg[0];
  6263. arg[0] = (arg0 & 0x7f);
  6264. exp_op = 0;
  6265. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6266. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6267. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6268. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6269. ) {
  6270. /* It must be length operator: ${#var} */
  6271. var++;
  6272. exp_op = 'L';
  6273. } else {
  6274. /* Maybe handle parameter expansion */
  6275. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6276. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6277. ) {
  6278. /* ${?:0}, ${#[:]%0} etc */
  6279. exp_saveptr = var + 1;
  6280. } else {
  6281. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6282. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6283. }
  6284. exp_op = exp_save = *exp_saveptr;
  6285. if (exp_op) {
  6286. exp_word = exp_saveptr + 1;
  6287. if (exp_op == ':') {
  6288. exp_op = *exp_word++;
  6289. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6290. if (BASH_SUBSTR
  6291. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6292. ) {
  6293. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6294. exp_op = ':';
  6295. exp_word--;
  6296. }
  6297. }
  6298. *exp_saveptr = '\0';
  6299. } /* else: it's not an expansion op, but bare ${var} */
  6300. }
  6301. /* Look up the variable in question */
  6302. if (isdigit(var[0])) {
  6303. /* parse_dollar should have vetted var for us */
  6304. int nn = xatoi_positive(var);
  6305. if (nn < G.global_argc)
  6306. val = G.global_argv[nn];
  6307. /* else val remains NULL: $N with too big N */
  6308. } else {
  6309. switch (var[0]) {
  6310. case '$': /* pid */
  6311. val = utoa(G.root_pid);
  6312. break;
  6313. case '!': /* bg pid */
  6314. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6315. break;
  6316. case '?': /* exitcode */
  6317. val = utoa(G.last_exitcode);
  6318. break;
  6319. case '#': /* argc */
  6320. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6321. break;
  6322. case '-': { /* active options */
  6323. /* Check set_mode() to see what option chars we support */
  6324. char *cp;
  6325. val = cp = G.optstring_buf;
  6326. if (G.o_opt[OPT_O_ERREXIT])
  6327. *cp++ = 'e';
  6328. if (G_interactive_fd)
  6329. *cp++ = 'i';
  6330. if (G_x_mode)
  6331. *cp++ = 'x';
  6332. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6333. * commands read but are not executed,
  6334. * so $- can not execute too, 'n' is never seen in $-.
  6335. */
  6336. if (G.opt_c)
  6337. *cp++ = 'c';
  6338. if (G.opt_s)
  6339. *cp++ = 's';
  6340. *cp = '\0';
  6341. break;
  6342. }
  6343. default:
  6344. val = get_local_var_value(var);
  6345. }
  6346. }
  6347. /* Handle any expansions */
  6348. if (exp_op == 'L') {
  6349. reinit_unicode_for_hush();
  6350. debug_printf_expand("expand: length(%s)=", val);
  6351. val = utoa(val ? unicode_strlen(val) : 0);
  6352. debug_printf_expand("%s\n", val);
  6353. } else if (exp_op) {
  6354. if (exp_op == '%' || exp_op == '#') {
  6355. /* Standard-mandated substring removal ops:
  6356. * ${parameter%word} - remove smallest suffix pattern
  6357. * ${parameter%%word} - remove largest suffix pattern
  6358. * ${parameter#word} - remove smallest prefix pattern
  6359. * ${parameter##word} - remove largest prefix pattern
  6360. *
  6361. * Word is expanded to produce a glob pattern.
  6362. * Then var's value is matched to it and matching part removed.
  6363. */
  6364. /* bash compat: if x is "" and no shrinking of it is possible,
  6365. * inner ${...} is not evaluated. Example:
  6366. * unset b; : ${a%${b=B}}; echo $b
  6367. * assignment b=B only happens if $a is not "".
  6368. */
  6369. if (val && val[0]) {
  6370. char *t;
  6371. char *exp_exp_word;
  6372. char *loc;
  6373. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6374. if (exp_op == *exp_word) /* ## or %% */
  6375. exp_word++;
  6376. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6377. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6378. if (exp_exp_word)
  6379. exp_word = exp_exp_word;
  6380. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6381. /*
  6382. * HACK ALERT. We depend here on the fact that
  6383. * G.global_argv and results of utoa and get_local_var_value
  6384. * are actually in writable memory:
  6385. * scan_and_match momentarily stores NULs there.
  6386. */
  6387. t = (char*)val;
  6388. loc = scan_and_match(t, exp_word, scan_flags);
  6389. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6390. free(exp_exp_word);
  6391. if (loc) { /* match was found */
  6392. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6393. val = loc; /* take right part */
  6394. else /* %[%] */
  6395. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6396. }
  6397. }
  6398. }
  6399. #if BASH_PATTERN_SUBST
  6400. else if (exp_op == '/' || exp_op == '\\') {
  6401. /* It's ${var/[/]pattern[/repl]} thing.
  6402. * Note that in encoded form it has TWO parts:
  6403. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6404. * and if // is used, it is encoded as \:
  6405. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6406. */
  6407. /* bash compat: if var is "", both pattern and repl
  6408. * are still evaluated, if it is unset, then not:
  6409. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6410. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6411. */
  6412. if (val /*&& val[0]*/) {
  6413. /* pattern uses non-standard expansion.
  6414. * repl should be unbackslashed and globbed
  6415. * by the usual expansion rules:
  6416. * >az >bz
  6417. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6418. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6419. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6420. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6421. * (note that a*z _pattern_ is never globbed!)
  6422. */
  6423. char *pattern, *repl, *t;
  6424. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6425. if (!pattern)
  6426. pattern = xstrdup(exp_word);
  6427. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6428. *p++ = SPECIAL_VAR_SYMBOL;
  6429. exp_word = p;
  6430. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6431. *p = '\0';
  6432. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6433. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6434. /* HACK ALERT. We depend here on the fact that
  6435. * G.global_argv and results of utoa and get_local_var_value
  6436. * are actually in writable memory:
  6437. * replace_pattern momentarily stores NULs there. */
  6438. t = (char*)val;
  6439. to_be_freed = replace_pattern(t,
  6440. pattern,
  6441. (repl ? repl : exp_word),
  6442. exp_op);
  6443. if (to_be_freed) /* at least one replace happened */
  6444. val = to_be_freed;
  6445. free(pattern);
  6446. free(repl);
  6447. } else {
  6448. /* Unset variable always gives nothing */
  6449. // a=; echo ${a/*/w} # "w"
  6450. // unset a; echo ${a/*/w} # ""
  6451. /* Just skip "replace" part */
  6452. *p++ = SPECIAL_VAR_SYMBOL;
  6453. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6454. *p = '\0';
  6455. }
  6456. }
  6457. #endif /* BASH_PATTERN_SUBST */
  6458. else if (exp_op == ':') {
  6459. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6460. /* It's ${var:N[:M]} bashism.
  6461. * Note that in encoded form it has TWO parts:
  6462. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6463. */
  6464. arith_t beg, len;
  6465. unsigned vallen;
  6466. const char *errmsg;
  6467. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6468. if (errmsg)
  6469. goto empty_result;
  6470. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6471. *p++ = SPECIAL_VAR_SYMBOL;
  6472. exp_word = p;
  6473. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6474. *p = '\0';
  6475. vallen = val ? strlen(val) : 0;
  6476. if (beg < 0) {
  6477. /* negative beg counts from the end */
  6478. beg = (arith_t)vallen + beg;
  6479. }
  6480. /* If expansion will be empty, do not even evaluate len */
  6481. if (!val || beg < 0 || beg > vallen) {
  6482. /* Why > vallen, not >=? bash:
  6483. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6484. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6485. */
  6486. goto empty_result;
  6487. }
  6488. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6489. if (errmsg)
  6490. goto empty_result;
  6491. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6492. debug_printf_varexp("from val:'%s'\n", val);
  6493. if (len < 0) {
  6494. /* in bash, len=-n means strlen()-n */
  6495. len = (arith_t)vallen - beg + len;
  6496. if (len < 0) /* bash compat */
  6497. msg_and_die_if_script("%s: substring expression < 0", var);
  6498. }
  6499. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6500. empty_result:
  6501. val = NULL;
  6502. } else {
  6503. /* Paranoia. What if user entered 9999999999999
  6504. * which fits in arith_t but not int? */
  6505. if (len > INT_MAX)
  6506. len = INT_MAX;
  6507. val = to_be_freed = xstrndup(val + beg, len);
  6508. }
  6509. debug_printf_varexp("val:'%s'\n", val);
  6510. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6511. msg_and_die_if_script("malformed ${%s:...}", var);
  6512. val = NULL;
  6513. #endif
  6514. } else { /* one of "-=+?" */
  6515. /* Standard-mandated substitution ops:
  6516. * ${var?word} - indicate error if unset
  6517. * If var is unset, word (or a message indicating it is unset
  6518. * if word is null) is written to standard error
  6519. * and the shell exits with a non-zero exit status.
  6520. * Otherwise, the value of var is substituted.
  6521. * ${var-word} - use default value
  6522. * If var is unset, word is substituted.
  6523. * ${var=word} - assign and use default value
  6524. * If var is unset, word is assigned to var.
  6525. * In all cases, final value of var is substituted.
  6526. * ${var+word} - use alternative value
  6527. * If var is unset, null is substituted.
  6528. * Otherwise, word is substituted.
  6529. *
  6530. * Word is subjected to tilde expansion, parameter expansion,
  6531. * command substitution, and arithmetic expansion.
  6532. * If word is not needed, it is not expanded.
  6533. *
  6534. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6535. * but also treat null var as if it is unset.
  6536. *
  6537. * Word-splitting and single quote behavior:
  6538. *
  6539. * $ f() { for i; do echo "|$i|"; done; }
  6540. *
  6541. * $ x=; f ${x:?'x y' z}; echo $?
  6542. * bash: x: x y z # neither f nor "echo $?" executes
  6543. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6544. * $ x=; f "${x:?'x y' z}"
  6545. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6546. *
  6547. * $ x=; f ${x:='x y' z}
  6548. * |x|
  6549. * |y|
  6550. * |z|
  6551. * $ x=; f "${x:='x y' z}"
  6552. * |'x y' z|
  6553. *
  6554. * $ x=x; f ${x:+'x y' z}
  6555. * |x y|
  6556. * |z|
  6557. * $ x=x; f "${x:+'x y' z}"
  6558. * |'x y' z|
  6559. *
  6560. * $ x=; f ${x:-'x y' z}
  6561. * |x y|
  6562. * |z|
  6563. * $ x=; f "${x:-'x y' z}"
  6564. * |'x y' z|
  6565. */
  6566. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6567. if (exp_op == '+')
  6568. use_word = !use_word;
  6569. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6570. (exp_save == ':') ? "true" : "false", use_word);
  6571. if (use_word) {
  6572. if (exp_op == '+' || exp_op == '-') {
  6573. /* ${var+word} - use alternative value */
  6574. /* ${var-word} - use default value */
  6575. n = encode_then_append_var_plusminus(output, n, exp_word,
  6576. /*dquoted:*/ (arg0 & 0x80)
  6577. );
  6578. val = NULL;
  6579. } else {
  6580. /* ${var?word} - indicate error if unset */
  6581. /* ${var=word} - assign and use default value */
  6582. to_be_freed = encode_then_expand_vararg(exp_word,
  6583. /*handle_squotes:*/ !(arg0 & 0x80),
  6584. /*unbackslash:*/ 0
  6585. );
  6586. if (to_be_freed)
  6587. exp_word = to_be_freed;
  6588. if (exp_op == '?') {
  6589. /* mimic bash message */
  6590. msg_and_die_if_script("%s: %s",
  6591. var,
  6592. exp_word[0]
  6593. ? exp_word
  6594. : "parameter null or not set"
  6595. /* ash has more specific messages, a-la: */
  6596. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6597. );
  6598. //TODO: how interactive bash aborts expansion mid-command?
  6599. //It aborts the entire line, returns to prompt:
  6600. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6601. // bash: x: x y z
  6602. // $
  6603. // ("echo YO" is not executed, neither the f function call)
  6604. } else {
  6605. val = exp_word;
  6606. }
  6607. if (exp_op == '=') {
  6608. /* ${var=[word]} or ${var:=[word]} */
  6609. if (isdigit(var[0]) || var[0] == '#') {
  6610. /* mimic bash message */
  6611. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6612. val = NULL;
  6613. } else {
  6614. char *new_var = xasprintf("%s=%s", var, val);
  6615. set_local_var0(new_var);
  6616. }
  6617. }
  6618. }
  6619. }
  6620. } /* one of "-=+?" */
  6621. *exp_saveptr = exp_save;
  6622. } /* if (exp_op) */
  6623. arg[0] = arg0;
  6624. *pp = p;
  6625. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6626. free(to_be_freed);
  6627. return n;
  6628. }
  6629. /* Expand all variable references in given string, adding words to list[]
  6630. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6631. * to be filled). This routine is extremely tricky: has to deal with
  6632. * variables/parameters with whitespace, $* and $@, and constructs like
  6633. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6634. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6635. {
  6636. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6637. * expansion of right-hand side of assignment == 1-element expand.
  6638. */
  6639. char cant_be_null = 0; /* only bit 0x80 matters */
  6640. char *p;
  6641. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6642. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6643. debug_print_list("expand_vars_to_list[0]", output, n);
  6644. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6645. char first_ch;
  6646. #if ENABLE_FEATURE_SH_MATH
  6647. char arith_buf[sizeof(arith_t)*3 + 2];
  6648. #endif
  6649. if (output->ended_in_ifs) {
  6650. o_addchr(output, '\0');
  6651. n = o_save_ptr(output, n);
  6652. output->ended_in_ifs = 0;
  6653. }
  6654. o_addblock(output, arg, p - arg);
  6655. debug_print_list("expand_vars_to_list[1]", output, n);
  6656. arg = ++p;
  6657. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6658. /* Fetch special var name (if it is indeed one of them)
  6659. * and quote bit, force the bit on if singleword expansion -
  6660. * important for not getting v=$@ expand to many words. */
  6661. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6662. /* Is this variable quoted and thus expansion can't be null?
  6663. * "$@" is special. Even if quoted, it can still
  6664. * expand to nothing (not even an empty string),
  6665. * thus it is excluded. */
  6666. if ((first_ch & 0x7f) != '@')
  6667. cant_be_null |= first_ch;
  6668. switch (first_ch & 0x7f) {
  6669. /* Highest bit in first_ch indicates that var is double-quoted */
  6670. case '*':
  6671. case '@': {
  6672. int i;
  6673. if (!G.global_argv[1])
  6674. break;
  6675. i = 1;
  6676. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6677. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6678. while (G.global_argv[i]) {
  6679. n = expand_on_ifs(output, n, G.global_argv[i]);
  6680. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6681. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6682. /* this argv[] is not empty and not last:
  6683. * put terminating NUL, start new word */
  6684. o_addchr(output, '\0');
  6685. debug_print_list("expand_vars_to_list[2]", output, n);
  6686. n = o_save_ptr(output, n);
  6687. debug_print_list("expand_vars_to_list[3]", output, n);
  6688. }
  6689. }
  6690. } else
  6691. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6692. * and in this case should treat it like '$*' - see 'else...' below */
  6693. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6694. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6695. ) {
  6696. while (1) {
  6697. o_addQstr(output, G.global_argv[i]);
  6698. if (++i >= G.global_argc)
  6699. break;
  6700. o_addchr(output, '\0');
  6701. debug_print_list("expand_vars_to_list[4]", output, n);
  6702. n = o_save_ptr(output, n);
  6703. }
  6704. } else { /* quoted $* (or v="$@" case): add as one word */
  6705. while (1) {
  6706. o_addQstr(output, G.global_argv[i]);
  6707. if (!G.global_argv[++i])
  6708. break;
  6709. if (G.ifs[0])
  6710. o_addchr(output, G.ifs[0]);
  6711. }
  6712. output->has_quoted_part = 1;
  6713. }
  6714. break;
  6715. }
  6716. case SPECIAL_VAR_SYMBOL: {
  6717. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6718. /* "Empty variable", used to make "" etc to not disappear */
  6719. output->has_quoted_part = 1;
  6720. cant_be_null = 0x80;
  6721. arg++;
  6722. break;
  6723. }
  6724. case SPECIAL_VAR_QUOTED_SVS:
  6725. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6726. /* "^C variable", represents literal ^C char (possible in scripts) */
  6727. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6728. arg++;
  6729. break;
  6730. #if ENABLE_HUSH_TICK
  6731. case '`': {
  6732. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6733. o_string subst_result = NULL_O_STRING;
  6734. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6735. arg++;
  6736. /* Can't just stuff it into output o_string,
  6737. * expanded result may need to be globbed
  6738. * and $IFS-split */
  6739. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6740. G.last_exitcode = process_command_subs(&subst_result, arg);
  6741. G.expand_exitcode = G.last_exitcode;
  6742. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6743. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6744. o_free(&subst_result);
  6745. break;
  6746. }
  6747. #endif
  6748. #if ENABLE_FEATURE_SH_MATH
  6749. case '+': {
  6750. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6751. arith_t res;
  6752. arg++; /* skip '+' */
  6753. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6754. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6755. res = expand_and_evaluate_arith(arg, NULL);
  6756. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6757. sprintf(arith_buf, ARITH_FMT, res);
  6758. if (res < 0
  6759. && first_ch == (char)('+'|0x80)
  6760. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6761. ) {
  6762. /* Quoted negative ariths, like filename[0"$((-9))"],
  6763. * should not be interpreted as glob ranges.
  6764. * Convert leading '-' to '\-':
  6765. */
  6766. o_grow_by(output, 1);
  6767. output->data[output->length++] = '\\';
  6768. }
  6769. o_addstr(output, arith_buf);
  6770. break;
  6771. }
  6772. #endif
  6773. default:
  6774. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6775. n = expand_one_var(output, n, first_ch, arg, &p);
  6776. break;
  6777. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6778. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6779. * Do the check to avoid writing to a const string. */
  6780. if (*p != SPECIAL_VAR_SYMBOL)
  6781. *p = SPECIAL_VAR_SYMBOL;
  6782. arg = ++p;
  6783. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6784. if (*arg) {
  6785. /* handle trailing string */
  6786. if (output->ended_in_ifs) {
  6787. o_addchr(output, '\0');
  6788. n = o_save_ptr(output, n);
  6789. }
  6790. debug_print_list("expand_vars_to_list[a]", output, n);
  6791. /* this part is literal, and it was already pre-quoted
  6792. * if needed (much earlier), do not use o_addQstr here!
  6793. */
  6794. o_addstr(output, arg);
  6795. debug_print_list("expand_vars_to_list[b]", output, n);
  6796. } else
  6797. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6798. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6799. && !output->has_quoted_part
  6800. ) {
  6801. n--;
  6802. /* allow to reuse list[n] later without re-growth */
  6803. output->has_empty_slot = 1;
  6804. }
  6805. return n;
  6806. }
  6807. static char **expand_variables(char **argv, unsigned expflags)
  6808. {
  6809. int n;
  6810. char **list;
  6811. o_string output = NULL_O_STRING;
  6812. output.o_expflags = expflags;
  6813. n = 0;
  6814. for (;;) {
  6815. /* go to next list[n] */
  6816. output.ended_in_ifs = 0;
  6817. n = o_save_ptr(&output, n);
  6818. if (!*argv)
  6819. break;
  6820. /* expand argv[i] */
  6821. n = expand_vars_to_list(&output, n, *argv++);
  6822. /* if (!output->has_empty_slot) -- need this?? */
  6823. o_addchr(&output, '\0');
  6824. }
  6825. debug_print_list("expand_variables", &output, n);
  6826. /* output.data (malloced in one block) gets returned in "list" */
  6827. list = o_finalize_list(&output, n);
  6828. debug_print_strings("expand_variables[1]", list);
  6829. return list;
  6830. }
  6831. static char **expand_strvec_to_strvec(char **argv)
  6832. {
  6833. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6834. }
  6835. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6836. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6837. {
  6838. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6839. }
  6840. #endif
  6841. /* Used for expansion of right hand of assignments,
  6842. * $((...)), heredocs, variable expansion parts.
  6843. *
  6844. * NB: should NOT do globbing!
  6845. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6846. */
  6847. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6848. {
  6849. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6850. const int do_unbackslash = 1;
  6851. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6852. #endif
  6853. char *argv[2], **list;
  6854. debug_printf_expand("string_to_string<='%s'\n", str);
  6855. /* This is generally an optimization, but it also
  6856. * handles "", which otherwise trips over !list[0] check below.
  6857. * (is this ever happens that we actually get str="" here?)
  6858. */
  6859. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6860. //TODO: Can use on strings with \ too, just unbackslash() them?
  6861. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6862. return xstrdup(str);
  6863. }
  6864. argv[0] = (char*)str;
  6865. argv[1] = NULL;
  6866. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6867. if (!list[0]) {
  6868. /* Example where it happens:
  6869. * x=; echo ${x:-"$@"}
  6870. */
  6871. ((char*)list)[0] = '\0';
  6872. } else {
  6873. if (HUSH_DEBUG)
  6874. if (list[1])
  6875. bb_simple_error_msg_and_die("BUG in varexp2");
  6876. /* actually, just move string 2*sizeof(char*) bytes back */
  6877. overlapping_strcpy((char*)list, list[0]);
  6878. if (do_unbackslash)
  6879. unbackslash((char*)list);
  6880. }
  6881. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6882. return (char*)list;
  6883. }
  6884. #if 0
  6885. static char* expand_strvec_to_string(char **argv)
  6886. {
  6887. char **list;
  6888. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6889. /* Convert all NULs to spaces */
  6890. if (list[0]) {
  6891. int n = 1;
  6892. while (list[n]) {
  6893. if (HUSH_DEBUG)
  6894. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6895. bb_error_msg_and_die("BUG in varexp3");
  6896. /* bash uses ' ' regardless of $IFS contents */
  6897. list[n][-1] = ' ';
  6898. n++;
  6899. }
  6900. }
  6901. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6902. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6903. return (char*)list;
  6904. }
  6905. #endif
  6906. static char **expand_assignments(char **argv, int count)
  6907. {
  6908. int i;
  6909. char **p;
  6910. G.expanded_assignments = p = NULL;
  6911. /* Expand assignments into one string each */
  6912. for (i = 0; i < count; i++) {
  6913. p = add_string_to_strings(p,
  6914. expand_string_to_string(argv[i],
  6915. EXP_FLAG_ESC_GLOB_CHARS,
  6916. /*unbackslash:*/ 1
  6917. )
  6918. );
  6919. G.expanded_assignments = p;
  6920. }
  6921. G.expanded_assignments = NULL;
  6922. return p;
  6923. }
  6924. static void switch_off_special_sigs(unsigned mask)
  6925. {
  6926. unsigned sig = 0;
  6927. while ((mask >>= 1) != 0) {
  6928. sig++;
  6929. if (!(mask & 1))
  6930. continue;
  6931. #if ENABLE_HUSH_TRAP
  6932. if (G_traps) {
  6933. if (G_traps[sig] && !G_traps[sig][0])
  6934. /* trap is '', has to remain SIG_IGN */
  6935. continue;
  6936. free(G_traps[sig]);
  6937. G_traps[sig] = NULL;
  6938. }
  6939. #endif
  6940. /* We are here only if no trap or trap was not '' */
  6941. install_sighandler(sig, SIG_DFL);
  6942. }
  6943. }
  6944. #if BB_MMU
  6945. /* never called */
  6946. void re_execute_shell(char ***to_free, const char *s,
  6947. char *g_argv0, char **g_argv,
  6948. char **builtin_argv) NORETURN;
  6949. static void reset_traps_to_defaults(void)
  6950. {
  6951. /* This function is always called in a child shell
  6952. * after fork (not vfork, NOMMU doesn't use this function).
  6953. */
  6954. IF_HUSH_TRAP(unsigned sig;)
  6955. unsigned mask;
  6956. /* Child shells are not interactive.
  6957. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6958. * Testcase: (while :; do :; done) + ^Z should background.
  6959. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6960. */
  6961. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6962. if (!G_traps && !mask)
  6963. return; /* already no traps and no special sigs */
  6964. /* Switch off special sigs */
  6965. switch_off_special_sigs(mask);
  6966. # if ENABLE_HUSH_JOB
  6967. G_fatal_sig_mask = 0;
  6968. # endif
  6969. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6970. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6971. * remain set in G.special_sig_mask */
  6972. # if ENABLE_HUSH_TRAP
  6973. if (!G_traps)
  6974. return;
  6975. /* Reset all sigs to default except ones with empty traps */
  6976. for (sig = 0; sig < NSIG; sig++) {
  6977. if (!G_traps[sig])
  6978. continue; /* no trap: nothing to do */
  6979. if (!G_traps[sig][0])
  6980. continue; /* empty trap: has to remain SIG_IGN */
  6981. /* sig has non-empty trap, reset it: */
  6982. free(G_traps[sig]);
  6983. G_traps[sig] = NULL;
  6984. /* There is no signal for trap 0 (EXIT) */
  6985. if (sig == 0)
  6986. continue;
  6987. install_sighandler(sig, pick_sighandler(sig));
  6988. }
  6989. # endif
  6990. }
  6991. #else /* !BB_MMU */
  6992. static void re_execute_shell(char ***to_free, const char *s,
  6993. char *g_argv0, char **g_argv,
  6994. char **builtin_argv) NORETURN;
  6995. static void re_execute_shell(char ***to_free, const char *s,
  6996. char *g_argv0, char **g_argv,
  6997. char **builtin_argv)
  6998. {
  6999. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  7000. /* delims + 2 * (number of bytes in printed hex numbers) */
  7001. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  7002. char *heredoc_argv[4];
  7003. struct variable *cur;
  7004. # if ENABLE_HUSH_FUNCTIONS
  7005. struct function *funcp;
  7006. # endif
  7007. char **argv, **pp;
  7008. unsigned cnt;
  7009. unsigned long long empty_trap_mask;
  7010. if (!g_argv0) { /* heredoc */
  7011. argv = heredoc_argv;
  7012. argv[0] = (char *) G.argv0_for_re_execing;
  7013. argv[1] = (char *) "-<";
  7014. argv[2] = (char *) s;
  7015. argv[3] = NULL;
  7016. pp = &argv[3]; /* used as pointer to empty environment */
  7017. goto do_exec;
  7018. }
  7019. cnt = 0;
  7020. pp = builtin_argv;
  7021. if (pp) while (*pp++)
  7022. cnt++;
  7023. empty_trap_mask = 0;
  7024. if (G_traps) {
  7025. int sig;
  7026. for (sig = 1; sig < NSIG; sig++) {
  7027. if (G_traps[sig] && !G_traps[sig][0])
  7028. empty_trap_mask |= 1LL << sig;
  7029. }
  7030. }
  7031. sprintf(param_buf, NOMMU_HACK_FMT
  7032. , (unsigned) G.root_pid
  7033. , (unsigned) G.root_ppid
  7034. , (unsigned) G.last_bg_pid
  7035. , (unsigned) G.last_exitcode
  7036. , cnt
  7037. , empty_trap_mask
  7038. IF_HUSH_LOOPS(, G.depth_of_loop)
  7039. );
  7040. # undef NOMMU_HACK_FMT
  7041. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  7042. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  7043. */
  7044. cnt += 6;
  7045. for (cur = G.top_var; cur; cur = cur->next) {
  7046. if (!cur->flg_export || cur->flg_read_only)
  7047. cnt += 2;
  7048. }
  7049. # if ENABLE_HUSH_LINENO_VAR
  7050. cnt += 2;
  7051. # endif
  7052. # if ENABLE_HUSH_FUNCTIONS
  7053. for (funcp = G.top_func; funcp; funcp = funcp->next)
  7054. cnt += 3;
  7055. # endif
  7056. pp = g_argv;
  7057. while (*pp++)
  7058. cnt++;
  7059. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  7060. *pp++ = (char *) G.argv0_for_re_execing;
  7061. *pp++ = param_buf;
  7062. for (cur = G.top_var; cur; cur = cur->next) {
  7063. if (strcmp(cur->varstr, hush_version_str) == 0)
  7064. continue;
  7065. if (cur->flg_read_only) {
  7066. *pp++ = (char *) "-R";
  7067. *pp++ = cur->varstr;
  7068. } else if (!cur->flg_export) {
  7069. *pp++ = (char *) "-V";
  7070. *pp++ = cur->varstr;
  7071. }
  7072. }
  7073. # if ENABLE_HUSH_LINENO_VAR
  7074. *pp++ = (char *) "-L";
  7075. *pp++ = utoa(G.execute_lineno);
  7076. # endif
  7077. # if ENABLE_HUSH_FUNCTIONS
  7078. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7079. *pp++ = (char *) "-F";
  7080. *pp++ = funcp->name;
  7081. *pp++ = funcp->body_as_string;
  7082. }
  7083. # endif
  7084. /* We can pass activated traps here. Say, -Tnn:trap_string
  7085. *
  7086. * However, POSIX says that subshells reset signals with traps
  7087. * to SIG_DFL.
  7088. * I tested bash-3.2 and it not only does that with true subshells
  7089. * of the form ( list ), but with any forked children shells.
  7090. * I set trap "echo W" WINCH; and then tried:
  7091. *
  7092. * { echo 1; sleep 20; echo 2; } &
  7093. * while true; do echo 1; sleep 20; echo 2; break; done &
  7094. * true | { echo 1; sleep 20; echo 2; } | cat
  7095. *
  7096. * In all these cases sending SIGWINCH to the child shell
  7097. * did not run the trap. If I add trap "echo V" WINCH;
  7098. * _inside_ group (just before echo 1), it works.
  7099. *
  7100. * I conclude it means we don't need to pass active traps here.
  7101. */
  7102. *pp++ = (char *) "-c";
  7103. *pp++ = (char *) s;
  7104. if (builtin_argv) {
  7105. while (*++builtin_argv)
  7106. *pp++ = *builtin_argv;
  7107. *pp++ = (char *) "";
  7108. }
  7109. *pp++ = g_argv0;
  7110. while (*g_argv)
  7111. *pp++ = *g_argv++;
  7112. /* *pp = NULL; - is already there */
  7113. pp = environ;
  7114. do_exec:
  7115. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7116. /* Don't propagate SIG_IGN to the child */
  7117. if (SPECIAL_JOBSTOP_SIGS != 0)
  7118. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7119. execve(bb_busybox_exec_path, argv, pp);
  7120. /* Fallback. Useful for init=/bin/hush usage etc */
  7121. if (argv[0][0] == '/')
  7122. execve(argv[0], argv, pp);
  7123. xfunc_error_retval = 127;
  7124. bb_simple_error_msg_and_die("can't re-execute the shell");
  7125. }
  7126. #endif /* !BB_MMU */
  7127. static int run_and_free_list(struct pipe *pi);
  7128. /* Executing from string: eval, sh -c '...'
  7129. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7130. * end_trigger controls how often we stop parsing
  7131. * NUL: parse all, execute, return
  7132. * ';': parse till ';' or newline, execute, repeat till EOF
  7133. */
  7134. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7135. {
  7136. /* Why we need empty flag?
  7137. * An obscure corner case "false; ``; echo $?":
  7138. * empty command in `` should still set $? to 0.
  7139. * But we can't just set $? to 0 at the start,
  7140. * this breaks "false; echo `echo $?`" case.
  7141. */
  7142. bool empty = 1;
  7143. while (1) {
  7144. struct pipe *pipe_list;
  7145. #if ENABLE_HUSH_INTERACTIVE
  7146. if (end_trigger == ';') {
  7147. G.promptmode = 0; /* PS1 */
  7148. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7149. }
  7150. #endif
  7151. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7152. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7153. /* If we are in "big" script
  7154. * (not in `cmd` or something similar)...
  7155. */
  7156. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7157. /* Discard cached input (rest of line) */
  7158. int ch = inp->last_char;
  7159. while (ch != EOF && ch != '\n') {
  7160. //bb_error_msg("Discarded:'%c'", ch);
  7161. ch = i_getch(inp);
  7162. }
  7163. /* Force prompt */
  7164. inp->p = NULL;
  7165. /* Clear "peeked" EOF. Without this,
  7166. * $ { cmd }<Enter>
  7167. * > ^D
  7168. * hush: syntax error: unterminated {
  7169. * exits interactive shell:
  7170. */
  7171. if (inp->peek_buf[0] == EOF)
  7172. inp->peek_buf[0] = 0;
  7173. /* This stream isn't empty */
  7174. empty = 0;
  7175. continue;
  7176. }
  7177. if (!pipe_list && empty)
  7178. G.last_exitcode = 0;
  7179. break;
  7180. }
  7181. debug_print_tree(pipe_list, 0);
  7182. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7183. run_and_free_list(pipe_list);
  7184. empty = 0;
  7185. if (G_flag_return_in_progress == 1)
  7186. break;
  7187. }
  7188. }
  7189. static void parse_and_run_string(const char *s)
  7190. {
  7191. struct in_str input;
  7192. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7193. setup_string_in_str(&input, s);
  7194. parse_and_run_stream(&input, '\0');
  7195. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7196. }
  7197. static void parse_and_run_file(HFILE *fp)
  7198. {
  7199. struct in_str input;
  7200. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7201. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7202. setup_file_in_str(&input, fp);
  7203. parse_and_run_stream(&input, ';');
  7204. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7205. }
  7206. #if ENABLE_HUSH_TICK
  7207. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7208. {
  7209. pid_t pid;
  7210. int channel[2];
  7211. # if !BB_MMU
  7212. char **to_free = NULL;
  7213. # endif
  7214. xpipe(channel);
  7215. pid = BB_MMU ? xfork() : xvfork();
  7216. if (pid == 0) { /* child */
  7217. disable_restore_tty_pgrp_on_exit();
  7218. /* Process substitution is not considered to be usual
  7219. * 'command execution'.
  7220. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7221. */
  7222. bb_signals(0
  7223. + (1 << SIGTSTP)
  7224. + (1 << SIGTTIN)
  7225. + (1 << SIGTTOU)
  7226. , SIG_IGN);
  7227. close(channel[0]); /* NB: close _first_, then move fd! */
  7228. xmove_fd(channel[1], 1);
  7229. # if ENABLE_HUSH_TRAP
  7230. /* Awful hack for `trap` or $(trap).
  7231. *
  7232. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7233. * contains an example where "trap" is executed in a subshell:
  7234. *
  7235. * save_traps=$(trap)
  7236. * ...
  7237. * eval "$save_traps"
  7238. *
  7239. * Standard does not say that "trap" in subshell shall print
  7240. * parent shell's traps. It only says that its output
  7241. * must have suitable form, but then, in the above example
  7242. * (which is not supposed to be normative), it implies that.
  7243. *
  7244. * bash (and probably other shell) does implement it
  7245. * (traps are reset to defaults, but "trap" still shows them),
  7246. * but as a result, "trap" logic is hopelessly messed up:
  7247. *
  7248. * # trap
  7249. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7250. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7251. * # true | trap <--- trap is in subshell - no output (ditto)
  7252. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7253. * trap -- 'echo Ho' SIGWINCH
  7254. * # echo `(trap)` <--- in subshell in subshell - output
  7255. * trap -- 'echo Ho' SIGWINCH
  7256. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7257. * trap -- 'echo Ho' SIGWINCH
  7258. *
  7259. * The rules when to forget and when to not forget traps
  7260. * get really complex and nonsensical.
  7261. *
  7262. * Our solution: ONLY bare $(trap) or `trap` is special.
  7263. */
  7264. s = skip_whitespace(s);
  7265. if (is_prefixed_with(s, "trap")
  7266. && skip_whitespace(s + 4)[0] == '\0'
  7267. ) {
  7268. static const char *const argv[] ALIGN_PTR = { NULL, NULL };
  7269. builtin_trap((char**)argv);
  7270. fflush_all(); /* important */
  7271. _exit(0);
  7272. }
  7273. # endif
  7274. # if BB_MMU
  7275. /* Prevent it from trying to handle ctrl-z etc */
  7276. IF_HUSH_JOB(G.run_list_level = 1;)
  7277. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7278. reset_traps_to_defaults();
  7279. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7280. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7281. parse_and_run_string(s);
  7282. _exit(G.last_exitcode);
  7283. # else
  7284. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7285. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7286. * huge=`cat BIG` # was blocking here forever
  7287. * echo OK
  7288. */
  7289. re_execute_shell(&to_free,
  7290. s,
  7291. G.global_argv[0],
  7292. G.global_argv + 1,
  7293. NULL);
  7294. # endif
  7295. }
  7296. /* parent */
  7297. *pid_p = pid;
  7298. # if ENABLE_HUSH_FAST
  7299. G.count_SIGCHLD++;
  7300. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7301. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7302. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7303. # endif
  7304. enable_restore_tty_pgrp_on_exit();
  7305. # if !BB_MMU
  7306. free(to_free);
  7307. # endif
  7308. close(channel[1]);
  7309. return channel[0];
  7310. }
  7311. /* Return code is exit status of the process that is run. */
  7312. static int process_command_subs(o_string *dest, const char *s)
  7313. {
  7314. FILE *fp;
  7315. pid_t pid;
  7316. int status, ch, eol_cnt;
  7317. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7318. /* Now send results of command back into original context */
  7319. eol_cnt = 0;
  7320. while ((ch = getc(fp)) != EOF) {
  7321. if (ch == '\0')
  7322. continue;
  7323. if (ch == '\n') {
  7324. eol_cnt++;
  7325. continue;
  7326. }
  7327. while (eol_cnt) {
  7328. o_addchr(dest, '\n');
  7329. eol_cnt--;
  7330. }
  7331. o_addQchr(dest, ch);
  7332. }
  7333. debug_printf("done reading from `cmd` pipe, closing it\n");
  7334. fclose(fp);
  7335. /* We need to extract exitcode. Test case
  7336. * "true; echo `sleep 1; false` $?"
  7337. * should print 1 */
  7338. safe_waitpid(pid, &status, 0);
  7339. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7340. return WEXITSTATUS(status);
  7341. }
  7342. #endif /* ENABLE_HUSH_TICK */
  7343. static void setup_heredoc(struct redir_struct *redir)
  7344. {
  7345. struct fd_pair pair;
  7346. pid_t pid;
  7347. int len, written;
  7348. /* the _body_ of heredoc (misleading field name) */
  7349. const char *heredoc = redir->rd_filename;
  7350. char *expanded;
  7351. #if !BB_MMU
  7352. char **to_free;
  7353. #endif
  7354. expanded = NULL;
  7355. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7356. expanded = encode_then_expand_string(heredoc);
  7357. if (expanded)
  7358. heredoc = expanded;
  7359. }
  7360. len = strlen(heredoc);
  7361. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7362. xpiped_pair(pair);
  7363. xmove_fd(pair.rd, redir->rd_fd);
  7364. /* Try writing without forking. Newer kernels have
  7365. * dynamically growing pipes. Must use non-blocking write! */
  7366. ndelay_on(pair.wr);
  7367. while (1) {
  7368. written = write(pair.wr, heredoc, len);
  7369. if (written <= 0)
  7370. break;
  7371. len -= written;
  7372. if (len == 0) {
  7373. close(pair.wr);
  7374. free(expanded);
  7375. return;
  7376. }
  7377. heredoc += written;
  7378. }
  7379. ndelay_off(pair.wr);
  7380. /* Okay, pipe buffer was not big enough */
  7381. /* Note: we must not create a stray child (bastard? :)
  7382. * for the unsuspecting parent process. Child creates a grandchild
  7383. * and exits before parent execs the process which consumes heredoc
  7384. * (that exec happens after we return from this function) */
  7385. #if !BB_MMU
  7386. to_free = NULL;
  7387. #endif
  7388. pid = xvfork();
  7389. if (pid == 0) {
  7390. /* child */
  7391. disable_restore_tty_pgrp_on_exit();
  7392. pid = BB_MMU ? xfork() : xvfork();
  7393. if (pid != 0)
  7394. _exit(0);
  7395. /* grandchild */
  7396. close(redir->rd_fd); /* read side of the pipe */
  7397. #if BB_MMU
  7398. full_write(pair.wr, heredoc, len); /* may loop or block */
  7399. _exit(0);
  7400. #else
  7401. /* Delegate blocking writes to another process */
  7402. xmove_fd(pair.wr, STDOUT_FILENO);
  7403. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7404. #endif
  7405. }
  7406. /* parent */
  7407. #if ENABLE_HUSH_FAST
  7408. G.count_SIGCHLD++;
  7409. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7410. #endif
  7411. enable_restore_tty_pgrp_on_exit();
  7412. #if !BB_MMU
  7413. free(to_free);
  7414. #endif
  7415. close(pair.wr);
  7416. free(expanded);
  7417. wait(NULL); /* wait till child has died */
  7418. }
  7419. struct squirrel {
  7420. int orig_fd;
  7421. int moved_to;
  7422. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7423. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7424. };
  7425. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7426. {
  7427. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7428. sq[i].orig_fd = orig;
  7429. sq[i].moved_to = moved;
  7430. sq[i+1].orig_fd = -1; /* end marker */
  7431. return sq;
  7432. }
  7433. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7434. {
  7435. int moved_to;
  7436. int i;
  7437. i = 0;
  7438. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7439. /* If we collide with an already moved fd... */
  7440. if (fd == sq[i].moved_to) {
  7441. moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7442. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, moved_to);
  7443. if (moved_to < 0) {
  7444. /* "echo 2>/dev/tty 10>&9999" testcase:
  7445. * We move fd 2 to 10, then discover we need to move fd 10
  7446. * (and not hit 9999) and the latter fails.
  7447. */
  7448. return NULL; /* fcntl failed */
  7449. }
  7450. sq[i].moved_to = moved_to;
  7451. return sq;
  7452. }
  7453. if (fd == sq[i].orig_fd) {
  7454. /* Example: echo Hello >/dev/null 1>&2 */
  7455. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7456. return sq;
  7457. }
  7458. }
  7459. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7460. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7461. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7462. if (moved_to < 0 && errno != EBADF)
  7463. return NULL; /* fcntl failed (not because fd is closed) */
  7464. return append_squirrel(sq, i, fd, moved_to);
  7465. }
  7466. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7467. {
  7468. int i;
  7469. i = 0;
  7470. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7471. /* If we collide with an already moved fd... */
  7472. if (fd == sq[i].orig_fd) {
  7473. /* Examples:
  7474. * "echo 3>FILE 3>&- 3>FILE"
  7475. * "echo 3>&- 3>FILE"
  7476. * No need for last redirect to insert
  7477. * another "need to close 3" indicator.
  7478. */
  7479. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7480. return sq;
  7481. }
  7482. }
  7483. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7484. return append_squirrel(sq, i, fd, -1);
  7485. }
  7486. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7487. * Move all conflicting internally used fds,
  7488. * and remember them so that we can restore them later.
  7489. */
  7490. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7491. {
  7492. struct squirrel *new_squirrel;
  7493. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7494. avoid_fd = 9;
  7495. #if ENABLE_HUSH_INTERACTIVE
  7496. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7497. && fd == G_interactive_fd
  7498. ) {
  7499. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7500. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7501. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7502. return 1; /* "we closed fd" */
  7503. }
  7504. #endif
  7505. /* Are we called from setup_redirects(squirrel==NULL)
  7506. * in redirect in a [v]forked child?
  7507. */
  7508. if (sqp == NULL) {
  7509. /* No need to move script fds.
  7510. * For NOMMU case, it's actively wrong: we'd change ->fd
  7511. * fields in memory for the parent, but parent's fds
  7512. * aren't moved, it would use wrong fd!
  7513. * Reproducer: "cmd 3>FILE" in script.
  7514. * If we would call move_HFILEs_on_redirect(), child would:
  7515. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7516. * close(3) = 0
  7517. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7518. */
  7519. //bb_error_msg("sqp == NULL: [v]forked child");
  7520. return 0;
  7521. }
  7522. /* If this one of script's fds? */
  7523. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7524. return 1; /* yes. "we closed fd" (actually moved it) */
  7525. /* Are we called for "exec 3>FILE"? Came through
  7526. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7527. * This case used to fail for this script:
  7528. * exec 3>FILE
  7529. * echo Ok
  7530. * ...100000 more lines...
  7531. * echo Ok
  7532. * as follows:
  7533. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7534. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7535. * dup2(4, 3) = 3
  7536. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7537. * close(4) = 0
  7538. * write(1, "Ok\n", 3) = 3
  7539. * ... = 3
  7540. * write(1, "Ok\n", 3) = 3
  7541. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7542. * ^^^^^^^^ oops, wrong fd!!!
  7543. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7544. * it now works:
  7545. */
  7546. if (sqp == ERR_PTR) {
  7547. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7548. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7549. return 0;
  7550. }
  7551. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7552. new_squirrel = add_squirrel(*sqp, fd, avoid_fd);
  7553. if (!new_squirrel)
  7554. return -1; /* redirect error */
  7555. *sqp = new_squirrel;
  7556. return 0; /* "we did not close fd" */
  7557. }
  7558. static void restore_redirects(struct squirrel *sq)
  7559. {
  7560. if (sq) {
  7561. int i;
  7562. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7563. if (sq[i].moved_to >= 0) {
  7564. /* We simply die on error */
  7565. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7566. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7567. } else {
  7568. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7569. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7570. close(sq[i].orig_fd);
  7571. }
  7572. }
  7573. free(sq);
  7574. }
  7575. if (G.HFILE_stdin
  7576. && G.HFILE_stdin->fd > STDIN_FILENO
  7577. /* we compare > STDIN, not == STDIN, since hfgetc()
  7578. * closes fd and sets ->fd to -1 if EOF is reached.
  7579. * Testcase: echo 'pwd' | hush
  7580. */
  7581. ) {
  7582. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7583. * Redirect moves ->fd to e.g. 10,
  7584. * and it is not restored above (we do not restore script fds
  7585. * after redirects, we just use new, "moved" fds).
  7586. * However for stdin, get_user_input() -> read_line_input(),
  7587. * and read builtin, depend on fd == STDIN_FILENO.
  7588. */
  7589. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7590. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7591. G.HFILE_stdin->fd = STDIN_FILENO;
  7592. }
  7593. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7594. }
  7595. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7596. static void close_saved_fds_and_FILE_fds(void)
  7597. {
  7598. if (G_interactive_fd)
  7599. close(G_interactive_fd);
  7600. close_all_HFILE_list();
  7601. }
  7602. #endif
  7603. static int internally_opened_fd(int fd, struct squirrel *sq)
  7604. {
  7605. int i;
  7606. #if ENABLE_HUSH_INTERACTIVE
  7607. if (fd == G_interactive_fd)
  7608. return 1;
  7609. #endif
  7610. /* If this one of script's fds? */
  7611. if (fd_in_HFILEs(fd))
  7612. return 1;
  7613. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7614. if (fd == sq[i].moved_to)
  7615. return 1;
  7616. }
  7617. return 0;
  7618. }
  7619. /* sqp != NULL means we squirrel away copies of stdin, stdout,
  7620. * and stderr if they are redirected.
  7621. * If redirection fails, return 1. This will make caller
  7622. * skip command execution and restore already created redirect fds.
  7623. */
  7624. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7625. {
  7626. struct redir_struct *redir;
  7627. for (redir = prog->redirects; redir; redir = redir->next) {
  7628. int newfd;
  7629. int closed;
  7630. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7631. /* "rd_fd<<HERE" case */
  7632. if (save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp) < 0)
  7633. return 1;
  7634. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7635. * of the heredoc */
  7636. debug_printf_redir("set heredoc '%s'\n",
  7637. redir->rd_filename);
  7638. setup_heredoc(redir);
  7639. continue;
  7640. }
  7641. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7642. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7643. char *p;
  7644. int mode;
  7645. if (redir->rd_filename == NULL) {
  7646. /* Examples:
  7647. * "cmd >" (no filename)
  7648. * "cmd > <file" (2nd redirect starts too early)
  7649. */
  7650. syntax_error("invalid redirect");
  7651. return 1;
  7652. }
  7653. mode = redir_table[redir->rd_type].mode;
  7654. p = expand_string_to_string(redir->rd_filename,
  7655. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7656. newfd = open_or_warn(p, mode);
  7657. free(p);
  7658. if (newfd < 0) {
  7659. /* Error message from open_or_warn can be lost
  7660. * if stderr has been redirected, but bash
  7661. * and ash both lose it as well
  7662. * (though zsh doesn't!)
  7663. */
  7664. return 1;
  7665. }
  7666. if (newfd == redir->rd_fd && sqp
  7667. && sqp != ERR_PTR /* not a redirect in "exec" */
  7668. ) {
  7669. /* open() gave us precisely the fd we wanted.
  7670. * This means that this fd was not busy
  7671. * (not opened to anywhere).
  7672. * Remember to close it on restore:
  7673. */
  7674. *sqp = add_squirrel_closed(*sqp, newfd);
  7675. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7676. }
  7677. } else {
  7678. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7679. newfd = redir->rd_dup;
  7680. }
  7681. if (newfd == redir->rd_fd)
  7682. continue;
  7683. /* if "N>FILE": move newfd to redir->rd_fd */
  7684. /* if "N>&M": dup newfd to redir->rd_fd */
  7685. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7686. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7687. if (closed < 0)
  7688. return 1; /* error */
  7689. if (newfd == REDIRFD_CLOSE) {
  7690. /* "N>&-" means "close me" */
  7691. if (!closed) {
  7692. /* ^^^ optimization: saving may already
  7693. * have closed it. If not... */
  7694. close(redir->rd_fd);
  7695. }
  7696. /* Sometimes we do another close on restore, getting EBADF.
  7697. * Consider "echo 3>FILE 3>&-"
  7698. * first redirect remembers "need to close 3",
  7699. * and second redirect closes 3! Restore code then closes 3 again.
  7700. */
  7701. } else {
  7702. /* if newfd is a script fd or saved fd, do not allow to use it */
  7703. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7704. bb_error_msg("fd#%d is not open", newfd);
  7705. return 1;
  7706. }
  7707. if (dup2(newfd, redir->rd_fd) < 0) {
  7708. /* "echo >&99" testcase */
  7709. bb_perror_msg("dup2(%d,%d)", newfd, redir->rd_fd);
  7710. return 1;
  7711. }
  7712. if (redir->rd_dup == REDIRFD_TO_FILE)
  7713. /* "rd_fd > FILE" */
  7714. close(newfd);
  7715. /* else: "rd_fd > rd_dup" */
  7716. }
  7717. }
  7718. return 0;
  7719. }
  7720. /* Find a file in PATH, not necessarily executable
  7721. * Name is known to not contain '/'.
  7722. */
  7723. //TODO: shares code with find_executable() in libbb, factor out?
  7724. static char *find_in_PATH(const char *name)
  7725. {
  7726. char *p = (char*) get_local_var_value("PATH");
  7727. if (!p)
  7728. return NULL;
  7729. while (1) {
  7730. const char *end = strchrnul(p, ':');
  7731. int sz = end - p; /* must be int! */
  7732. if (sz != 0) {
  7733. p = xasprintf("%.*s/%s", sz, p, name);
  7734. } else {
  7735. /* We have xxx::yyy in $PATH,
  7736. * it means "use current dir" */
  7737. p = xstrdup(name);
  7738. }
  7739. if (access(p, F_OK) == 0)
  7740. return p;
  7741. free(p);
  7742. if (*end == '\0')
  7743. return NULL;
  7744. p = (char *) end + 1;
  7745. }
  7746. }
  7747. #if ENABLE_HUSH_TYPE || ENABLE_HUSH_COMMAND
  7748. static char *find_executable_in_PATH(const char *name)
  7749. {
  7750. const char *PATH;
  7751. if (strchr(name, '/')) {
  7752. /* Name with '/' is tested verbatim, with no PATH traversal:
  7753. * "cd /bin; type ./cat" should print "./cat is ./cat",
  7754. * NOT "./cat is /bin/./cat"
  7755. */
  7756. if (file_is_executable(name))
  7757. return xstrdup(name);
  7758. return NULL;
  7759. }
  7760. PATH = get_local_var_value("PATH");
  7761. return find_executable(name, &PATH); /* path == NULL is ok */
  7762. }
  7763. #endif
  7764. static const struct built_in_command *find_builtin_helper(const char *name,
  7765. const struct built_in_command *x,
  7766. const struct built_in_command *end)
  7767. {
  7768. while (x != end) {
  7769. if (strcmp(name, x->b_cmd) != 0) {
  7770. x++;
  7771. continue;
  7772. }
  7773. debug_printf_exec("found builtin '%s'\n", name);
  7774. return x;
  7775. }
  7776. return NULL;
  7777. }
  7778. static const struct built_in_command *find_builtin1(const char *name)
  7779. {
  7780. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7781. }
  7782. static const struct built_in_command *find_builtin(const char *name)
  7783. {
  7784. const struct built_in_command *x = find_builtin1(name);
  7785. if (x)
  7786. return x;
  7787. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7788. }
  7789. #if ENABLE_HUSH_JOB && ENABLE_FEATURE_TAB_COMPLETION
  7790. static const char * FAST_FUNC hush_command_name(int i)
  7791. {
  7792. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7793. return bltins1[i].b_cmd;
  7794. }
  7795. i -= ARRAY_SIZE(bltins1);
  7796. if (i < ARRAY_SIZE(bltins2)) {
  7797. return bltins2[i].b_cmd;
  7798. }
  7799. # if ENABLE_HUSH_FUNCTIONS
  7800. {
  7801. struct function *funcp;
  7802. i -= ARRAY_SIZE(bltins2);
  7803. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7804. if (--i < 0)
  7805. return funcp->name;
  7806. }
  7807. }
  7808. # endif
  7809. return NULL;
  7810. }
  7811. #endif
  7812. static void remove_nested_vars(void)
  7813. {
  7814. struct variable *cur;
  7815. struct variable **cur_pp;
  7816. cur_pp = &G.top_var;
  7817. while ((cur = *cur_pp) != NULL) {
  7818. if (cur->var_nest_level <= G.var_nest_level) {
  7819. cur_pp = &cur->next;
  7820. continue;
  7821. }
  7822. /* Unexport */
  7823. if (cur->flg_export) {
  7824. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7825. bb_unsetenv(cur->varstr);
  7826. }
  7827. /* Remove from global list */
  7828. *cur_pp = cur->next;
  7829. /* Free */
  7830. if (!cur->max_len) {
  7831. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7832. free(cur->varstr);
  7833. }
  7834. free(cur);
  7835. }
  7836. }
  7837. static void enter_var_nest_level(void)
  7838. {
  7839. G.var_nest_level++;
  7840. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7841. /* Try: f() { echo -n .; f; }; f
  7842. * struct variable::var_nest_level is uint16_t,
  7843. * thus limiting recursion to < 2^16.
  7844. * In any case, with 8 Mbyte stack SEGV happens
  7845. * not too long after 2^16 recursions anyway.
  7846. */
  7847. if (G.var_nest_level > 0xff00)
  7848. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7849. }
  7850. static void leave_var_nest_level(void)
  7851. {
  7852. G.var_nest_level--;
  7853. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7854. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7855. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7856. remove_nested_vars();
  7857. }
  7858. #if ENABLE_HUSH_FUNCTIONS
  7859. static struct function **find_function_slot(const char *name)
  7860. {
  7861. struct function *funcp;
  7862. struct function **funcpp = &G.top_func;
  7863. while ((funcp = *funcpp) != NULL) {
  7864. if (strcmp(name, funcp->name) == 0) {
  7865. debug_printf_exec("found function '%s'\n", name);
  7866. break;
  7867. }
  7868. funcpp = &funcp->next;
  7869. }
  7870. return funcpp;
  7871. }
  7872. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7873. {
  7874. const struct function *funcp = *find_function_slot(name);
  7875. return funcp;
  7876. }
  7877. /* Note: takes ownership on name ptr */
  7878. static struct function *new_function(char *name)
  7879. {
  7880. struct function **funcpp = find_function_slot(name);
  7881. struct function *funcp = *funcpp;
  7882. if (funcp != NULL) {
  7883. struct command *cmd = funcp->parent_cmd;
  7884. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7885. if (!cmd) {
  7886. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7887. free(funcp->name);
  7888. /* Note: if !funcp->body, do not free body_as_string!
  7889. * This is a special case of "-F name body" function:
  7890. * body_as_string was not malloced! */
  7891. if (funcp->body) {
  7892. free_pipe_list(funcp->body);
  7893. # if !BB_MMU
  7894. free(funcp->body_as_string);
  7895. # endif
  7896. }
  7897. } else {
  7898. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7899. cmd->argv[0] = funcp->name;
  7900. cmd->group = funcp->body;
  7901. # if !BB_MMU
  7902. cmd->group_as_string = funcp->body_as_string;
  7903. # endif
  7904. }
  7905. } else {
  7906. debug_printf_exec("remembering new function '%s'\n", name);
  7907. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7908. /*funcp->next = NULL;*/
  7909. }
  7910. funcp->name = name;
  7911. return funcp;
  7912. }
  7913. # if ENABLE_HUSH_UNSET
  7914. static void unset_func(const char *name)
  7915. {
  7916. struct function **funcpp = find_function_slot(name);
  7917. struct function *funcp = *funcpp;
  7918. if (funcp != NULL) {
  7919. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7920. *funcpp = funcp->next;
  7921. /* funcp is unlinked now, deleting it.
  7922. * Note: if !funcp->body, the function was created by
  7923. * "-F name body", do not free ->body_as_string
  7924. * and ->name as they were not malloced. */
  7925. if (funcp->body) {
  7926. free_pipe_list(funcp->body);
  7927. free(funcp->name);
  7928. # if !BB_MMU
  7929. free(funcp->body_as_string);
  7930. # endif
  7931. }
  7932. free(funcp);
  7933. }
  7934. }
  7935. # endif
  7936. # if BB_MMU
  7937. #define exec_function(to_free, funcp, argv) \
  7938. exec_function(funcp, argv)
  7939. # endif
  7940. static void exec_function(char ***to_free,
  7941. const struct function *funcp,
  7942. char **argv) NORETURN;
  7943. static void exec_function(char ***to_free,
  7944. const struct function *funcp,
  7945. char **argv)
  7946. {
  7947. # if BB_MMU
  7948. int n;
  7949. argv[0] = G.global_argv[0];
  7950. G.global_argv = argv;
  7951. G.global_argc = n = 1 + string_array_len(argv + 1);
  7952. // Example when we are here: "cmd | func"
  7953. // func will run with saved-redirect fds open.
  7954. // $ f() { echo /proc/self/fd/*; }
  7955. // $ true | f
  7956. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7957. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7958. // Same in script:
  7959. // $ . ./SCRIPT
  7960. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7961. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7962. // They are CLOEXEC so external programs won't see them, but
  7963. // for "more correctness" we might want to close those extra fds here:
  7964. //? close_saved_fds_and_FILE_fds();
  7965. /* "we are in a function, ok to use return" */
  7966. G_flag_return_in_progress = -1;
  7967. enter_var_nest_level();
  7968. IF_HUSH_LOCAL(G.func_nest_level++;)
  7969. /* On MMU, funcp->body is always non-NULL */
  7970. n = run_list(funcp->body);
  7971. _exit(n);
  7972. # else
  7973. //? close_saved_fds_and_FILE_fds();
  7974. //TODO: check whether "true | func_with_return" works
  7975. re_execute_shell(to_free,
  7976. funcp->body_as_string,
  7977. G.global_argv[0],
  7978. argv + 1,
  7979. NULL);
  7980. # endif
  7981. }
  7982. static int run_function(const struct function *funcp, char **argv)
  7983. {
  7984. int rc;
  7985. save_arg_t sv;
  7986. smallint sv_flg;
  7987. save_and_replace_G_args(&sv, argv);
  7988. /* "We are in function, ok to use return" */
  7989. sv_flg = G_flag_return_in_progress;
  7990. G_flag_return_in_progress = -1;
  7991. /* Make "local" variables properly shadow previous ones */
  7992. IF_HUSH_LOCAL(enter_var_nest_level();)
  7993. IF_HUSH_LOCAL(G.func_nest_level++;)
  7994. /* On MMU, funcp->body is always non-NULL */
  7995. # if !BB_MMU
  7996. if (!funcp->body) {
  7997. /* Function defined by -F */
  7998. parse_and_run_string(funcp->body_as_string);
  7999. rc = G.last_exitcode;
  8000. } else
  8001. # endif
  8002. {
  8003. rc = run_list(funcp->body);
  8004. }
  8005. IF_HUSH_LOCAL(G.func_nest_level--;)
  8006. IF_HUSH_LOCAL(leave_var_nest_level();)
  8007. G_flag_return_in_progress = sv_flg;
  8008. # if ENABLE_HUSH_TRAP
  8009. debug_printf_exec("G.return_exitcode=-1\n");
  8010. G.return_exitcode = -1; /* invalidate stashed return value */
  8011. # endif
  8012. restore_G_args(&sv, argv);
  8013. return rc;
  8014. }
  8015. #endif /* ENABLE_HUSH_FUNCTIONS */
  8016. #if BB_MMU
  8017. #define exec_builtin(to_free, x, argv) \
  8018. exec_builtin(x, argv)
  8019. #else
  8020. #define exec_builtin(to_free, x, argv) \
  8021. exec_builtin(to_free, argv)
  8022. #endif
  8023. static void exec_builtin(char ***to_free,
  8024. const struct built_in_command *x,
  8025. char **argv) NORETURN;
  8026. static void exec_builtin(char ***to_free,
  8027. const struct built_in_command *x,
  8028. char **argv)
  8029. {
  8030. #if BB_MMU
  8031. int rcode;
  8032. //? close_saved_fds_and_FILE_fds();
  8033. rcode = x->b_function(argv);
  8034. fflush_all();
  8035. _exit(rcode);
  8036. #else
  8037. fflush_all();
  8038. /* On NOMMU, we must never block!
  8039. * Example: { sleep 99 | read line; } & echo Ok
  8040. */
  8041. re_execute_shell(to_free,
  8042. argv[0],
  8043. G.global_argv[0],
  8044. G.global_argv + 1,
  8045. argv);
  8046. #endif
  8047. }
  8048. static void execvp_or_die(char **argv) NORETURN;
  8049. static void execvp_or_die(char **argv)
  8050. {
  8051. int e;
  8052. debug_printf_exec("execing '%s'\n", argv[0]);
  8053. /* Don't propagate SIG_IGN to the child */
  8054. if (SPECIAL_JOBSTOP_SIGS != 0)
  8055. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8056. execvp(argv[0], argv);
  8057. e = 2;
  8058. if (errno == EACCES) e = 126;
  8059. if (errno == ENOENT) e = 127;
  8060. bb_perror_msg("can't execute '%s'", argv[0]);
  8061. _exit(e);
  8062. }
  8063. #if ENABLE_HUSH_MODE_X
  8064. static void x_mode_print_optionally_squoted(const char *str)
  8065. {
  8066. unsigned len;
  8067. const char *cp;
  8068. cp = str;
  8069. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  8070. /* test a char with: bash -c 'set -x; echo "CH"' */
  8071. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  8072. " " "\001\002\003\004\005\006\007"
  8073. "\010\011\012\013\014\015\016\017"
  8074. "\020\021\022\023\024\025\026\027"
  8075. "\030\031\032\033\034\035\036\037"
  8076. )
  8077. ] == '\0'
  8078. ) {
  8079. /* string has no special chars */
  8080. x_mode_addstr(str);
  8081. return;
  8082. }
  8083. cp = str;
  8084. for (;;) {
  8085. /* print '....' up to EOL or first squote */
  8086. len = (int)(strchrnul(cp, '\'') - cp);
  8087. if (len != 0) {
  8088. x_mode_addchr('\'');
  8089. x_mode_addblock(cp, len);
  8090. x_mode_addchr('\'');
  8091. cp += len;
  8092. }
  8093. if (*cp == '\0')
  8094. break;
  8095. /* string contains squote(s), print them as \' */
  8096. x_mode_addchr('\\');
  8097. x_mode_addchr('\'');
  8098. cp++;
  8099. }
  8100. }
  8101. static void dump_cmd_in_x_mode(char **argv)
  8102. {
  8103. if (G_x_mode && argv) {
  8104. unsigned n;
  8105. /* "+[+++...][ cmd...]\n\0" */
  8106. x_mode_prefix();
  8107. n = 0;
  8108. while (argv[n]) {
  8109. x_mode_addchr(' ');
  8110. if (argv[n][0] == '\0') {
  8111. x_mode_addchr('\'');
  8112. x_mode_addchr('\'');
  8113. } else {
  8114. x_mode_print_optionally_squoted(argv[n]);
  8115. }
  8116. n++;
  8117. }
  8118. x_mode_flush();
  8119. }
  8120. }
  8121. #else
  8122. # define dump_cmd_in_x_mode(argv) ((void)0)
  8123. #endif
  8124. #if ENABLE_HUSH_COMMAND
  8125. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  8126. {
  8127. char *to_free;
  8128. if (!opt_vV)
  8129. return;
  8130. to_free = NULL;
  8131. if (!explanation) {
  8132. explanation = to_free = find_executable_in_PATH(cmd);
  8133. if (!explanation) {
  8134. bb_error_msg("%s: %s: not found", "command", cmd);
  8135. _exit(1); /* PROG was not found */
  8136. }
  8137. if (opt_vV != 'V')
  8138. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  8139. }
  8140. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  8141. free(to_free);
  8142. fflush_all();
  8143. _exit(0);
  8144. }
  8145. #else
  8146. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  8147. #endif
  8148. #if BB_MMU
  8149. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  8150. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  8151. #define pseudo_exec(nommu_save, command, argv_expanded) \
  8152. pseudo_exec(command, argv_expanded)
  8153. #endif
  8154. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  8155. * Never returns.
  8156. * Don't exit() here. If you don't exec, use _exit instead.
  8157. * The at_exit handlers apparently confuse the calling process,
  8158. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  8159. */
  8160. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8161. char **argv, int assignment_cnt,
  8162. char **argv_expanded) NORETURN;
  8163. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8164. char **argv, int assignment_cnt,
  8165. char **argv_expanded)
  8166. {
  8167. const struct built_in_command *x;
  8168. struct variable **sv_shadowed;
  8169. char **new_env;
  8170. IF_HUSH_COMMAND(char opt_vV = 0;)
  8171. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8172. new_env = expand_assignments(argv, assignment_cnt);
  8173. dump_cmd_in_x_mode(new_env);
  8174. if (!argv[assignment_cnt]) {
  8175. /* Case when we are here: ... | var=val | ...
  8176. * (note that we do not exit early, i.e., do not optimize out
  8177. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8178. */
  8179. free_strings(new_env);
  8180. _exit_SUCCESS();
  8181. }
  8182. sv_shadowed = G.shadowed_vars_pp;
  8183. #if BB_MMU
  8184. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8185. #else
  8186. G.shadowed_vars_pp = &nommu_save->old_vars;
  8187. G.var_nest_level++;
  8188. #endif
  8189. set_vars_and_save_old(new_env);
  8190. G.shadowed_vars_pp = sv_shadowed;
  8191. if (argv_expanded) {
  8192. argv = argv_expanded;
  8193. } else {
  8194. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8195. #if !BB_MMU
  8196. nommu_save->argv = argv;
  8197. #endif
  8198. }
  8199. dump_cmd_in_x_mode(argv);
  8200. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8201. if (strchr(argv[0], '/') != NULL)
  8202. goto skip;
  8203. #endif
  8204. #if ENABLE_HUSH_FUNCTIONS
  8205. /* Check if the command matches any functions (this goes before bltins) */
  8206. funcp = find_function(argv[0]);
  8207. if (funcp)
  8208. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8209. #endif
  8210. #if ENABLE_HUSH_COMMAND
  8211. /* "command BAR": run BAR without looking it up among functions
  8212. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8213. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8214. */
  8215. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8216. char *p;
  8217. argv++;
  8218. p = *argv;
  8219. if (p[0] != '-' || !p[1])
  8220. continue; /* bash allows "command command command [-OPT] BAR" */
  8221. for (;;) {
  8222. p++;
  8223. switch (*p) {
  8224. case '\0':
  8225. argv++;
  8226. p = *argv;
  8227. if (p[0] != '-' || !p[1])
  8228. goto after_opts;
  8229. continue; /* next arg is also -opts, process it too */
  8230. case 'v':
  8231. case 'V':
  8232. opt_vV = *p;
  8233. continue;
  8234. default:
  8235. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8236. }
  8237. }
  8238. }
  8239. after_opts:
  8240. # if ENABLE_HUSH_FUNCTIONS
  8241. if (opt_vV && find_function(argv[0]))
  8242. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8243. # endif
  8244. #endif
  8245. /* Check if the command matches any of the builtins.
  8246. * Depending on context, this might be redundant. But it's
  8247. * easier to waste a few CPU cycles than it is to figure out
  8248. * if this is one of those cases.
  8249. */
  8250. /* Why "BB_MMU ? :" difference in logic? -
  8251. * On NOMMU, it is more expensive to re-execute shell
  8252. * just in order to run echo or test builtin.
  8253. * It's better to skip it here and run corresponding
  8254. * non-builtin later. */
  8255. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8256. if (x) {
  8257. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8258. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8259. }
  8260. #if ENABLE_FEATURE_SH_STANDALONE
  8261. /* Check if the command matches any busybox applets */
  8262. {
  8263. int a = find_applet_by_name(argv[0]);
  8264. if (a >= 0) {
  8265. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8266. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8267. if (APPLET_IS_NOEXEC(a)) {
  8268. /* Do not leak open fds from opened script files etc.
  8269. * Testcase: interactive "ls -l /proc/self/fd"
  8270. * should not show tty fd open.
  8271. */
  8272. close_saved_fds_and_FILE_fds();
  8273. //FIXME: should also close saved redir fds
  8274. //This casuses test failures in
  8275. //redir_children_should_not_see_saved_fd_2.tests
  8276. //redir_children_should_not_see_saved_fd_3.tests
  8277. //if you replace "busybox find" with just "find" in them
  8278. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8279. switch_off_special_sigs(G.special_sig_mask);
  8280. debug_printf_exec("running applet '%s'\n", argv[0]);
  8281. run_noexec_applet_and_exit(a, argv[0], argv);
  8282. }
  8283. # endif
  8284. /* Re-exec ourselves */
  8285. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8286. /* Don't propagate SIG_IGN to the child */
  8287. if (SPECIAL_JOBSTOP_SIGS != 0)
  8288. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8289. execv(bb_busybox_exec_path, argv);
  8290. /* If they called chroot or otherwise made the binary no longer
  8291. * executable, fall through */
  8292. }
  8293. }
  8294. #endif
  8295. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8296. skip:
  8297. #endif
  8298. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8299. execvp_or_die(argv);
  8300. }
  8301. /* Called after [v]fork() in run_pipe
  8302. */
  8303. static void pseudo_exec(nommu_save_t *nommu_save,
  8304. struct command *command,
  8305. char **argv_expanded) NORETURN;
  8306. static void pseudo_exec(nommu_save_t *nommu_save,
  8307. struct command *command,
  8308. char **argv_expanded)
  8309. {
  8310. #if ENABLE_HUSH_FUNCTIONS
  8311. if (command->cmd_type == CMD_FUNCDEF) {
  8312. /* Ignore funcdefs in pipes:
  8313. * true | f() { cmd }
  8314. */
  8315. _exit(0);
  8316. }
  8317. #endif
  8318. if (command->argv) {
  8319. pseudo_exec_argv(nommu_save, command->argv,
  8320. command->assignment_cnt, argv_expanded);
  8321. }
  8322. if (command->group) {
  8323. /* Cases when we are here:
  8324. * ( list )
  8325. * { list } &
  8326. * ... | ( list ) | ...
  8327. * ... | { list } | ...
  8328. */
  8329. #if BB_MMU
  8330. int rcode;
  8331. debug_printf_exec("pseudo_exec: run_list\n");
  8332. reset_traps_to_defaults();
  8333. rcode = run_list(command->group);
  8334. /* OK to leak memory by not calling free_pipe_list,
  8335. * since this process is about to exit */
  8336. _exit(rcode);
  8337. #else
  8338. re_execute_shell(&nommu_save->argv_from_re_execing,
  8339. command->group_as_string,
  8340. G.global_argv[0],
  8341. G.global_argv + 1,
  8342. NULL);
  8343. #endif
  8344. }
  8345. /* Case when we are here: ... | >file */
  8346. debug_printf_exec("pseudo_exec'ed null command\n");
  8347. _exit_SUCCESS();
  8348. }
  8349. #if ENABLE_HUSH_JOB
  8350. static const char *get_cmdtext(struct pipe *pi)
  8351. {
  8352. char **argv;
  8353. char *p;
  8354. int len;
  8355. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8356. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8357. * On subsequent bg argv is trashed, but we won't use it */
  8358. if (pi->cmdtext)
  8359. return pi->cmdtext;
  8360. argv = pi->cmds[0].argv;
  8361. if (!argv) {
  8362. pi->cmdtext = xzalloc(1);
  8363. return pi->cmdtext;
  8364. }
  8365. len = 0;
  8366. do {
  8367. len += strlen(*argv) + 1;
  8368. } while (*++argv);
  8369. p = xmalloc(len);
  8370. pi->cmdtext = p;
  8371. argv = pi->cmds[0].argv;
  8372. do {
  8373. p = stpcpy(p, *argv);
  8374. *p++ = ' ';
  8375. } while (*++argv);
  8376. p[-1] = '\0';
  8377. return pi->cmdtext;
  8378. }
  8379. static void remove_job_from_table(struct pipe *pi)
  8380. {
  8381. struct pipe *prev_pipe;
  8382. if (pi == G.job_list) {
  8383. G.job_list = pi->next;
  8384. } else {
  8385. prev_pipe = G.job_list;
  8386. while (prev_pipe->next != pi)
  8387. prev_pipe = prev_pipe->next;
  8388. prev_pipe->next = pi->next;
  8389. }
  8390. G.last_jobid = 0;
  8391. if (G.job_list)
  8392. G.last_jobid = G.job_list->jobid;
  8393. }
  8394. static void delete_finished_job(struct pipe *pi)
  8395. {
  8396. remove_job_from_table(pi);
  8397. free_pipe(pi);
  8398. }
  8399. static void clean_up_last_dead_job(void)
  8400. {
  8401. if (G.job_list && !G.job_list->alive_cmds)
  8402. delete_finished_job(G.job_list);
  8403. }
  8404. static void insert_job_into_table(struct pipe *pi)
  8405. {
  8406. struct pipe *job, **jobp;
  8407. int i;
  8408. clean_up_last_dead_job();
  8409. /* Find the end of the list, and find next job ID to use */
  8410. i = 0;
  8411. jobp = &G.job_list;
  8412. while ((job = *jobp) != NULL) {
  8413. if (job->jobid > i)
  8414. i = job->jobid;
  8415. jobp = &job->next;
  8416. }
  8417. pi->jobid = i + 1;
  8418. /* Create a new job struct at the end */
  8419. job = *jobp = xmemdup(pi, sizeof(*pi));
  8420. job->next = NULL;
  8421. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8422. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8423. for (i = 0; i < pi->num_cmds; i++) {
  8424. job->cmds[i].pid = pi->cmds[i].pid;
  8425. /* all other fields are not used and stay zero */
  8426. }
  8427. job->cmdtext = xstrdup(get_cmdtext(pi));
  8428. if (G_interactive_fd)
  8429. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8430. G.last_jobid = job->jobid;
  8431. }
  8432. #endif /* JOB */
  8433. static int job_exited_or_stopped(struct pipe *pi)
  8434. {
  8435. int rcode, i;
  8436. if (pi->alive_cmds != pi->stopped_cmds)
  8437. return -1;
  8438. /* All processes in fg pipe have exited or stopped */
  8439. rcode = 0;
  8440. i = pi->num_cmds;
  8441. while (--i >= 0) {
  8442. rcode = pi->cmds[i].cmd_exitcode;
  8443. /* usually last process gives overall exitstatus,
  8444. * but with "set -o pipefail", last *failed* process does */
  8445. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8446. break;
  8447. }
  8448. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8449. return rcode;
  8450. }
  8451. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8452. {
  8453. #if ENABLE_HUSH_JOB
  8454. struct pipe *pi;
  8455. #endif
  8456. int i, dead;
  8457. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8458. #if DEBUG_JOBS
  8459. if (WIFSTOPPED(status))
  8460. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8461. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8462. if (WIFSIGNALED(status))
  8463. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8464. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8465. if (WIFEXITED(status))
  8466. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8467. childpid, WEXITSTATUS(status));
  8468. #endif
  8469. /* Were we asked to wait for a fg pipe? */
  8470. if (fg_pipe) {
  8471. i = fg_pipe->num_cmds;
  8472. while (--i >= 0) {
  8473. int rcode;
  8474. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8475. if (fg_pipe->cmds[i].pid != childpid)
  8476. continue;
  8477. if (dead) {
  8478. int ex;
  8479. fg_pipe->cmds[i].pid = 0;
  8480. fg_pipe->alive_cmds--;
  8481. ex = WEXITSTATUS(status);
  8482. /* bash prints killer signal's name for *last*
  8483. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8484. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8485. */
  8486. if (WIFSIGNALED(status)) {
  8487. int sig = WTERMSIG(status);
  8488. #if ENABLE_HUSH_JOB
  8489. if (G.run_list_level == 1
  8490. /* ^^^^^ Do not print in nested contexts, example:
  8491. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8492. */
  8493. && i == fg_pipe->num_cmds-1
  8494. ) {
  8495. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8496. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8497. }
  8498. #endif
  8499. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8500. /* MIPS has 128 sigs (1..128), if sig==128,
  8501. * 128 + sig would result in exitcode 256 -> 0!
  8502. */
  8503. ex = 128 | sig;
  8504. }
  8505. fg_pipe->cmds[i].cmd_exitcode = ex;
  8506. } else {
  8507. fg_pipe->stopped_cmds++;
  8508. }
  8509. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8510. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8511. rcode = job_exited_or_stopped(fg_pipe);
  8512. if (rcode >= 0) {
  8513. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8514. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8515. * and "killall -STOP cat" */
  8516. if (G_interactive_fd) {
  8517. #if ENABLE_HUSH_JOB
  8518. if (fg_pipe->alive_cmds != 0)
  8519. insert_job_into_table(fg_pipe);
  8520. #endif
  8521. return rcode;
  8522. }
  8523. if (fg_pipe->alive_cmds == 0)
  8524. return rcode;
  8525. }
  8526. /* There are still running processes in the fg_pipe */
  8527. return -1;
  8528. }
  8529. /* It wasn't in fg_pipe, look for process in bg pipes */
  8530. }
  8531. #if ENABLE_HUSH_JOB
  8532. /* We were asked to wait for bg or orphaned children */
  8533. /* No need to remember exitcode in this case */
  8534. for (pi = G.job_list; pi; pi = pi->next) {
  8535. for (i = 0; i < pi->num_cmds; i++) {
  8536. if (pi->cmds[i].pid == childpid)
  8537. goto found_pi_and_prognum;
  8538. }
  8539. }
  8540. /* Happens when shell is used as init process (init=/bin/sh) */
  8541. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8542. return -1; /* this wasn't a process from fg_pipe */
  8543. found_pi_and_prognum:
  8544. if (dead) {
  8545. /* child exited */
  8546. int rcode = WEXITSTATUS(status);
  8547. if (WIFSIGNALED(status))
  8548. /* NB: not 128 + sig, MIPS has sig 128 */
  8549. rcode = 128 | WTERMSIG(status);
  8550. pi->cmds[i].cmd_exitcode = rcode;
  8551. if (G.last_bg_pid == pi->cmds[i].pid)
  8552. G.last_bg_pid_exitcode = rcode;
  8553. pi->cmds[i].pid = 0;
  8554. pi->alive_cmds--;
  8555. if (!pi->alive_cmds) {
  8556. # if ENABLE_HUSH_BASH_COMPAT
  8557. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8558. # endif
  8559. if (G_interactive_fd) {
  8560. printf(JOB_STATUS_FORMAT, pi->jobid,
  8561. "Done", pi->cmdtext);
  8562. delete_finished_job(pi);
  8563. } else {
  8564. /*
  8565. * bash deletes finished jobs from job table only in interactive mode,
  8566. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8567. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8568. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8569. * We only retain one "dead" job, if it's the single job on the list.
  8570. * This covers most of real-world scenarios where this is useful.
  8571. */
  8572. if (pi != G.job_list)
  8573. delete_finished_job(pi);
  8574. }
  8575. }
  8576. } else {
  8577. /* child stopped */
  8578. pi->stopped_cmds++;
  8579. }
  8580. #endif
  8581. return -1; /* this wasn't a process from fg_pipe */
  8582. }
  8583. /* Check to see if any processes have exited -- if they have,
  8584. * figure out why and see if a job has completed.
  8585. *
  8586. * If non-NULL fg_pipe: wait for its completion or stop.
  8587. * Return its exitcode or zero if stopped.
  8588. *
  8589. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8590. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8591. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8592. * or 0 if no children changed status.
  8593. *
  8594. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8595. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8596. * or 0 if no children changed status.
  8597. */
  8598. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8599. {
  8600. int attributes;
  8601. int status;
  8602. int rcode = 0;
  8603. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8604. attributes = WUNTRACED;
  8605. if (fg_pipe == NULL)
  8606. attributes |= WNOHANG;
  8607. errno = 0;
  8608. #if ENABLE_HUSH_FAST
  8609. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8610. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8611. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8612. /* There was neither fork nor SIGCHLD since last waitpid */
  8613. /* Avoid doing waitpid syscall if possible */
  8614. if (!G.we_have_children) {
  8615. errno = ECHILD;
  8616. return -1;
  8617. }
  8618. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8619. /* We have children, but they did not exit
  8620. * or stop yet (we saw no SIGCHLD) */
  8621. return 0;
  8622. }
  8623. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8624. }
  8625. #endif
  8626. /* Do we do this right?
  8627. * bash-3.00# sleep 20 | false
  8628. * <ctrl-Z pressed>
  8629. * [3]+ Stopped sleep 20 | false
  8630. * bash-3.00# echo $?
  8631. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8632. * [hush 1.14.0: yes we do it right]
  8633. */
  8634. while (1) {
  8635. pid_t childpid;
  8636. #if ENABLE_HUSH_FAST
  8637. int i;
  8638. i = G.count_SIGCHLD;
  8639. #endif
  8640. childpid = waitpid(-1, &status, attributes);
  8641. if (childpid <= 0) {
  8642. if (childpid && errno != ECHILD)
  8643. bb_simple_perror_msg("waitpid");
  8644. #if ENABLE_HUSH_FAST
  8645. else { /* Until next SIGCHLD, waitpid's are useless */
  8646. G.we_have_children = (childpid == 0);
  8647. G.handled_SIGCHLD = i;
  8648. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8649. }
  8650. #endif
  8651. /* ECHILD (no children), or 0 (no change in children status) */
  8652. rcode = childpid;
  8653. break;
  8654. }
  8655. rcode = process_wait_result(fg_pipe, childpid, status);
  8656. if (rcode >= 0) {
  8657. /* fg_pipe exited or stopped */
  8658. break;
  8659. }
  8660. if (childpid == waitfor_pid) { /* "wait PID" */
  8661. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8662. rcode = WEXITSTATUS(status);
  8663. if (WIFSIGNALED(status))
  8664. rcode = 128 | WTERMSIG(status);
  8665. if (WIFSTOPPED(status))
  8666. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8667. rcode = 128 | WSTOPSIG(status);
  8668. rcode++;
  8669. break; /* "wait PID" called us, give it exitcode+1 */
  8670. }
  8671. #if ENABLE_HUSH_BASH_COMPAT
  8672. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8673. && G.dead_job_exitcode >= 0 /* some job did finish */
  8674. ) {
  8675. debug_printf_exec("waitfor_pid:-1\n");
  8676. rcode = G.dead_job_exitcode + 1;
  8677. break;
  8678. }
  8679. #endif
  8680. /* This wasn't one of our processes, or */
  8681. /* fg_pipe still has running processes, do waitpid again */
  8682. } /* while (waitpid succeeds)... */
  8683. return rcode;
  8684. }
  8685. #if ENABLE_HUSH_JOB
  8686. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8687. {
  8688. pid_t p;
  8689. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8690. if (G_saved_tty_pgrp) {
  8691. /* Job finished, move the shell to the foreground */
  8692. p = getpgrp(); /* our process group id */
  8693. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8694. tcsetpgrp(G_interactive_fd, p);
  8695. }
  8696. return rcode;
  8697. }
  8698. #endif
  8699. /* Start all the jobs, but don't wait for anything to finish.
  8700. * See checkjobs().
  8701. *
  8702. * Return code is normally -1, when the caller has to wait for children
  8703. * to finish to determine the exit status of the pipe. If the pipe
  8704. * is a simple builtin command, however, the action is done by the
  8705. * time run_pipe returns, and the exit code is provided as the
  8706. * return value.
  8707. *
  8708. * Returns -1 only if started some children. IOW: we have to
  8709. * mask out retvals of builtins etc with 0xff!
  8710. *
  8711. * The only case when we do not need to [v]fork is when the pipe
  8712. * is single, non-backgrounded, non-subshell command. Examples:
  8713. * cmd ; ... { list } ; ...
  8714. * cmd && ... { list } && ...
  8715. * cmd || ... { list } || ...
  8716. * If it is, then we can run cmd as a builtin, NOFORK,
  8717. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8718. * with run_list. If it isn't one of these, we fork and exec cmd.
  8719. *
  8720. * Cases when we must fork:
  8721. * non-single: cmd | cmd
  8722. * backgrounded: cmd & { list } &
  8723. * subshell: ( list ) [&]
  8724. */
  8725. static void set_G_ifs(void)
  8726. {
  8727. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8728. * Result should be 3 lines: q w e, qwe, q w e
  8729. */
  8730. if (G.ifs_whitespace != G.ifs)
  8731. free(G.ifs_whitespace);
  8732. G.ifs = get_local_var_value("IFS");
  8733. if (G.ifs) {
  8734. char *p;
  8735. G.ifs_whitespace = (char*)G.ifs;
  8736. p = skip_whitespace(G.ifs);
  8737. if (*p) {
  8738. /* Not all $IFS is whitespace */
  8739. char *d;
  8740. int len = p - G.ifs;
  8741. p = skip_non_whitespace(p);
  8742. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8743. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8744. while (*p) {
  8745. if (isspace(*p))
  8746. *d++ = *p;
  8747. p++;
  8748. }
  8749. *d = '\0';
  8750. }
  8751. } else {
  8752. G.ifs = defifs;
  8753. G.ifs_whitespace = (char*)G.ifs;
  8754. }
  8755. }
  8756. #if !ENABLE_HUSH_MODE_X
  8757. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8758. redirect_and_varexp_helper(command, sqp)
  8759. #endif
  8760. static int redirect_and_varexp_helper(
  8761. struct command *command,
  8762. struct squirrel **sqp,
  8763. char **argv_expanded)
  8764. {
  8765. /* Assignments occur before redirects. Try:
  8766. * a=`sleep 1` sleep 2 3>/qwe/rty
  8767. */
  8768. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8769. dump_cmd_in_x_mode(new_env);
  8770. dump_cmd_in_x_mode(argv_expanded);
  8771. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8772. set_vars_and_save_old(new_env);
  8773. return setup_redirects(command, sqp);
  8774. }
  8775. static NOINLINE int run_pipe(struct pipe *pi)
  8776. {
  8777. static const char *const null_ptr = NULL;
  8778. int cmd_no;
  8779. int next_infd;
  8780. struct command *command;
  8781. char **argv_expanded;
  8782. char **argv;
  8783. struct squirrel *squirrel = NULL;
  8784. int rcode;
  8785. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8786. debug_enter();
  8787. set_G_ifs();
  8788. IF_HUSH_JOB(pi->pgrp = -1;)
  8789. pi->stopped_cmds = 0;
  8790. command = &pi->cmds[0];
  8791. argv_expanded = NULL;
  8792. if (pi->num_cmds != 1
  8793. || pi->followup == PIPE_BG
  8794. || command->cmd_type == CMD_SUBSHELL
  8795. ) {
  8796. goto must_fork;
  8797. }
  8798. pi->alive_cmds = 1;
  8799. debug_printf_exec(": group:%p argv:'%s'\n",
  8800. command->group, command->argv ? command->argv[0] : "NONE");
  8801. if (command->group) {
  8802. #if ENABLE_HUSH_FUNCTIONS
  8803. if (command->cmd_type == CMD_FUNCDEF) {
  8804. /* "executing" func () { list } */
  8805. struct function *funcp;
  8806. funcp = new_function(command->argv[0]);
  8807. /* funcp->name is already set to argv[0] */
  8808. funcp->body = command->group;
  8809. # if !BB_MMU
  8810. funcp->body_as_string = command->group_as_string;
  8811. command->group_as_string = NULL;
  8812. # endif
  8813. command->group = NULL;
  8814. command->argv[0] = NULL;
  8815. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8816. funcp->parent_cmd = command;
  8817. command->child_func = funcp;
  8818. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8819. debug_leave();
  8820. return EXIT_SUCCESS;
  8821. }
  8822. #endif
  8823. /* { list } */
  8824. debug_printf_exec("non-subshell group\n");
  8825. rcode = 1; /* exitcode if redir failed */
  8826. if (setup_redirects(command, &squirrel) == 0) {
  8827. debug_printf_exec(": run_list\n");
  8828. //FIXME: we need to pass squirrel down into run_list()
  8829. //for SH_STANDALONE case, or else this construct:
  8830. // { find /proc/self/fd; true; } >FILE; cmd2
  8831. //has no way of closing saved fd#1 for "find",
  8832. //and in SH_STANDALONE mode, "find" is not execed,
  8833. //therefore CLOEXEC on saved fd does not help.
  8834. rcode = run_list(command->group) & 0xff;
  8835. }
  8836. restore_redirects(squirrel);
  8837. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8838. debug_leave();
  8839. debug_printf_exec("run_pipe: return %d\n", rcode);
  8840. return rcode;
  8841. }
  8842. argv = command->argv ? command->argv : (char **) &null_ptr;
  8843. {
  8844. const struct built_in_command *x;
  8845. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8846. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8847. struct variable **sv_shadowed;
  8848. struct variable *old_vars;
  8849. #if ENABLE_HUSH_LINENO_VAR
  8850. G.execute_lineno = command->lineno;
  8851. #endif
  8852. if (argv[command->assignment_cnt] == NULL) {
  8853. /* Assignments, but no command.
  8854. * Ensure redirects take effect (that is, create files).
  8855. * Try "a=t >file"
  8856. */
  8857. unsigned i;
  8858. G.expand_exitcode = 0;
  8859. only_assignments:
  8860. rcode = setup_redirects(command, &squirrel);
  8861. restore_redirects(squirrel);
  8862. /* Set shell variables */
  8863. i = 0;
  8864. while (i < command->assignment_cnt) {
  8865. char *p = expand_string_to_string(argv[i],
  8866. EXP_FLAG_ESC_GLOB_CHARS,
  8867. /*unbackslash:*/ 1
  8868. );
  8869. #if ENABLE_HUSH_MODE_X
  8870. if (G_x_mode) {
  8871. char *eq;
  8872. if (i == 0)
  8873. x_mode_prefix();
  8874. x_mode_addchr(' ');
  8875. eq = strchrnul(p, '=');
  8876. if (*eq) eq++;
  8877. x_mode_addblock(p, (eq - p));
  8878. x_mode_print_optionally_squoted(eq);
  8879. x_mode_flush();
  8880. }
  8881. #endif
  8882. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8883. if (set_local_var0(p)) {
  8884. /* assignment to readonly var / putenv error? */
  8885. rcode = 1;
  8886. }
  8887. i++;
  8888. }
  8889. /* Redirect error sets $? to 1. Otherwise,
  8890. * if evaluating assignment value set $?, retain it.
  8891. * Else, clear $?:
  8892. * false; q=`exit 2`; echo $? - should print 2
  8893. * false; x=1; echo $? - should print 0
  8894. * Because of the 2nd case, we can't just use G.last_exitcode.
  8895. */
  8896. if (rcode == 0)
  8897. rcode = G.expand_exitcode;
  8898. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8899. debug_leave();
  8900. debug_printf_exec("run_pipe: return %d\n", rcode);
  8901. return rcode;
  8902. }
  8903. /* Expand the rest into (possibly) many strings each */
  8904. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8905. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8906. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8907. else
  8908. #endif
  8909. #if defined(CMD_SINGLEWORD_NOGLOB)
  8910. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8911. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8912. else
  8913. #endif
  8914. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8915. /* If someone gives us an empty string: `cmd with empty output` */
  8916. if (!argv_expanded[0]) {
  8917. free(argv_expanded);
  8918. /* `false` still has to set exitcode 1 */
  8919. G.expand_exitcode = G.last_exitcode;
  8920. goto only_assignments;
  8921. }
  8922. old_vars = NULL;
  8923. sv_shadowed = G.shadowed_vars_pp;
  8924. /* Check if argv[0] matches any functions (this goes before bltins) */
  8925. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8926. IF_HUSH_FUNCTIONS(x = NULL;)
  8927. IF_HUSH_FUNCTIONS(if (!funcp))
  8928. x = find_builtin(argv_expanded[0]);
  8929. if (x || funcp) {
  8930. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8931. debug_printf("exec with redirects only\n");
  8932. /*
  8933. * Variable assignments are executed, but then "forgotten":
  8934. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8935. * sleeps, but prints nothing.
  8936. */
  8937. enter_var_nest_level();
  8938. G.shadowed_vars_pp = &old_vars;
  8939. rcode = redirect_and_varexp_helper(command,
  8940. /*squirrel:*/ ERR_PTR,
  8941. argv_expanded
  8942. );
  8943. G.shadowed_vars_pp = sv_shadowed;
  8944. /* rcode=1 can be if redir file can't be opened */
  8945. goto clean_up_and_ret1;
  8946. }
  8947. /* Bump var nesting, or this will leak exported $a:
  8948. * a=b true; env | grep ^a=
  8949. */
  8950. enter_var_nest_level();
  8951. /* Collect all variables "shadowed" by helper
  8952. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8953. * into old_vars list:
  8954. */
  8955. G.shadowed_vars_pp = &old_vars;
  8956. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8957. if (rcode == 0) {
  8958. if (!funcp) {
  8959. /* Do not collect *to old_vars list* vars shadowed
  8960. * by e.g. "local VAR" builtin (collect them
  8961. * in the previously nested list instead):
  8962. * don't want them to be restored immediately
  8963. * after "local" completes.
  8964. */
  8965. G.shadowed_vars_pp = sv_shadowed;
  8966. debug_printf_exec(": builtin '%s' '%s'...\n",
  8967. x->b_cmd, argv_expanded[1]);
  8968. fflush_all();
  8969. rcode = x->b_function(argv_expanded) & 0xff;
  8970. fflush_all();
  8971. }
  8972. #if ENABLE_HUSH_FUNCTIONS
  8973. else {
  8974. debug_printf_exec(": function '%s' '%s'...\n",
  8975. funcp->name, argv_expanded[1]);
  8976. rcode = run_function(funcp, argv_expanded) & 0xff;
  8977. /*
  8978. * But do collect *to old_vars list* vars shadowed
  8979. * within function execution. To that end, restore
  8980. * this pointer _after_ function run:
  8981. */
  8982. G.shadowed_vars_pp = sv_shadowed;
  8983. }
  8984. #endif
  8985. }
  8986. } else
  8987. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8988. int n = find_applet_by_name(argv_expanded[0]);
  8989. if (n < 0 || !APPLET_IS_NOFORK(n))
  8990. goto must_fork;
  8991. enter_var_nest_level();
  8992. /* Collect all variables "shadowed" by helper into old_vars list */
  8993. G.shadowed_vars_pp = &old_vars;
  8994. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8995. G.shadowed_vars_pp = sv_shadowed;
  8996. if (rcode == 0) {
  8997. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8998. argv_expanded[0], argv_expanded[1]);
  8999. /*
  9000. * Note: signals (^C) can't interrupt here.
  9001. * We remember them and they will be acted upon
  9002. * after applet returns.
  9003. * This makes applets which can run for a long time
  9004. * and/or wait for user input ineligible for NOFORK:
  9005. * for example, "yes" or "rm" (rm -i waits for input).
  9006. */
  9007. rcode = run_nofork_applet(n, argv_expanded);
  9008. }
  9009. } else
  9010. goto must_fork;
  9011. restore_redirects(squirrel);
  9012. clean_up_and_ret1:
  9013. leave_var_nest_level();
  9014. add_vars(old_vars);
  9015. /*
  9016. * Try "usleep 99999999" + ^C + "echo $?"
  9017. * with FEATURE_SH_NOFORK=y.
  9018. */
  9019. if (!funcp) {
  9020. /* It was builtin or nofork.
  9021. * if this would be a real fork/execed program,
  9022. * it should have died if a fatal sig was received.
  9023. * But OTOH, there was no separate process,
  9024. * the sig was sent to _shell_, not to non-existing
  9025. * child.
  9026. * Let's just handle ^C only, this one is obvious:
  9027. * we aren't ok with exitcode 0 when ^C was pressed
  9028. * during builtin/nofork.
  9029. */
  9030. if (sigismember(&G.pending_set, SIGINT))
  9031. rcode = 128 | SIGINT;
  9032. }
  9033. free(argv_expanded);
  9034. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  9035. debug_leave();
  9036. debug_printf_exec("run_pipe return %d\n", rcode);
  9037. return rcode;
  9038. }
  9039. must_fork:
  9040. /* NB: argv_expanded may already be created, and that
  9041. * might include `cmd` runs! Do not rerun it! We *must*
  9042. * use argv_expanded if it's non-NULL */
  9043. /* Going to fork a child per each pipe member */
  9044. pi->alive_cmds = 0;
  9045. next_infd = 0;
  9046. cmd_no = 0;
  9047. while (cmd_no < pi->num_cmds) {
  9048. struct fd_pair pipefds;
  9049. #if !BB_MMU
  9050. int sv_var_nest_level = G.var_nest_level;
  9051. volatile nommu_save_t nommu_save;
  9052. nommu_save.old_vars = NULL;
  9053. nommu_save.argv = NULL;
  9054. nommu_save.argv_from_re_execing = NULL;
  9055. #endif
  9056. command = &pi->cmds[cmd_no];
  9057. cmd_no++;
  9058. if (command->argv) {
  9059. debug_printf_exec(": pipe member '%s' '%s'...\n",
  9060. command->argv[0], command->argv[1]);
  9061. } else {
  9062. debug_printf_exec(": pipe member with no argv\n");
  9063. }
  9064. /* pipes are inserted between pairs of commands */
  9065. pipefds.rd = 0;
  9066. pipefds.wr = 1;
  9067. if (cmd_no < pi->num_cmds)
  9068. xpiped_pair(pipefds);
  9069. #if ENABLE_HUSH_LINENO_VAR
  9070. G.execute_lineno = command->lineno;
  9071. #endif
  9072. command->pid = BB_MMU ? fork() : vfork();
  9073. if (!command->pid) { /* child */
  9074. #if ENABLE_HUSH_JOB
  9075. disable_restore_tty_pgrp_on_exit();
  9076. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  9077. /* Every child adds itself to new process group
  9078. * with pgid == pid_of_first_child_in_pipe */
  9079. if (G.run_list_level == 1 && G_interactive_fd) {
  9080. pid_t pgrp;
  9081. pgrp = pi->pgrp;
  9082. if (pgrp < 0) /* true for 1st process only */
  9083. pgrp = getpid();
  9084. if (setpgid(0, pgrp) == 0
  9085. && pi->followup != PIPE_BG
  9086. && G_saved_tty_pgrp /* we have ctty */
  9087. ) {
  9088. /* We do it in *every* child, not just first,
  9089. * to avoid races */
  9090. tcsetpgrp(G_interactive_fd, pgrp);
  9091. }
  9092. }
  9093. #endif
  9094. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  9095. /* 1st cmd in backgrounded pipe
  9096. * should have its stdin /dev/null'ed */
  9097. close(0);
  9098. if (open(bb_dev_null, O_RDONLY))
  9099. xopen("/", O_RDONLY);
  9100. } else {
  9101. xmove_fd(next_infd, 0);
  9102. }
  9103. xmove_fd(pipefds.wr, 1);
  9104. if (pipefds.rd > 1)
  9105. close(pipefds.rd);
  9106. /* Like bash, explicit redirects override pipes,
  9107. * and the pipe fd (fd#1) is available for dup'ing:
  9108. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  9109. * of cmd1 goes into pipe.
  9110. */
  9111. if (setup_redirects(command, NULL)) {
  9112. /* Happens when redir file can't be opened:
  9113. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  9114. * FOO
  9115. * hush: can't open '/qwe/rty': No such file or directory
  9116. * BAZ
  9117. * (echo BAR is not executed, it hits _exit(1) below)
  9118. */
  9119. _exit(1);
  9120. }
  9121. /* Stores to nommu_save list of env vars putenv'ed
  9122. * (NOMMU, on MMU we don't need that) */
  9123. /* cast away volatility... */
  9124. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  9125. /* pseudo_exec() does not return */
  9126. }
  9127. /* parent or error */
  9128. #if ENABLE_HUSH_FAST
  9129. G.count_SIGCHLD++;
  9130. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  9131. #endif
  9132. enable_restore_tty_pgrp_on_exit();
  9133. #if !BB_MMU
  9134. /* Clean up after vforked child */
  9135. free(nommu_save.argv);
  9136. free(nommu_save.argv_from_re_execing);
  9137. G.var_nest_level = sv_var_nest_level;
  9138. remove_nested_vars();
  9139. add_vars(nommu_save.old_vars);
  9140. #endif
  9141. free(argv_expanded);
  9142. argv_expanded = NULL;
  9143. if (command->pid < 0) { /* [v]fork failed */
  9144. /* Clearly indicate, was it fork or vfork */
  9145. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  9146. } else {
  9147. pi->alive_cmds++;
  9148. #if ENABLE_HUSH_JOB
  9149. /* Second and next children need to know pid of first one */
  9150. if (pi->pgrp < 0)
  9151. pi->pgrp = command->pid;
  9152. #endif
  9153. }
  9154. if (cmd_no > 1)
  9155. close(next_infd);
  9156. if (cmd_no < pi->num_cmds)
  9157. close(pipefds.wr);
  9158. /* Pass read (output) pipe end to next iteration */
  9159. next_infd = pipefds.rd;
  9160. }
  9161. if (!pi->alive_cmds) {
  9162. debug_leave();
  9163. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9164. return 1;
  9165. }
  9166. debug_leave();
  9167. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9168. return -1;
  9169. }
  9170. /* NB: called by pseudo_exec, and therefore must not modify any
  9171. * global data until exec/_exit (we can be a child after vfork!) */
  9172. static int run_list(struct pipe *pi)
  9173. {
  9174. #if ENABLE_HUSH_CASE
  9175. char *case_word = NULL;
  9176. #endif
  9177. #if ENABLE_HUSH_LOOPS
  9178. struct pipe *loop_top = NULL;
  9179. char **for_lcur = NULL;
  9180. char **for_list = NULL;
  9181. #endif
  9182. smallint last_followup;
  9183. smalluint rcode;
  9184. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9185. smalluint cond_code = 0;
  9186. #else
  9187. enum { cond_code = 0 };
  9188. #endif
  9189. #if HAS_KEYWORDS
  9190. smallint rword; /* RES_foo */
  9191. smallint last_rword; /* ditto */
  9192. #endif
  9193. debug_printf_exec("run_list lvl %d start\n", G.run_list_level);
  9194. debug_enter();
  9195. set_G_ifs();
  9196. #if ENABLE_HUSH_LOOPS
  9197. /* Check syntax for "for" */
  9198. {
  9199. struct pipe *cpipe;
  9200. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9201. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9202. continue;
  9203. /* current word is FOR or IN (BOLD in comments below) */
  9204. if (cpipe->next == NULL) {
  9205. syntax_error("malformed for");
  9206. debug_leave();
  9207. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9208. return 1;
  9209. }
  9210. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9211. if (cpipe->next->res_word == RES_DO)
  9212. continue;
  9213. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9214. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9215. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9216. ) {
  9217. syntax_error("malformed for");
  9218. debug_leave();
  9219. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9220. return 1;
  9221. }
  9222. }
  9223. }
  9224. #endif
  9225. /* Past this point, all code paths should jump to ret: label
  9226. * in order to return, no direct "return" statements please.
  9227. * This helps to ensure that no memory is leaked. */
  9228. #if ENABLE_HUSH_JOB
  9229. G.run_list_level++;
  9230. #endif
  9231. #if HAS_KEYWORDS
  9232. rword = RES_NONE;
  9233. last_rword = RES_XXXX;
  9234. #endif
  9235. last_followup = PIPE_SEQ;
  9236. rcode = G.last_exitcode;
  9237. /* Go through list of pipes, (maybe) executing them. */
  9238. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9239. int r;
  9240. int sv_errexit_depth;
  9241. if (G.flag_SIGINT)
  9242. break;
  9243. if (G_flag_return_in_progress == 1)
  9244. break;
  9245. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9246. debug_printf_exec(": rword:%d cond_code:%d last_rword:%d\n",
  9247. rword, cond_code, last_rword);
  9248. sv_errexit_depth = G.errexit_depth;
  9249. if (
  9250. #if ENABLE_HUSH_IF
  9251. rword == RES_IF || rword == RES_ELIF ||
  9252. #endif
  9253. pi->followup != PIPE_SEQ
  9254. ) {
  9255. G.errexit_depth++;
  9256. }
  9257. #if ENABLE_HUSH_LOOPS
  9258. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9259. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9260. ) {
  9261. /* start of a loop: remember where loop starts */
  9262. loop_top = pi;
  9263. G.depth_of_loop++;
  9264. }
  9265. #endif
  9266. /* Still in the same "if...", "then..." or "do..." branch? */
  9267. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9268. if ((rcode == 0 && last_followup == PIPE_OR)
  9269. || (rcode != 0 && last_followup == PIPE_AND)
  9270. ) {
  9271. /* It is "<true> || CMD" or "<false> && CMD"
  9272. * and we should not execute CMD */
  9273. debug_printf_exec("skipped cmd because of || or &&\n");
  9274. last_followup = pi->followup;
  9275. goto dont_check_jobs_but_continue;
  9276. }
  9277. }
  9278. last_followup = pi->followup;
  9279. #if ENABLE_HUSH_IF
  9280. if (cond_code != 0) {
  9281. if (rword == RES_THEN) {
  9282. /* if false; then ... fi has exitcode 0! */
  9283. G.last_exitcode = rcode = EXIT_SUCCESS;
  9284. /* "if <false> THEN cmd": skip cmd */
  9285. debug_printf_exec("skipped THEN cmd because IF condition was false\n");
  9286. last_rword = rword;
  9287. continue;
  9288. }
  9289. } else {
  9290. if (rword == RES_ELSE
  9291. || (rword == RES_ELIF && last_rword != RES_ELIF)
  9292. ) {
  9293. /* "if <true> then ... ELSE/ELIF cmd":
  9294. * skip cmd and all following ones */
  9295. debug_printf_exec("skipped ELSE/ELIF branch because IF condition was true\n");
  9296. break;
  9297. }
  9298. //if (rword == RES_THEN): "if <true> THEN cmd", run cmd (fall through)
  9299. }
  9300. #endif
  9301. IF_HAS_KEYWORDS(last_rword = rword;)
  9302. #if ENABLE_HUSH_LOOPS
  9303. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9304. if (!for_lcur) {
  9305. /* first loop through for */
  9306. static const char encoded_dollar_at[] ALIGN1 = {
  9307. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9308. }; /* encoded representation of "$@" */
  9309. static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
  9310. encoded_dollar_at, NULL
  9311. }; /* argv list with one element: "$@" */
  9312. char **vals;
  9313. G.last_exitcode = rcode = EXIT_SUCCESS;
  9314. vals = (char**)encoded_dollar_at_argv;
  9315. if (pi->next->res_word == RES_IN) {
  9316. /* if no variable values after "in" we skip "for" */
  9317. if (!pi->next->cmds[0].argv) {
  9318. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9319. break;
  9320. }
  9321. vals = pi->next->cmds[0].argv;
  9322. } /* else: "for var; do..." -> assume "$@" list */
  9323. /* create list of variable values */
  9324. debug_print_strings("for_list made from", vals);
  9325. for_list = expand_strvec_to_strvec(vals);
  9326. for_lcur = for_list;
  9327. debug_print_strings("for_list", for_list);
  9328. }
  9329. if (!*for_lcur) {
  9330. /* "for" loop is over, clean up */
  9331. free(for_list);
  9332. for_list = NULL;
  9333. for_lcur = NULL;
  9334. break;
  9335. }
  9336. /* Insert next value from for_lcur */
  9337. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9338. set_local_var_from_halves(pi->cmds[0].argv[0], *for_lcur++);
  9339. continue;
  9340. }
  9341. if (rword == RES_IN) {
  9342. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9343. }
  9344. if (rword == RES_DONE) {
  9345. continue; /* "done" has no cmds too */
  9346. }
  9347. #endif
  9348. #if ENABLE_HUSH_CASE
  9349. if (rword == RES_CASE) {
  9350. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9351. case_word = expand_string_to_string(pi->cmds->argv[0],
  9352. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9353. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9354. //unbackslash(case_word);
  9355. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9356. continue;
  9357. }
  9358. if (rword == RES_MATCH) {
  9359. char **argv;
  9360. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9361. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9362. break;
  9363. /* all prev words didn't match, does this one match? */
  9364. argv = pi->cmds->argv;
  9365. while (*argv) {
  9366. char *pattern;
  9367. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9368. pattern = expand_string_to_string(*argv,
  9369. EXP_FLAG_ESC_GLOB_CHARS,
  9370. /*unbackslash:*/ 0
  9371. );
  9372. /* TODO: which FNM_xxx flags to use? */
  9373. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9374. debug_printf_exec("cond_code=fnmatch(pattern:'%s',str:'%s'):%d\n",
  9375. pattern, case_word, cond_code);
  9376. free(pattern);
  9377. if (cond_code == 0) {
  9378. /* match! we will execute this branch */
  9379. free(case_word);
  9380. case_word = NULL; /* make future "word)" stop */
  9381. break;
  9382. }
  9383. argv++;
  9384. }
  9385. continue;
  9386. }
  9387. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9388. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9389. if (cond_code != 0)
  9390. continue; /* not matched yet, skip this pipe */
  9391. }
  9392. if (rword == RES_ESAC) {
  9393. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9394. if (case_word) {
  9395. /* "case" did not match anything: still set $? (to 0) */
  9396. G.last_exitcode = rcode = EXIT_SUCCESS;
  9397. }
  9398. }
  9399. #endif
  9400. /* Just pressing <enter> in shell should check for jobs.
  9401. * OTOH, in non-interactive shell this is useless
  9402. * and only leads to extra job checks */
  9403. if (pi->num_cmds == 0) {
  9404. if (G_interactive_fd)
  9405. goto check_jobs_and_continue;
  9406. continue;
  9407. }
  9408. /* After analyzing all keywords and conditions, we decided
  9409. * to execute this pipe. NB: have to do checkjobs(NULL)
  9410. * after run_pipe to collect any background children,
  9411. * even if list execution is to be stopped. */
  9412. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9413. #if ENABLE_HUSH_LOOPS
  9414. G.flag_break_continue = 0;
  9415. #endif
  9416. rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
  9417. /* NB: rcode is a smalluint, r is int */
  9418. if (r != -1) {
  9419. /* We ran a builtin, function, or group.
  9420. * rcode is already known
  9421. * and we don't need to wait for anything. */
  9422. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9423. G.last_exitcode = rcode;
  9424. check_and_run_traps();
  9425. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9426. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9427. #endif
  9428. #if ENABLE_HUSH_LOOPS
  9429. /* Was it "break" or "continue"? */
  9430. if (G.flag_break_continue) {
  9431. smallint fbc = G.flag_break_continue;
  9432. /* We might fall into outer *loop*,
  9433. * don't want to break it too */
  9434. if (loop_top) {
  9435. G.depth_break_continue--;
  9436. if (G.depth_break_continue == 0)
  9437. G.flag_break_continue = 0;
  9438. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9439. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9440. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9441. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9442. break;
  9443. }
  9444. /* "continue": simulate end of loop */
  9445. rword = RES_DONE;
  9446. continue;
  9447. }
  9448. #endif
  9449. if (G_flag_return_in_progress == 1) {
  9450. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9451. break;
  9452. }
  9453. } else if (pi->followup == PIPE_BG) {
  9454. /* What does bash do with attempts to background builtins? */
  9455. /* even bash 3.2 doesn't do that well with nested bg:
  9456. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9457. * I'm NOT treating inner &'s as jobs */
  9458. #if ENABLE_HUSH_JOB
  9459. if (G.run_list_level == 1)
  9460. insert_job_into_table(pi);
  9461. #endif
  9462. /* Last command's pid goes to $! */
  9463. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9464. G.last_bg_pid_exitcode = 0;
  9465. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9466. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9467. rcode = EXIT_SUCCESS;
  9468. goto check_traps;
  9469. } else {
  9470. #if ENABLE_HUSH_JOB
  9471. if (G.run_list_level == 1 && G_interactive_fd) {
  9472. /* Waits for completion, then fg's main shell */
  9473. rcode = checkjobs_and_fg_shell(pi);
  9474. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9475. goto check_traps;
  9476. }
  9477. #endif
  9478. /* This one just waits for completion */
  9479. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9480. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9481. check_traps:
  9482. G.last_exitcode = rcode;
  9483. check_and_run_traps();
  9484. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9485. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9486. #endif
  9487. }
  9488. /* Handle "set -e" */
  9489. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9490. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9491. if (G.errexit_depth == 0)
  9492. hush_exit(rcode);
  9493. }
  9494. G.errexit_depth = sv_errexit_depth;
  9495. /* Analyze how result affects subsequent commands */
  9496. #if ENABLE_HUSH_IF
  9497. if (rword == RES_IF || rword == RES_ELIF) {
  9498. debug_printf_exec("cond_code=rcode:%d\n", rcode);
  9499. cond_code = rcode;
  9500. }
  9501. #endif
  9502. check_jobs_and_continue:
  9503. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9504. dont_check_jobs_but_continue: ;
  9505. #if ENABLE_HUSH_LOOPS
  9506. /* Beware of "while false; true; do ..."! */
  9507. if (pi->next
  9508. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9509. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9510. ) {
  9511. if (rword == RES_WHILE) {
  9512. if (rcode) {
  9513. /* "while false; do...done" - exitcode 0 */
  9514. G.last_exitcode = rcode = EXIT_SUCCESS;
  9515. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9516. break;
  9517. }
  9518. }
  9519. if (rword == RES_UNTIL) {
  9520. if (!rcode) {
  9521. debug_printf_exec(": until expr is true: breaking\n");
  9522. break;
  9523. }
  9524. }
  9525. }
  9526. #endif
  9527. } /* for (pi) */
  9528. #if ENABLE_HUSH_JOB
  9529. G.run_list_level--;
  9530. #endif
  9531. #if ENABLE_HUSH_LOOPS
  9532. if (loop_top)
  9533. G.depth_of_loop--;
  9534. free(for_list);
  9535. #endif
  9536. #if ENABLE_HUSH_CASE
  9537. free(case_word);
  9538. #endif
  9539. debug_leave();
  9540. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level, rcode);
  9541. return rcode;
  9542. }
  9543. /* Select which version we will use */
  9544. static int run_and_free_list(struct pipe *pi)
  9545. {
  9546. int rcode = 0;
  9547. debug_printf_exec("run_and_free_list entered\n");
  9548. if (!G.o_opt[OPT_O_NOEXEC]) {
  9549. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9550. rcode = run_list(pi);
  9551. }
  9552. /* free_pipe_list has the side effect of clearing memory.
  9553. * In the long run that function can be merged with run_list,
  9554. * but doing that now would hobble the debugging effort. */
  9555. free_pipe_list(pi);
  9556. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9557. return rcode;
  9558. }
  9559. /*
  9560. * Initialization and main
  9561. */
  9562. static void install_sighandlers(unsigned mask)
  9563. {
  9564. sighandler_t old_handler;
  9565. unsigned sig = 0;
  9566. while ((mask >>= 1) != 0) {
  9567. sig++;
  9568. if (!(mask & 1))
  9569. continue;
  9570. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9571. /* POSIX allows shell to re-enable SIGCHLD
  9572. * even if it was SIG_IGN on entry.
  9573. * Therefore we skip IGN check for it:
  9574. */
  9575. if (sig == SIGCHLD)
  9576. continue;
  9577. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9578. * Try:
  9579. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9580. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9581. */
  9582. if (sig == SIGHUP && G_interactive_fd)
  9583. continue;
  9584. /* Unless one of the above signals, is it SIG_IGN? */
  9585. if (old_handler == SIG_IGN) {
  9586. /* oops... restore back to IGN, and record this fact */
  9587. install_sighandler(sig, old_handler);
  9588. #if ENABLE_HUSH_TRAP
  9589. if (!G_traps)
  9590. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9591. free(G_traps[sig]);
  9592. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9593. #endif
  9594. }
  9595. }
  9596. }
  9597. /* Called a few times only (or even once if "sh -c") */
  9598. static void install_special_sighandlers(void)
  9599. {
  9600. unsigned mask;
  9601. /* Which signals are shell-special? */
  9602. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9603. if (G_interactive_fd) {
  9604. mask |= SPECIAL_INTERACTIVE_SIGS;
  9605. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9606. mask |= SPECIAL_JOBSTOP_SIGS;
  9607. }
  9608. /* Careful, do not re-install handlers we already installed */
  9609. if (G.special_sig_mask != mask) {
  9610. unsigned diff = mask & ~G.special_sig_mask;
  9611. G.special_sig_mask = mask;
  9612. install_sighandlers(diff);
  9613. }
  9614. }
  9615. #if ENABLE_HUSH_JOB
  9616. /* helper */
  9617. /* Set handlers to restore tty pgrp and exit */
  9618. static void install_fatal_sighandlers(void)
  9619. {
  9620. unsigned mask;
  9621. /* We will restore tty pgrp on these signals */
  9622. mask = 0
  9623. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9624. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9625. + (1 << SIGBUS ) * HUSH_DEBUG
  9626. + (1 << SIGSEGV) * HUSH_DEBUG
  9627. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9628. + (1 << SIGABRT)
  9629. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9630. + (1 << SIGPIPE)
  9631. + (1 << SIGALRM)
  9632. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9633. * if we aren't interactive... but in this case
  9634. * we never want to restore pgrp on exit, and this fn is not called
  9635. */
  9636. /*+ (1 << SIGHUP )*/
  9637. /*+ (1 << SIGTERM)*/
  9638. /*+ (1 << SIGINT )*/
  9639. ;
  9640. G_fatal_sig_mask = mask;
  9641. install_sighandlers(mask);
  9642. }
  9643. #endif
  9644. static int set_mode(int state, char mode, const char *o_opt)
  9645. {
  9646. int idx;
  9647. switch (mode) {
  9648. case 'n':
  9649. /* set -n has no effect in interactive shell */
  9650. /* Try: while set -n; do echo $-; done */
  9651. if (!G_interactive_fd)
  9652. G.o_opt[OPT_O_NOEXEC] = state;
  9653. break;
  9654. case 'x':
  9655. IF_HUSH_MODE_X(G_x_mode = state;)
  9656. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9657. break;
  9658. case 'e':
  9659. G.o_opt[OPT_O_ERREXIT] = state;
  9660. break;
  9661. case 'o':
  9662. if (!o_opt) {
  9663. /* "set -o" or "set +o" without parameter.
  9664. * in bash, set -o produces this output:
  9665. * pipefail off
  9666. * and set +o:
  9667. * set +o pipefail
  9668. * We always use the second form.
  9669. */
  9670. const char *p = o_opt_strings;
  9671. idx = 0;
  9672. while (*p) {
  9673. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9674. idx++;
  9675. p += strlen(p) + 1;
  9676. }
  9677. break;
  9678. }
  9679. idx = index_in_strings(o_opt_strings, o_opt);
  9680. if (idx >= 0) {
  9681. G.o_opt[idx] = state;
  9682. break;
  9683. }
  9684. /* fall through to error */
  9685. default:
  9686. return EXIT_FAILURE;
  9687. }
  9688. return EXIT_SUCCESS;
  9689. }
  9690. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9691. int hush_main(int argc, char **argv)
  9692. {
  9693. pid_t cached_getpid;
  9694. enum {
  9695. OPT_login = (1 << 0),
  9696. };
  9697. unsigned flags;
  9698. #if !BB_MMU
  9699. unsigned builtin_argc = 0;
  9700. #endif
  9701. char **e;
  9702. struct variable *cur_var;
  9703. struct variable *shell_ver;
  9704. INIT_G();
  9705. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9706. G.last_exitcode = EXIT_SUCCESS;
  9707. #if !BB_MMU
  9708. /* "Big heredoc" support via "sh -< STRING" invocation.
  9709. * Check it first (do not bother to run the usual init code,
  9710. * it is not needed for this case).
  9711. */
  9712. if (argv[1]
  9713. && argv[1][0] == '-' && argv[1][1] == '<' /*&& !argv[1][2]*/
  9714. /*&& argv[2] && !argv[3] - we don't check some conditions */
  9715. ) {
  9716. full_write1_str(argv[2]);
  9717. _exit(0);
  9718. }
  9719. G.argv0_for_re_execing = argv[0];
  9720. if (G.argv0_for_re_execing[0] == '-')
  9721. /* reexeced hush should never be a login shell */
  9722. G.argv0_for_re_execing++;
  9723. #endif
  9724. #if ENABLE_HUSH_TRAP
  9725. # if ENABLE_HUSH_FUNCTIONS
  9726. G.return_exitcode = -1;
  9727. # endif
  9728. G.pre_trap_exitcode = -1;
  9729. #endif
  9730. #if ENABLE_HUSH_FAST
  9731. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9732. #endif
  9733. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9734. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9735. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9736. /* Deal with HUSH_VERSION */
  9737. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9738. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9739. shell_ver = xzalloc(sizeof(*shell_ver));
  9740. shell_ver->flg_export = 1;
  9741. shell_ver->flg_read_only = 1;
  9742. /* Code which handles ${var<op>...} needs writable values for all variables,
  9743. * therefore we xstrdup: */
  9744. shell_ver->varstr = xstrdup(hush_version_str);
  9745. /* Create shell local variables from the values
  9746. * currently living in the environment */
  9747. G.top_var = shell_ver;
  9748. cur_var = G.top_var;
  9749. e = environ;
  9750. if (e) while (*e) {
  9751. char *value = strchr(*e, '=');
  9752. if (value) { /* paranoia */
  9753. cur_var->next = xzalloc(sizeof(*cur_var));
  9754. cur_var = cur_var->next;
  9755. cur_var->varstr = *e;
  9756. cur_var->max_len = strlen(*e);
  9757. cur_var->flg_export = 1;
  9758. }
  9759. e++;
  9760. }
  9761. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9762. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9763. putenv(shell_ver->varstr);
  9764. /* Export PWD */
  9765. set_pwd_var(SETFLAG_EXPORT);
  9766. #if BASH_HOSTNAME_VAR
  9767. /* Set (but not export) HOSTNAME unless already set */
  9768. if (!get_local_var_value("HOSTNAME")) {
  9769. struct utsname uts;
  9770. uname(&uts);
  9771. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9772. }
  9773. #endif
  9774. /* IFS is not inherited from the parent environment */
  9775. set_local_var_from_halves("IFS", defifs);
  9776. if (!get_local_var_value("PATH"))
  9777. set_local_var_from_halves("PATH", bb_default_root_path);
  9778. /* PS1/PS2 are set later, if we determine that we are interactive */
  9779. /* bash also exports SHLVL and _,
  9780. * and sets (but doesn't export) the following variables:
  9781. * BASH=/bin/bash
  9782. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9783. * BASH_VERSION='3.2.0(1)-release'
  9784. * HOSTTYPE=i386
  9785. * MACHTYPE=i386-pc-linux-gnu
  9786. * OSTYPE=linux-gnu
  9787. * PPID=<NNNNN> - we also do it elsewhere
  9788. * EUID=<NNNNN>
  9789. * UID=<NNNNN>
  9790. * GROUPS=()
  9791. * LINES=<NNN>
  9792. * COLUMNS=<NNN>
  9793. * BASH_ARGC=()
  9794. * BASH_ARGV=()
  9795. * BASH_LINENO=()
  9796. * BASH_SOURCE=()
  9797. * DIRSTACK=()
  9798. * PIPESTATUS=([0]="0")
  9799. * HISTFILE=/<xxx>/.bash_history
  9800. * HISTFILESIZE=500
  9801. * HISTSIZE=500
  9802. * MAILCHECK=60
  9803. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9804. * SHELL=/bin/bash
  9805. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9806. * TERM=dumb
  9807. * OPTERR=1
  9808. * OPTIND=1
  9809. * PS4='+ '
  9810. */
  9811. #if NUM_SCRIPTS > 0
  9812. if (argc < 0) {
  9813. char *script = get_script_content(-argc - 1);
  9814. G.global_argv = argv;
  9815. G.global_argc = string_array_len(argv);
  9816. //install_special_sighandlers(); - needed?
  9817. parse_and_run_string(script);
  9818. goto final_return;
  9819. }
  9820. #endif
  9821. /* Initialize some more globals to non-zero values */
  9822. die_func = restore_ttypgrp_and__exit;
  9823. /* Shell is non-interactive at first. We need to call
  9824. * install_special_sighandlers() if we are going to execute "sh <script>",
  9825. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9826. * If we later decide that we are interactive, we run install_special_sighandlers()
  9827. * in order to intercept (more) signals.
  9828. */
  9829. /* Parse options */
  9830. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9831. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9832. while (1) {
  9833. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9834. "cexinsl"
  9835. #if !BB_MMU
  9836. "$:R:V:"
  9837. # if ENABLE_HUSH_LINENO_VAR
  9838. "L:"
  9839. # endif
  9840. # if ENABLE_HUSH_FUNCTIONS
  9841. "F:"
  9842. # endif
  9843. #endif
  9844. );
  9845. if (opt <= 0)
  9846. break;
  9847. switch (opt) {
  9848. case 'c':
  9849. /* Note: -c is not an option with param!
  9850. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9851. */
  9852. G.opt_c = 1;
  9853. break;
  9854. case 'i':
  9855. /* Well, we cannot just declare interactiveness,
  9856. * we have to have some stuff (ctty, etc) */
  9857. /* G_interactive_fd++; */
  9858. //There are a few cases where bash -i -c 'SCRIPT'
  9859. //has visible effect (differs from bash -c 'SCRIPT'):
  9860. //it ignores TERM:
  9861. // bash -i -c 'kill $$; echo ALIVE'
  9862. // ALIVE
  9863. //it resets SIG_IGNed HUP to SIG_DFL:
  9864. // trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
  9865. // Hangup [the message is not printed by bash, it's the shell which started it]
  9866. //is talkative about jobs and exiting:
  9867. // bash -i -c 'sleep 1 & exit'
  9868. // [1] 16170
  9869. // exit
  9870. //includes $ENV file (only if run as "sh"):
  9871. // echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
  9872. // last: cannot open /var/log/wtmp: No such file or directory
  9873. // HERE
  9874. //(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
  9875. //
  9876. //ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
  9877. //(this may be a bug, bash does not do this).
  9878. //(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
  9879. //
  9880. //None of the above feel like useful features people would rely on.
  9881. break;
  9882. case 's':
  9883. G.opt_s = 1;
  9884. break;
  9885. case 'l':
  9886. flags |= OPT_login;
  9887. break;
  9888. #if !BB_MMU
  9889. case '$': {
  9890. unsigned long long empty_trap_mask;
  9891. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9892. optarg++;
  9893. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9894. optarg++;
  9895. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9896. optarg++;
  9897. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9898. optarg++;
  9899. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9900. optarg++;
  9901. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9902. if (empty_trap_mask != 0) {
  9903. IF_HUSH_TRAP(int sig;)
  9904. install_special_sighandlers();
  9905. # if ENABLE_HUSH_TRAP
  9906. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9907. for (sig = 1; sig < NSIG; sig++) {
  9908. if (empty_trap_mask & (1LL << sig)) {
  9909. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9910. install_sighandler(sig, SIG_IGN);
  9911. }
  9912. }
  9913. # endif
  9914. }
  9915. # if ENABLE_HUSH_LOOPS
  9916. optarg++;
  9917. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9918. # endif
  9919. /* Suppress "killed by signal" message, -$ hack is used
  9920. * for subshells: echo `sh -c 'kill -9 $$'`
  9921. * should be silent.
  9922. */
  9923. IF_HUSH_JOB(G.run_list_level = 1;)
  9924. # if ENABLE_HUSH_FUNCTIONS
  9925. /* nommu uses re-exec trick for "... | func | ...",
  9926. * should allow "return".
  9927. * This accidentally allows returns in subshells.
  9928. */
  9929. G_flag_return_in_progress = -1;
  9930. # endif
  9931. break;
  9932. }
  9933. case 'R':
  9934. case 'V':
  9935. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9936. break;
  9937. # if ENABLE_HUSH_LINENO_VAR
  9938. case 'L':
  9939. G.parse_lineno = xatou(optarg);
  9940. break;
  9941. # endif
  9942. # if ENABLE_HUSH_FUNCTIONS
  9943. case 'F': {
  9944. struct function *funcp = new_function(optarg);
  9945. /* funcp->name is already set to optarg */
  9946. /* funcp->body is set to NULL. It's a special case. */
  9947. funcp->body_as_string = argv[optind];
  9948. optind++;
  9949. break;
  9950. }
  9951. # endif
  9952. #endif
  9953. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9954. /*case 'n':*/
  9955. /*case 'x':*/
  9956. /*case 'e':*/
  9957. default:
  9958. if (set_mode(1, opt, NULL) == 0) /* no error */
  9959. break;
  9960. bb_show_usage();
  9961. }
  9962. } /* option parsing loop */
  9963. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9964. G.global_argc = argc - (optind - 1);
  9965. G.global_argv = argv + (optind - 1);
  9966. G.global_argv[0] = argv[0];
  9967. /* If we are login shell... */
  9968. if (flags & OPT_login) {
  9969. const char *hp = NULL;
  9970. HFILE *input;
  9971. debug_printf("sourcing /etc/profile\n");
  9972. input = hfopen("/etc/profile");
  9973. run_profile:
  9974. if (input != NULL) {
  9975. install_special_sighandlers();
  9976. parse_and_run_file(input);
  9977. hfclose(input);
  9978. }
  9979. /* bash: after sourcing /etc/profile,
  9980. * tries to source (in the given order):
  9981. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9982. * stopping on first found. --noprofile turns this off.
  9983. * bash also sources ~/.bash_logout on exit.
  9984. * If called as sh, skips .bash_XXX files.
  9985. */
  9986. if (!hp) { /* unless we looped on the "goto" already */
  9987. hp = get_local_var_value("HOME");
  9988. if (hp && hp[0]) {
  9989. debug_printf("sourcing ~/.profile\n");
  9990. hp = concat_path_file(hp, ".profile");
  9991. input = hfopen(hp);
  9992. free((char*)hp);
  9993. goto run_profile;
  9994. }
  9995. }
  9996. }
  9997. /* -c takes effect *after* -l */
  9998. if (G.opt_c) {
  9999. /* Possibilities:
  10000. * sh ... -c 'script'
  10001. * sh ... -c 'script' ARG0 [ARG1...]
  10002. * On NOMMU, if builtin_argc != 0,
  10003. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  10004. * "" needs to be replaced with NULL
  10005. * and BARGV vector fed to builtin function.
  10006. * Note: the form without ARG0 never happens:
  10007. * sh ... -c 'builtin' BARGV... ""
  10008. */
  10009. char *script;
  10010. install_special_sighandlers();
  10011. G.global_argc--;
  10012. G.global_argv++;
  10013. #if !BB_MMU
  10014. if (builtin_argc) {
  10015. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  10016. const struct built_in_command *x;
  10017. x = find_builtin(G.global_argv[0]);
  10018. if (x) { /* paranoia */
  10019. argv = G.global_argv;
  10020. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  10021. G.global_argv += builtin_argc + 1;
  10022. G.global_argv[-1] = NULL; /* replace "" */
  10023. G.last_exitcode = x->b_function(argv);
  10024. }
  10025. goto final_return;
  10026. }
  10027. #endif
  10028. script = G.global_argv[0];
  10029. if (!script)
  10030. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  10031. if (!G.global_argv[1]) {
  10032. /* -c 'script' (no params): prevent empty $0 */
  10033. G.global_argv[0] = argv[0];
  10034. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  10035. G.global_argc--;
  10036. G.global_argv++;
  10037. }
  10038. parse_and_run_string(script);
  10039. goto final_return;
  10040. }
  10041. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  10042. if (!G.opt_s && G.global_argv[1]) {
  10043. HFILE *input;
  10044. /*
  10045. * "bash <script>" (which is never interactive (unless -i?))
  10046. * sources $BASH_ENV here (without scanning $PATH).
  10047. * If called as sh, does the same but with $ENV.
  10048. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  10049. */
  10050. G.global_argc--;
  10051. G.global_argv++;
  10052. debug_printf("running script '%s'\n", G.global_argv[0]);
  10053. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  10054. input = hfopen(G.global_argv[0]);
  10055. if (!input) {
  10056. bb_simple_perror_msg_and_die(G.global_argv[0]);
  10057. }
  10058. xfunc_error_retval = 1;
  10059. install_special_sighandlers();
  10060. parse_and_run_file(input);
  10061. #if ENABLE_FEATURE_CLEAN_UP
  10062. hfclose(input);
  10063. #endif
  10064. goto final_return;
  10065. }
  10066. /* "implicit" -s: bare interactive hush shows 's' in $- */
  10067. G.opt_s = 1;
  10068. /* Up to here, shell was non-interactive. Now it may become one.
  10069. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  10070. */
  10071. /* A shell is interactive if the '-i' flag was given,
  10072. * or if all of the following conditions are met:
  10073. * no -c command
  10074. * no arguments remaining or the -s flag given
  10075. * standard input is a terminal
  10076. * standard output is a terminal
  10077. * Refer to Posix.2, the description of the 'sh' utility.
  10078. */
  10079. #if ENABLE_HUSH_JOB
  10080. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10081. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  10082. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  10083. if (G_saved_tty_pgrp < 0)
  10084. G_saved_tty_pgrp = 0;
  10085. /* try to dup stdin to high fd#, >= 255 */
  10086. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10087. if (G_interactive_fd < 0) {
  10088. /* try to dup to any fd */
  10089. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  10090. if (G_interactive_fd < 0) {
  10091. /* give up */
  10092. G_interactive_fd = 0;
  10093. G_saved_tty_pgrp = 0;
  10094. }
  10095. }
  10096. }
  10097. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  10098. if (G_interactive_fd) {
  10099. if (G_saved_tty_pgrp) {
  10100. /* If we were run as 'hush &', sleep until we are
  10101. * in the foreground (tty pgrp == our pgrp).
  10102. * If we get started under a job aware app (like bash),
  10103. * make sure we are now in charge so we don't fight over
  10104. * who gets the foreground */
  10105. while (1) {
  10106. pid_t shell_pgrp = getpgrp();
  10107. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  10108. if (G_saved_tty_pgrp == shell_pgrp)
  10109. break;
  10110. /* send TTIN to ourself (should stop us) */
  10111. kill(- shell_pgrp, SIGTTIN);
  10112. }
  10113. }
  10114. /* Install more signal handlers */
  10115. install_special_sighandlers();
  10116. if (G_saved_tty_pgrp) {
  10117. /* Set other signals to restore saved_tty_pgrp */
  10118. install_fatal_sighandlers();
  10119. /* Put ourselves in our own process group
  10120. * (bash, too, does this only if ctty is available) */
  10121. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  10122. /* Grab control of the terminal */
  10123. tcsetpgrp(G_interactive_fd, cached_getpid);
  10124. }
  10125. enable_restore_tty_pgrp_on_exit();
  10126. # if ENABLE_FEATURE_EDITING
  10127. G.line_input_state = new_line_input_t(FOR_SHELL);
  10128. # if ENABLE_FEATURE_TAB_COMPLETION
  10129. G.line_input_state->get_exe_name = hush_command_name;
  10130. # endif
  10131. # if EDITING_HAS_sh_get_var
  10132. G.line_input_state->sh_get_var = get_local_var_value;
  10133. # endif
  10134. # endif
  10135. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  10136. {
  10137. const char *hp = get_local_var_value("HISTFILE");
  10138. if (!hp) {
  10139. hp = get_local_var_value("HOME");
  10140. if (hp)
  10141. hp = concat_path_file(hp, ".hush_history");
  10142. } else {
  10143. hp = xstrdup(hp);
  10144. }
  10145. if (hp) {
  10146. G.line_input_state->hist_file = hp;
  10147. //set_local_var(xasprintf("HISTFILE=%s", ...));
  10148. }
  10149. # if ENABLE_FEATURE_SH_HISTFILESIZE
  10150. hp = get_local_var_value("HISTFILESIZE");
  10151. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  10152. # endif
  10153. }
  10154. # endif
  10155. } else {
  10156. install_special_sighandlers();
  10157. }
  10158. #elif ENABLE_HUSH_INTERACTIVE
  10159. /* No job control compiled in, only prompt/line editing */
  10160. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10161. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10162. if (G_interactive_fd < 0) {
  10163. /* try to dup to any fd */
  10164. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  10165. if (G_interactive_fd < 0)
  10166. /* give up */
  10167. G_interactive_fd = 0;
  10168. }
  10169. }
  10170. install_special_sighandlers();
  10171. #else
  10172. /* We have interactiveness code disabled */
  10173. install_special_sighandlers();
  10174. #endif
  10175. /* bash:
  10176. * if interactive but not a login shell, sources ~/.bashrc
  10177. * (--norc turns this off, --rcfile <file> overrides)
  10178. */
  10179. if (G_interactive_fd) {
  10180. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  10181. /* Set (but not export) PS1/2 unless already set */
  10182. if (!get_local_var_value("PS1"))
  10183. set_local_var_from_halves("PS1", "\\w \\$ ");
  10184. if (!get_local_var_value("PS2"))
  10185. set_local_var_from_halves("PS2", "> ");
  10186. #endif
  10187. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  10188. /* note: ash and hush share this string */
  10189. printf("\n\n%s %s\n"
  10190. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  10191. "\n",
  10192. bb_banner,
  10193. "hush - the humble shell"
  10194. );
  10195. }
  10196. }
  10197. parse_and_run_file(hfopen(NULL)); /* stdin */
  10198. final_return:
  10199. hush_exit(G.last_exitcode);
  10200. }
  10201. /*
  10202. * Built-ins
  10203. */
  10204. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  10205. {
  10206. return 0;
  10207. }
  10208. static int FAST_FUNC builtin_false(char **argv UNUSED_PARAM)
  10209. {
  10210. return 1;
  10211. }
  10212. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  10213. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  10214. {
  10215. int argc = string_array_len(argv);
  10216. return applet_main_func(argc, argv);
  10217. }
  10218. #endif
  10219. #if ENABLE_HUSH_TEST || BASH_TEST2
  10220. static int FAST_FUNC builtin_test(char **argv)
  10221. {
  10222. int argc = string_array_len(argv);
  10223. return test_main2(&G.groupinfo, argc, argv);
  10224. }
  10225. #endif
  10226. #if ENABLE_HUSH_ECHO
  10227. static int FAST_FUNC builtin_echo(char **argv)
  10228. {
  10229. return run_applet_main(argv, echo_main);
  10230. }
  10231. #endif
  10232. #if ENABLE_HUSH_PRINTF
  10233. static int FAST_FUNC builtin_printf(char **argv)
  10234. {
  10235. return run_applet_main(argv, printf_main);
  10236. }
  10237. #endif
  10238. #if ENABLE_HUSH_HELP
  10239. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10240. {
  10241. const struct built_in_command *x;
  10242. printf(
  10243. "Built-in commands:\n"
  10244. "------------------\n");
  10245. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10246. if (x->b_descr)
  10247. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10248. }
  10249. return EXIT_SUCCESS;
  10250. }
  10251. #endif
  10252. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10253. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10254. {
  10255. show_history(G.line_input_state);
  10256. return EXIT_SUCCESS;
  10257. }
  10258. #endif
  10259. static int FAST_FUNC builtin_cd(char **argv)
  10260. {
  10261. const char *newdir;
  10262. argv = skip_dash_dash(argv);
  10263. newdir = argv[0];
  10264. if (newdir == NULL) {
  10265. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10266. * bash says "bash: cd: HOME not set" and does nothing
  10267. * (exitcode 1)
  10268. */
  10269. const char *home = get_local_var_value("HOME");
  10270. newdir = home ? home : "/";
  10271. }
  10272. if (chdir(newdir)) {
  10273. /* Mimic bash message exactly */
  10274. bb_perror_msg("cd: %s", newdir);
  10275. return EXIT_FAILURE;
  10276. }
  10277. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10278. * Note: do not enforce exporting. If PWD was unset or unexported,
  10279. * set it again, but do not export. bash does the same.
  10280. */
  10281. set_pwd_var(/*flag:*/ 0);
  10282. return EXIT_SUCCESS;
  10283. }
  10284. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10285. {
  10286. puts(get_cwd(0));
  10287. return EXIT_SUCCESS;
  10288. }
  10289. static int FAST_FUNC builtin_eval(char **argv)
  10290. {
  10291. argv = skip_dash_dash(argv);
  10292. if (!argv[0])
  10293. return EXIT_SUCCESS;
  10294. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10295. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10296. if (!argv[1]) {
  10297. /* bash:
  10298. * eval "echo Hi; done" ("done" is syntax error):
  10299. * "echo Hi" will not execute too.
  10300. */
  10301. parse_and_run_string(argv[0]);
  10302. } else {
  10303. /* "The eval utility shall construct a command by
  10304. * concatenating arguments together, separating
  10305. * each with a <space> character."
  10306. */
  10307. char *str, *p;
  10308. unsigned len = 0;
  10309. char **pp = argv;
  10310. do
  10311. len += strlen(*pp) + 1;
  10312. while (*++pp);
  10313. str = p = xmalloc(len);
  10314. pp = argv;
  10315. for (;;) {
  10316. p = stpcpy(p, *pp);
  10317. pp++;
  10318. if (!*pp)
  10319. break;
  10320. *p++ = ' ';
  10321. }
  10322. parse_and_run_string(str);
  10323. free(str);
  10324. }
  10325. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10326. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10327. return G.last_exitcode;
  10328. }
  10329. static int FAST_FUNC builtin_exec(char **argv)
  10330. {
  10331. argv = skip_dash_dash(argv);
  10332. if (argv[0] == NULL)
  10333. return EXIT_SUCCESS; /* bash does this */
  10334. /* Careful: we can end up here after [v]fork. Do not restore
  10335. * tty pgrp then, only top-level shell process does that */
  10336. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10337. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10338. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10339. * open here. However, they are all CLOEXEC, and execv below
  10340. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10341. * it should show no extra open fds in the "ls" process.
  10342. * If we'd try to run builtins/NOEXECs, this would need improving.
  10343. */
  10344. //close_saved_fds_and_FILE_fds();
  10345. /* TODO: if exec fails, bash does NOT exit! We do.
  10346. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10347. * and tcsetpgrp, and this is inherently racy.
  10348. */
  10349. execvp_or_die(argv);
  10350. }
  10351. static int FAST_FUNC builtin_exit(char **argv)
  10352. {
  10353. debug_printf_exec("%s()\n", __func__);
  10354. /* interactive bash:
  10355. * # trap "echo EEE" EXIT
  10356. * # exit
  10357. * exit
  10358. * There are stopped jobs.
  10359. * (if there are _stopped_ jobs, running ones don't count)
  10360. * # exit
  10361. * exit
  10362. * EEE (then bash exits)
  10363. *
  10364. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10365. */
  10366. /* note: EXIT trap is run by hush_exit */
  10367. argv = skip_dash_dash(argv);
  10368. if (argv[0] == NULL) {
  10369. #if ENABLE_HUSH_TRAP
  10370. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10371. hush_exit(G.pre_trap_exitcode);
  10372. #endif
  10373. hush_exit(G.last_exitcode);
  10374. }
  10375. /* mimic bash: exit 123abc == exit 255 + error msg */
  10376. xfunc_error_retval = 255;
  10377. /* bash: exit -2 == exit 254, no error msg */
  10378. hush_exit(xatoi(argv[0]) & 0xff);
  10379. }
  10380. #if ENABLE_HUSH_TYPE
  10381. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10382. static int FAST_FUNC builtin_type(char **argv)
  10383. {
  10384. int ret = EXIT_SUCCESS;
  10385. while (*++argv) {
  10386. const char *type;
  10387. char *path = NULL;
  10388. if (0) {} /* make conditional compile easier below */
  10389. /*else if (find_alias(*argv))
  10390. type = "an alias";*/
  10391. # if ENABLE_HUSH_FUNCTIONS
  10392. else if (find_function(*argv))
  10393. type = "a function";
  10394. # endif
  10395. else if (find_builtin(*argv))
  10396. type = "a shell builtin";
  10397. else {
  10398. path = find_executable_in_PATH(*argv);
  10399. if (path)
  10400. type = path;
  10401. else {
  10402. bb_error_msg("%s: %s: not found", "type", *argv);
  10403. ret = EXIT_FAILURE;
  10404. continue;
  10405. }
  10406. }
  10407. printf("%s is %s\n", *argv, type);
  10408. free(path);
  10409. }
  10410. return ret;
  10411. }
  10412. #endif
  10413. #if ENABLE_HUSH_READ
  10414. /* Interruptibility of read builtin in bash
  10415. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10416. *
  10417. * Empty trap makes read ignore corresponding signal, for any signal.
  10418. *
  10419. * SIGINT:
  10420. * - terminates non-interactive shell;
  10421. * - interrupts read in interactive shell;
  10422. * if it has non-empty trap:
  10423. * - executes trap and returns to command prompt in interactive shell;
  10424. * - executes trap and returns to read in non-interactive shell;
  10425. * SIGTERM:
  10426. * - is ignored (does not interrupt) read in interactive shell;
  10427. * - terminates non-interactive shell;
  10428. * if it has non-empty trap:
  10429. * - executes trap and returns to read;
  10430. * SIGHUP:
  10431. * - terminates shell (regardless of interactivity);
  10432. * if it has non-empty trap:
  10433. * - executes trap and returns to read;
  10434. * SIGCHLD from children:
  10435. * - does not interrupt read regardless of interactivity:
  10436. * try: sleep 1 & read x; echo $x
  10437. */
  10438. static int FAST_FUNC builtin_read(char **argv)
  10439. {
  10440. const char *r;
  10441. struct builtin_read_params params;
  10442. memset(&params, 0, sizeof(params));
  10443. /* "!": do not abort on errors.
  10444. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10445. */
  10446. params.read_flags = getopt32(argv,
  10447. # if BASH_READ_D
  10448. IF_NOT_HUSH_BASH_COMPAT("^")
  10449. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10450. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10451. # else
  10452. IF_NOT_HUSH_BASH_COMPAT("^")
  10453. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10454. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10455. # endif
  10456. //TODO: print "read: need variable name"
  10457. //for the case of !BASH "read" with no args (now it fails silently)
  10458. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10459. );
  10460. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10461. return EXIT_FAILURE;
  10462. argv += optind;
  10463. params.argv = argv;
  10464. params.setvar = set_local_var_from_halves;
  10465. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10466. again:
  10467. r = shell_builtin_read(&params);
  10468. if ((uintptr_t)r == 1 && errno == EINTR) {
  10469. unsigned sig = check_and_run_traps();
  10470. if (sig != SIGINT)
  10471. goto again;
  10472. }
  10473. if ((uintptr_t)r > 1) {
  10474. bb_simple_error_msg(r);
  10475. r = (char*)(uintptr_t)1;
  10476. }
  10477. return (uintptr_t)r;
  10478. }
  10479. #endif
  10480. #if ENABLE_HUSH_UMASK
  10481. static int FAST_FUNC builtin_umask(char **argv)
  10482. {
  10483. int rc;
  10484. mode_t mask;
  10485. rc = 1;
  10486. mask = umask(0);
  10487. argv = skip_dash_dash(argv);
  10488. if (argv[0]) {
  10489. mode_t old_mask = mask;
  10490. /* numeric umasks are taken as-is */
  10491. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10492. if (!isdigit(argv[0][0]))
  10493. mask ^= 0777;
  10494. mask = bb_parse_mode(argv[0], mask);
  10495. if (!isdigit(argv[0][0]))
  10496. mask ^= 0777;
  10497. if ((unsigned)mask > 0777) {
  10498. mask = old_mask;
  10499. /* bash messages:
  10500. * bash: umask: 'q': invalid symbolic mode operator
  10501. * bash: umask: 999: octal number out of range
  10502. */
  10503. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10504. rc = 0;
  10505. }
  10506. } else {
  10507. /* Mimic bash */
  10508. printf("%04o\n", (unsigned) mask);
  10509. /* fall through and restore mask which we set to 0 */
  10510. }
  10511. umask(mask);
  10512. return !rc; /* rc != 0 - success */
  10513. }
  10514. #endif
  10515. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY || ENABLE_HUSH_SET || ENABLE_HUSH_TRAP
  10516. static void print_escaped(const char *s)
  10517. {
  10518. //TODO? bash "set" does not quote variables which contain only alnums and "%+,-./:=@_~",
  10519. // (but "export" quotes all variables, even with only these chars).
  10520. // I think quoting strings with %+,=~ looks better
  10521. // (example: "set" printing var== instead of var='=' looks strange)
  10522. // IOW: do not quote "-./:@_": / is used in pathnames, : in PATH, -._ often in file names, @ in emails
  10523. if (*s == '\'')
  10524. goto squote;
  10525. do {
  10526. const char *p = strchrnul(s, '\'');
  10527. /* print 'xxxx', possibly just '' */
  10528. printf("'%.*s'", (int)(p - s), s);
  10529. if (*p == '\0')
  10530. break;
  10531. s = p;
  10532. squote:
  10533. /* s points to '; print "'''...'''" */
  10534. putchar('"');
  10535. do putchar('\''); while (*++s == '\'');
  10536. putchar('"');
  10537. } while (*s);
  10538. }
  10539. #endif
  10540. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10541. static int helper_export_local(char **argv, unsigned flags)
  10542. {
  10543. do {
  10544. char *name = *argv;
  10545. const char *name_end = endofname(name);
  10546. if (*name_end == '\0') {
  10547. struct variable *var, **vpp;
  10548. vpp = get_ptr_to_local_var(name);
  10549. var = vpp ? *vpp : NULL;
  10550. if (flags & SETFLAG_UNEXPORT) {
  10551. /* export -n NAME (without =VALUE) */
  10552. if (var) {
  10553. var->flg_export = 0;
  10554. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10555. unsetenv(name);
  10556. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10557. continue;
  10558. }
  10559. if (flags & SETFLAG_EXPORT) {
  10560. /* export NAME (without =VALUE) */
  10561. if (var) {
  10562. var->flg_export = 1;
  10563. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10564. putenv(var->varstr);
  10565. continue;
  10566. }
  10567. }
  10568. if (flags & SETFLAG_MAKE_RO) {
  10569. /* readonly NAME (without =VALUE) */
  10570. if (var) {
  10571. var->flg_read_only = 1;
  10572. continue;
  10573. }
  10574. }
  10575. # if ENABLE_HUSH_LOCAL
  10576. /* Is this "local" bltin? */
  10577. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10578. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10579. if (var && var->var_nest_level == lvl) {
  10580. /* "local x=abc; ...; local x" - ignore second local decl */
  10581. continue;
  10582. }
  10583. }
  10584. # endif
  10585. /* Exporting non-existing variable.
  10586. * bash does not put it in environment,
  10587. * but remembers that it is exported,
  10588. * and does put it in env when it is set later.
  10589. * We just set it to "" and export.
  10590. */
  10591. /* Or, it's "local NAME" (without =VALUE).
  10592. * bash sets the value to "".
  10593. */
  10594. /* Or, it's "readonly NAME" (without =VALUE).
  10595. * bash remembers NAME and disallows its creation
  10596. * in the future.
  10597. */
  10598. name = xasprintf("%s=", name);
  10599. } else {
  10600. if (*name_end != '=') {
  10601. bb_error_msg("'%s': bad variable name", name);
  10602. /* do not parse following argv[]s: */
  10603. return 1;
  10604. }
  10605. /* (Un)exporting/making local NAME=VALUE */
  10606. name = xstrdup(name);
  10607. /* Testcase: export PS1='\w \$ ' */
  10608. unbackslash(name);
  10609. }
  10610. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10611. if (set_local_var(name, flags))
  10612. return EXIT_FAILURE;
  10613. } while (*++argv);
  10614. return EXIT_SUCCESS;
  10615. }
  10616. #endif
  10617. #if ENABLE_HUSH_EXPORT
  10618. static int FAST_FUNC builtin_export(char **argv)
  10619. {
  10620. unsigned opt_unexport;
  10621. # if ENABLE_HUSH_EXPORT_N
  10622. /* "!": do not abort on errors */
  10623. opt_unexport = getopt32(argv, "!n");
  10624. if (opt_unexport == (uint32_t)-1)
  10625. return EXIT_FAILURE;
  10626. argv += optind;
  10627. # else
  10628. opt_unexport = 0;
  10629. argv++;
  10630. # endif
  10631. if (argv[0] == NULL) {
  10632. char **e = environ;
  10633. if (e) {
  10634. while (*e) {
  10635. # if 0
  10636. puts(*e++);
  10637. # else
  10638. /* ash emits: export VAR='VAL'
  10639. * bash: declare -x VAR="VAL"
  10640. * we follow ash example */
  10641. const char *s = *e++;
  10642. const char *p = strchr(s, '=');
  10643. if (!p) /* wtf? take next variable */
  10644. continue;
  10645. /* "export VAR=" */
  10646. printf("%s %.*s", "export", (int)(p - s) + 1, s);
  10647. print_escaped(p + 1);
  10648. putchar('\n');
  10649. # endif
  10650. }
  10651. /*fflush_all(); - done after each builtin anyway */
  10652. }
  10653. return EXIT_SUCCESS;
  10654. }
  10655. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10656. }
  10657. #endif
  10658. #if ENABLE_HUSH_LOCAL
  10659. static int FAST_FUNC builtin_local(char **argv)
  10660. {
  10661. if (G.func_nest_level == 0) {
  10662. bb_error_msg("%s: not in a function", argv[0]);
  10663. return EXIT_FAILURE; /* bash compat */
  10664. }
  10665. //TODO? ash and bash support "local -" special form,
  10666. //which saves/restores $- around function call (including async returns, such as ^C)
  10667. //(IOW: it makes "set +/-..." effects local)
  10668. argv++;
  10669. /* Since all builtins run in a nested variable level,
  10670. * need to use level - 1 here. Or else the variable will be removed at once
  10671. * after builtin returns.
  10672. */
  10673. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10674. }
  10675. #endif
  10676. #if ENABLE_HUSH_READONLY
  10677. static int FAST_FUNC builtin_readonly(char **argv)
  10678. {
  10679. argv++;
  10680. if (*argv == NULL) {
  10681. /* bash: readonly [-p]: list all readonly VARs
  10682. * (-p has no effect in bash)
  10683. */
  10684. struct variable *e;
  10685. for (e = G.top_var; e; e = e->next) {
  10686. if (e->flg_read_only) {
  10687. const char *s = e->varstr;
  10688. const char *p = strchr(s, '=');
  10689. if (!p) /* wtf? take next variable */
  10690. continue;
  10691. /* "readonly VAR=" */
  10692. printf("%s %.*s", "readonly", (int)(p - s) + 1, s);
  10693. print_escaped(p + 1);
  10694. putchar('\n');
  10695. }
  10696. }
  10697. return EXIT_SUCCESS;
  10698. }
  10699. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10700. }
  10701. #endif
  10702. #if ENABLE_HUSH_UNSET
  10703. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10704. static int FAST_FUNC builtin_unset(char **argv)
  10705. {
  10706. int ret;
  10707. unsigned opts;
  10708. /* "!": do not abort on errors */
  10709. /* "+": stop at 1st non-option */
  10710. opts = getopt32(argv, "!+vf");
  10711. if (opts == (unsigned)-1)
  10712. return EXIT_FAILURE;
  10713. if (opts == 3) {
  10714. bb_simple_error_msg("unset: -v and -f are exclusive");
  10715. return EXIT_FAILURE;
  10716. }
  10717. argv += optind;
  10718. ret = EXIT_SUCCESS;
  10719. while (*argv) {
  10720. if (!(opts & 2)) { /* not -f */
  10721. if (unset_local_var(*argv)) {
  10722. /* unset <nonexistent_var> doesn't fail.
  10723. * Error is when one tries to unset RO var.
  10724. * Message was printed by unset_local_var. */
  10725. ret = EXIT_FAILURE;
  10726. }
  10727. }
  10728. # if ENABLE_HUSH_FUNCTIONS
  10729. else {
  10730. unset_func(*argv);
  10731. }
  10732. # endif
  10733. argv++;
  10734. }
  10735. return ret;
  10736. }
  10737. #endif
  10738. #if ENABLE_HUSH_SET
  10739. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10740. * built-in 'set' handler
  10741. * SUSv3 says:
  10742. * set [-abCefhmnuvx] [-o option] [argument...]
  10743. * set [+abCefhmnuvx] [+o option] [argument...]
  10744. * set -- [argument...]
  10745. * set -o
  10746. * set +o
  10747. * Implementations shall support the options in both their hyphen and
  10748. * plus-sign forms. These options can also be specified as options to sh.
  10749. * Examples:
  10750. * Write out all variables and their values: set
  10751. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10752. * Turn on the -x and -v options: set -xv
  10753. * Unset all positional parameters: set --
  10754. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10755. * Set the positional parameters to the expansion of x, even if x expands
  10756. * with a leading '-' or '+': set -- $x
  10757. *
  10758. * So far, we only support "set -- [argument...]" and some of the short names.
  10759. */
  10760. static int FAST_FUNC builtin_set(char **argv)
  10761. {
  10762. int n;
  10763. char **pp, **g_argv;
  10764. char *arg = *++argv;
  10765. if (arg == NULL) {
  10766. struct variable *e;
  10767. for (e = G.top_var; e; e = e->next) {
  10768. const char *s = e->varstr;
  10769. const char *p = strchr(s, '=');
  10770. if (!p) /* wtf? take next variable */
  10771. continue;
  10772. /* var= */
  10773. printf("%.*s", (int)(p - s) + 1, s);
  10774. print_escaped(p + 1);
  10775. putchar('\n');
  10776. }
  10777. return EXIT_SUCCESS;
  10778. }
  10779. do {
  10780. if (strcmp(arg, "--") == 0) {
  10781. ++argv;
  10782. goto set_argv;
  10783. }
  10784. if (arg[0] != '+' && arg[0] != '-')
  10785. break;
  10786. for (n = 1; arg[n]; ++n) {
  10787. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10788. bb_error_msg("%s: %s: invalid option", "set", arg);
  10789. return EXIT_FAILURE;
  10790. }
  10791. if (arg[n] == 'o' && argv[1])
  10792. argv++;
  10793. }
  10794. } while ((arg = *++argv) != NULL);
  10795. /* Now argv[0] is 1st argument */
  10796. if (arg == NULL)
  10797. return EXIT_SUCCESS;
  10798. set_argv:
  10799. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10800. g_argv = G.global_argv;
  10801. if (G.global_args_malloced) {
  10802. pp = g_argv;
  10803. while (*++pp)
  10804. free(*pp);
  10805. g_argv[1] = NULL;
  10806. } else {
  10807. G.global_args_malloced = 1;
  10808. pp = xzalloc(sizeof(pp[0]) * 2);
  10809. pp[0] = g_argv[0]; /* retain $0 */
  10810. g_argv = pp;
  10811. }
  10812. /* This realloc's G.global_argv */
  10813. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10814. G.global_argc = 1 + string_array_len(pp + 1);
  10815. return EXIT_SUCCESS;
  10816. }
  10817. #endif
  10818. static int FAST_FUNC builtin_shift(char **argv)
  10819. {
  10820. int n = 1;
  10821. argv = skip_dash_dash(argv);
  10822. if (argv[0]) {
  10823. n = bb_strtou(argv[0], NULL, 10);
  10824. if (errno || n < 0) {
  10825. /* shared string with ash.c */
  10826. bb_error_msg("Illegal number: %s", argv[0]);
  10827. /*
  10828. * ash aborts in this case.
  10829. * bash prints error message and set $? to 1.
  10830. * Interestingly, for "shift 99999" bash does not
  10831. * print error message, but does set $? to 1
  10832. * (and does no shifting at all).
  10833. */
  10834. }
  10835. }
  10836. if (n >= 0 && n < G.global_argc) {
  10837. if (G_global_args_malloced) {
  10838. int m = 1;
  10839. while (m <= n)
  10840. free(G.global_argv[m++]);
  10841. }
  10842. G.global_argc -= n;
  10843. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10844. G.global_argc * sizeof(G.global_argv[0]));
  10845. return EXIT_SUCCESS;
  10846. }
  10847. return EXIT_FAILURE;
  10848. }
  10849. #if ENABLE_HUSH_GETOPTS
  10850. static int FAST_FUNC builtin_getopts(char **argv)
  10851. {
  10852. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10853. TODO:
  10854. If a required argument is not found, and getopts is not silent,
  10855. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10856. diagnostic message is printed. If getopts is silent, then a
  10857. colon (:) is placed in VAR and OPTARG is set to the option
  10858. character found.
  10859. Test that VAR is a valid variable name?
  10860. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10861. */
  10862. char cbuf[2];
  10863. const char *cp, *optstring, *var;
  10864. int c, n, exitcode, my_opterr;
  10865. unsigned count;
  10866. optstring = *++argv;
  10867. if (!optstring || !(var = *++argv)) {
  10868. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10869. return EXIT_FAILURE;
  10870. }
  10871. if (argv[1])
  10872. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10873. else
  10874. argv = G.global_argv;
  10875. cbuf[1] = '\0';
  10876. my_opterr = 0;
  10877. if (optstring[0] != ':') {
  10878. cp = get_local_var_value("OPTERR");
  10879. /* 0 if "OPTERR=0", 1 otherwise */
  10880. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10881. }
  10882. /* getopts stops on first non-option. Add "+" to force that */
  10883. /*if (optstring[0] != '+')*/ {
  10884. char *s = alloca(strlen(optstring) + 2);
  10885. sprintf(s, "+%s", optstring);
  10886. optstring = s;
  10887. }
  10888. /* Naively, now we should just
  10889. * cp = get_local_var_value("OPTIND");
  10890. * optind = cp ? atoi(cp) : 0;
  10891. * optarg = NULL;
  10892. * opterr = my_opterr;
  10893. * c = getopt(string_array_len(argv), argv, optstring);
  10894. * and be done? Not so fast...
  10895. * Unlike normal getopt() usage in C programs, here
  10896. * each successive call will (usually) have the same argv[] CONTENTS,
  10897. * but not the ADDRESSES. Worse yet, it's possible that between
  10898. * invocations of "getopts", there will be calls to shell builtins
  10899. * which use getopt() internally. Example:
  10900. * while getopts "abc" RES -a -bc -abc de; do
  10901. * unset -ff func
  10902. * done
  10903. * This would not work correctly: getopt() call inside "unset"
  10904. * modifies internal libc state which is tracking position in
  10905. * multi-option strings ("-abc"). At best, it can skip options
  10906. * or return the same option infinitely. With glibc implementation
  10907. * of getopt(), it would use outright invalid pointers and return
  10908. * garbage even _without_ "unset" mangling internal state.
  10909. *
  10910. * We resort to resetting getopt() state and calling it N times,
  10911. * until we get Nth result (or failure).
  10912. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10913. */
  10914. GETOPT_RESET();
  10915. count = 0;
  10916. n = string_array_len(argv);
  10917. do {
  10918. optarg = NULL;
  10919. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10920. c = getopt(n, argv, optstring);
  10921. if (c < 0)
  10922. break;
  10923. count++;
  10924. } while (count <= G.getopt_count);
  10925. /* Set OPTIND. Prevent resetting of the magic counter! */
  10926. set_local_var_from_halves("OPTIND", utoa(optind));
  10927. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10928. GETOPT_RESET(); /* just in case */
  10929. /* Set OPTARG */
  10930. /* Always set or unset, never left as-is, even on exit/error:
  10931. * "If no option was found, or if the option that was found
  10932. * does not have an option-argument, OPTARG shall be unset."
  10933. */
  10934. cp = optarg;
  10935. if (c == '?') {
  10936. /* If ":optstring" and unknown option is seen,
  10937. * it is stored to OPTARG.
  10938. */
  10939. if (optstring[1] == ':') {
  10940. cbuf[0] = optopt;
  10941. cp = cbuf;
  10942. }
  10943. }
  10944. if (cp)
  10945. set_local_var_from_halves("OPTARG", cp);
  10946. else
  10947. unset_local_var("OPTARG");
  10948. /* Convert -1 to "?" */
  10949. exitcode = EXIT_SUCCESS;
  10950. if (c < 0) { /* -1: end of options */
  10951. exitcode = EXIT_FAILURE;
  10952. c = '?';
  10953. }
  10954. /* Set VAR */
  10955. cbuf[0] = c;
  10956. set_local_var_from_halves(var, cbuf);
  10957. return exitcode;
  10958. }
  10959. #endif
  10960. static int FAST_FUNC builtin_source(char **argv)
  10961. {
  10962. char *arg_path, *filename;
  10963. HFILE *input;
  10964. save_arg_t sv;
  10965. char *args_need_save;
  10966. #if ENABLE_HUSH_FUNCTIONS
  10967. smallint sv_flg;
  10968. #endif
  10969. argv = skip_dash_dash(argv);
  10970. filename = argv[0];
  10971. if (!filename) {
  10972. /* bash says: "bash: .: filename argument required" */
  10973. return 2; /* bash compat */
  10974. }
  10975. arg_path = NULL;
  10976. if (!strchr(filename, '/')) {
  10977. arg_path = find_in_PATH(filename);
  10978. if (arg_path)
  10979. filename = arg_path;
  10980. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10981. errno = ENOENT;
  10982. bb_simple_perror_msg(filename);
  10983. return EXIT_FAILURE;
  10984. }
  10985. }
  10986. input = hfopen(filename);
  10987. free(arg_path);
  10988. if (!input) {
  10989. bb_perror_msg("%s", filename);
  10990. /* POSIX: non-interactive shell should abort here,
  10991. * not merely fail. So far no one complained :)
  10992. */
  10993. return EXIT_FAILURE;
  10994. }
  10995. #if ENABLE_HUSH_FUNCTIONS
  10996. sv_flg = G_flag_return_in_progress;
  10997. /* "we are inside sourced file, ok to use return" */
  10998. G_flag_return_in_progress = -1;
  10999. #endif
  11000. args_need_save = argv[1]; /* used as a boolean variable */
  11001. if (args_need_save)
  11002. save_and_replace_G_args(&sv, argv);
  11003. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  11004. G.last_exitcode = 0;
  11005. parse_and_run_file(input);
  11006. hfclose(input);
  11007. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  11008. restore_G_args(&sv, argv);
  11009. #if ENABLE_HUSH_FUNCTIONS
  11010. G_flag_return_in_progress = sv_flg;
  11011. #endif
  11012. return G.last_exitcode;
  11013. }
  11014. #if ENABLE_HUSH_TRAP
  11015. static int FAST_FUNC builtin_trap(char **argv)
  11016. {
  11017. int sig;
  11018. char *new_cmd;
  11019. if (!G_traps)
  11020. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  11021. argv++;
  11022. if (!*argv) {
  11023. int i;
  11024. /* No args: print all trapped */
  11025. for (i = 0; i < NSIG; ++i) {
  11026. if (G_traps[i]) {
  11027. printf("trap -- ");
  11028. print_escaped(G_traps[i]);
  11029. /* note: bash adds "SIG", but only if invoked
  11030. * as "bash". If called as "sh", or if set -o posix,
  11031. * then it prints short signal names.
  11032. * We are printing short names: */
  11033. printf(" %s\n", get_signame(i));
  11034. }
  11035. }
  11036. /*fflush_all(); - done after each builtin anyway */
  11037. return EXIT_SUCCESS;
  11038. }
  11039. new_cmd = NULL;
  11040. /* If first arg is a number: reset all specified signals */
  11041. sig = bb_strtou(*argv, NULL, 10);
  11042. if (errno == 0) {
  11043. int ret;
  11044. process_sig_list:
  11045. ret = EXIT_SUCCESS;
  11046. while (*argv) {
  11047. sighandler_t handler;
  11048. sig = get_signum(*argv++);
  11049. if (sig < 0) {
  11050. ret = EXIT_FAILURE;
  11051. /* Mimic bash message exactly */
  11052. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  11053. continue;
  11054. }
  11055. free(G_traps[sig]);
  11056. G_traps[sig] = xstrdup(new_cmd);
  11057. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  11058. get_signame(sig), sig, G_traps[sig]);
  11059. /* There is no signal for 0 (EXIT) */
  11060. if (sig == 0)
  11061. continue;
  11062. if (new_cmd)
  11063. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  11064. else
  11065. /* We are removing trap handler */
  11066. handler = pick_sighandler(sig);
  11067. install_sighandler(sig, handler);
  11068. }
  11069. return ret;
  11070. }
  11071. if (!argv[1]) { /* no second arg */
  11072. bb_simple_error_msg("trap: invalid arguments");
  11073. return EXIT_FAILURE;
  11074. }
  11075. /* First arg is "-": reset all specified to default */
  11076. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  11077. /* Everything else: set arg as signal handler
  11078. * (includes "" case, which ignores signal) */
  11079. if (argv[0][0] == '-') {
  11080. if (argv[0][1] == '\0') { /* "-" */
  11081. /* new_cmd remains NULL: "reset these sigs" */
  11082. goto reset_traps;
  11083. }
  11084. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  11085. argv++;
  11086. }
  11087. /* else: "-something", no special meaning */
  11088. }
  11089. new_cmd = *argv;
  11090. reset_traps:
  11091. argv++;
  11092. goto process_sig_list;
  11093. }
  11094. #endif
  11095. #if ENABLE_HUSH_JOB
  11096. static struct pipe *parse_jobspec(const char *str)
  11097. {
  11098. struct pipe *pi;
  11099. unsigned jobnum;
  11100. if (sscanf(str, "%%%u", &jobnum) != 1) {
  11101. if (str[0] != '%'
  11102. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  11103. ) {
  11104. bb_error_msg("bad argument '%s'", str);
  11105. return NULL;
  11106. }
  11107. /* It is "%%", "%+" or "%" - current job */
  11108. jobnum = G.last_jobid;
  11109. if (jobnum == 0) {
  11110. bb_simple_error_msg("no current job");
  11111. return NULL;
  11112. }
  11113. }
  11114. for (pi = G.job_list; pi; pi = pi->next) {
  11115. if (pi->jobid == jobnum) {
  11116. return pi;
  11117. }
  11118. }
  11119. bb_error_msg("%u: no such job", jobnum);
  11120. return NULL;
  11121. }
  11122. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  11123. {
  11124. struct pipe *job;
  11125. const char *status_string;
  11126. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  11127. for (job = G.job_list; job; job = job->next) {
  11128. if (job->alive_cmds == job->stopped_cmds)
  11129. status_string = "Stopped";
  11130. else
  11131. status_string = "Running";
  11132. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  11133. }
  11134. clean_up_last_dead_job();
  11135. return EXIT_SUCCESS;
  11136. }
  11137. /* built-in 'fg' and 'bg' handler */
  11138. static int FAST_FUNC builtin_fg_bg(char **argv)
  11139. {
  11140. int i;
  11141. struct pipe *pi;
  11142. if (!G_interactive_fd)
  11143. return EXIT_FAILURE;
  11144. /* If they gave us no args, assume they want the last backgrounded task */
  11145. if (!argv[1]) {
  11146. for (pi = G.job_list; pi; pi = pi->next) {
  11147. if (pi->jobid == G.last_jobid) {
  11148. goto found;
  11149. }
  11150. }
  11151. bb_error_msg("%s: no current job", argv[0]);
  11152. return EXIT_FAILURE;
  11153. }
  11154. pi = parse_jobspec(argv[1]);
  11155. if (!pi)
  11156. return EXIT_FAILURE;
  11157. found:
  11158. /* TODO: bash prints a string representation
  11159. * of job being foregrounded (like "sleep 1 | cat") */
  11160. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  11161. /* Put the job into the foreground. */
  11162. tcsetpgrp(G_interactive_fd, pi->pgrp);
  11163. }
  11164. /* Restart the processes in the job */
  11165. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  11166. for (i = 0; i < pi->num_cmds; i++) {
  11167. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  11168. }
  11169. pi->stopped_cmds = 0;
  11170. i = kill(- pi->pgrp, SIGCONT);
  11171. if (i < 0) {
  11172. if (errno == ESRCH) {
  11173. delete_finished_job(pi);
  11174. return EXIT_SUCCESS;
  11175. }
  11176. bb_simple_perror_msg("kill (SIGCONT)");
  11177. }
  11178. if (argv[0][0] == 'f') {
  11179. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  11180. return checkjobs_and_fg_shell(pi);
  11181. }
  11182. return EXIT_SUCCESS;
  11183. }
  11184. #endif
  11185. #if ENABLE_HUSH_KILL
  11186. static int FAST_FUNC builtin_kill(char **argv)
  11187. {
  11188. int ret = 0;
  11189. # if ENABLE_HUSH_JOB
  11190. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  11191. int i = 1;
  11192. do {
  11193. struct pipe *pi;
  11194. char *dst;
  11195. int j, n;
  11196. if (argv[i][0] != '%')
  11197. continue;
  11198. /*
  11199. * "kill %N" - job kill
  11200. * Converting to pgrp / pid kill
  11201. */
  11202. pi = parse_jobspec(argv[i]);
  11203. if (!pi) {
  11204. /* Eat bad jobspec */
  11205. j = i;
  11206. do {
  11207. j++;
  11208. argv[j - 1] = argv[j];
  11209. } while (argv[j]);
  11210. ret = 1;
  11211. i--;
  11212. continue;
  11213. }
  11214. /*
  11215. * In jobs started under job control, we signal
  11216. * entire process group by kill -PGRP_ID.
  11217. * This happens, f.e., in interactive shell.
  11218. *
  11219. * Otherwise, we signal each child via
  11220. * kill PID1 PID2 PID3.
  11221. * Testcases:
  11222. * sh -c 'sleep 1|sleep 1 & kill %1'
  11223. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  11224. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  11225. */
  11226. n = G_interactive_fd ? 1 : pi->num_cmds;
  11227. dst = alloca(n * sizeof(int)*4);
  11228. argv[i] = dst;
  11229. if (G_interactive_fd)
  11230. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  11231. else for (j = 0; j < n; j++) {
  11232. struct command *cmd = &pi->cmds[j];
  11233. /* Skip exited members of the job */
  11234. if (cmd->pid == 0)
  11235. continue;
  11236. /*
  11237. * kill_main has matching code to expect
  11238. * leading space. Needed to not confuse
  11239. * negative pids with "kill -SIGNAL_NO" syntax
  11240. */
  11241. dst += sprintf(dst, " %u", (int)cmd->pid);
  11242. }
  11243. *dst = '\0';
  11244. } while (argv[++i]);
  11245. }
  11246. # endif
  11247. if (argv[1] || ret == 0) {
  11248. ret = run_applet_main(argv, kill_main);
  11249. }
  11250. /* else: ret = 1, "kill %bad_jobspec" case */
  11251. return ret;
  11252. }
  11253. #endif
  11254. #if ENABLE_HUSH_WAIT
  11255. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11256. # if !ENABLE_HUSH_JOB
  11257. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11258. # endif
  11259. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11260. {
  11261. int ret = 0;
  11262. for (;;) {
  11263. int sig;
  11264. sigset_t oldset;
  11265. if (!sigisemptyset(&G.pending_set))
  11266. goto check_sig;
  11267. /* waitpid is not interruptible by SA_RESTARTed
  11268. * signals which we use. Thus, this ugly dance:
  11269. */
  11270. /* Make sure possible SIGCHLD is stored in kernel's
  11271. * pending signal mask before we call waitpid.
  11272. * Or else we may race with SIGCHLD, lose it,
  11273. * and get stuck in sigsuspend...
  11274. */
  11275. sigfillset(&oldset); /* block all signals, remember old set */
  11276. sigprocmask2(SIG_SETMASK, &oldset);
  11277. if (!sigisemptyset(&G.pending_set)) {
  11278. /* Crap! we raced with some signal! */
  11279. goto restore;
  11280. }
  11281. /*errno = 0; - checkjobs does this */
  11282. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11283. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11284. debug_printf_exec("checkjobs:%d\n", ret);
  11285. # if ENABLE_HUSH_JOB
  11286. if (waitfor_pipe) {
  11287. int rcode = job_exited_or_stopped(waitfor_pipe);
  11288. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11289. if (rcode >= 0) {
  11290. ret = rcode;
  11291. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11292. break;
  11293. }
  11294. }
  11295. # endif
  11296. /* if ECHILD, there are no children (ret is -1 or 0) */
  11297. /* if ret == 0, no children changed state */
  11298. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11299. if (errno == ECHILD || ret) {
  11300. ret--;
  11301. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11302. ret = 0;
  11303. # if ENABLE_HUSH_BASH_COMPAT
  11304. if (waitfor_pid == -1 && errno == ECHILD) {
  11305. /* exitcode of "wait -n" with no children is 127, not 0 */
  11306. ret = 127;
  11307. }
  11308. # endif
  11309. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11310. break;
  11311. }
  11312. /* Wait for SIGCHLD or any other signal */
  11313. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11314. /* Note: sigsuspend invokes signal handler */
  11315. sigsuspend(&oldset);
  11316. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11317. * to make sure SIGCHLD is not masked off?
  11318. * It was reported that this:
  11319. * fn() { : | return; }
  11320. * shopt -s lastpipe
  11321. * fn
  11322. * exec hush SCRIPT
  11323. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11324. * making "wait" commands in SCRIPT block forever.
  11325. */
  11326. restore:
  11327. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11328. check_sig:
  11329. /* So, did we get a signal? */
  11330. sig = check_and_run_traps();
  11331. if (sig /*&& sig != SIGCHLD - always true */) {
  11332. /* Do this for any (non-ignored) signal, not only for ^C */
  11333. ret = 128 | sig;
  11334. break;
  11335. }
  11336. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11337. }
  11338. return ret;
  11339. }
  11340. static int FAST_FUNC builtin_wait(char **argv)
  11341. {
  11342. int ret;
  11343. int status;
  11344. argv = skip_dash_dash(argv);
  11345. # if ENABLE_HUSH_BASH_COMPAT
  11346. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11347. /* wait -n */
  11348. /* (bash accepts "wait -n PID" too and ignores PID) */
  11349. G.dead_job_exitcode = -1;
  11350. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11351. }
  11352. # endif
  11353. if (argv[0] == NULL) {
  11354. /* Don't care about wait results */
  11355. /* Note 1: must wait until there are no more children */
  11356. /* Note 2: must be interruptible */
  11357. /* Examples:
  11358. * $ sleep 3 & sleep 6 & wait
  11359. * [1] 30934 sleep 3
  11360. * [2] 30935 sleep 6
  11361. * [1] Done sleep 3
  11362. * [2] Done sleep 6
  11363. * $ sleep 3 & sleep 6 & wait
  11364. * [1] 30936 sleep 3
  11365. * [2] 30937 sleep 6
  11366. * [1] Done sleep 3
  11367. * ^C <-- after ~4 sec from keyboard
  11368. * $
  11369. */
  11370. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11371. }
  11372. do {
  11373. pid_t pid = bb_strtou(*argv, NULL, 10);
  11374. if (errno || pid <= 0) {
  11375. # if ENABLE_HUSH_JOB
  11376. if (argv[0][0] == '%') {
  11377. struct pipe *wait_pipe;
  11378. ret = 127; /* bash compat for bad jobspecs */
  11379. wait_pipe = parse_jobspec(*argv);
  11380. if (wait_pipe) {
  11381. ret = job_exited_or_stopped(wait_pipe);
  11382. if (ret < 0) {
  11383. ret = wait_for_child_or_signal(wait_pipe, 0);
  11384. } else {
  11385. /* waiting on "last dead job" removes it */
  11386. clean_up_last_dead_job();
  11387. }
  11388. }
  11389. /* else: parse_jobspec() already emitted error msg */
  11390. continue;
  11391. }
  11392. # endif
  11393. /* mimic bash message */
  11394. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11395. ret = EXIT_FAILURE;
  11396. continue; /* bash checks all argv[] */
  11397. }
  11398. /* Do we have such child? */
  11399. ret = waitpid(pid, &status, WNOHANG);
  11400. if (ret < 0) {
  11401. /* No */
  11402. ret = 127;
  11403. if (errno == ECHILD) {
  11404. if (pid == G.last_bg_pid) {
  11405. /* "wait $!" but last bg task has already exited. Try:
  11406. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11407. * In bash it prints exitcode 0, then 3.
  11408. * In dash, it is 127.
  11409. */
  11410. ret = G.last_bg_pid_exitcode;
  11411. } else {
  11412. /* Example: "wait 1". mimic bash message */
  11413. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11414. }
  11415. } else {
  11416. /* ??? */
  11417. bb_perror_msg("wait %s", *argv);
  11418. }
  11419. continue; /* bash checks all argv[] */
  11420. }
  11421. if (ret == 0) {
  11422. /* Yes, and it still runs */
  11423. ret = wait_for_child_or_signal(NULL, pid);
  11424. } else {
  11425. /* Yes, and it just exited */
  11426. process_wait_result(NULL, pid, status);
  11427. ret = WEXITSTATUS(status);
  11428. if (WIFSIGNALED(status))
  11429. ret = 128 | WTERMSIG(status);
  11430. }
  11431. } while (*++argv);
  11432. return ret;
  11433. }
  11434. #endif
  11435. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11436. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11437. {
  11438. if (argv[1]) {
  11439. def = bb_strtou(argv[1], NULL, 10);
  11440. if (errno || def < def_min || argv[2]) {
  11441. bb_error_msg("%s: bad arguments", argv[0]);
  11442. def = UINT_MAX;
  11443. }
  11444. }
  11445. return def;
  11446. }
  11447. #endif
  11448. #if ENABLE_HUSH_LOOPS
  11449. static int FAST_FUNC builtin_break(char **argv)
  11450. {
  11451. unsigned depth;
  11452. if (G.depth_of_loop == 0) {
  11453. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11454. /* if we came from builtin_continue(), need to undo "= 1" */
  11455. G.flag_break_continue = 0;
  11456. return EXIT_SUCCESS; /* bash compat */
  11457. }
  11458. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11459. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11460. if (depth == UINT_MAX)
  11461. G.flag_break_continue = BC_BREAK;
  11462. if (G.depth_of_loop < depth)
  11463. G.depth_break_continue = G.depth_of_loop;
  11464. return EXIT_SUCCESS;
  11465. }
  11466. static int FAST_FUNC builtin_continue(char **argv)
  11467. {
  11468. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11469. return builtin_break(argv);
  11470. }
  11471. #endif
  11472. #if ENABLE_HUSH_FUNCTIONS
  11473. static int FAST_FUNC builtin_return(char **argv)
  11474. {
  11475. int rc;
  11476. if (G_flag_return_in_progress != -1) {
  11477. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11478. return EXIT_FAILURE; /* bash compat */
  11479. }
  11480. G_flag_return_in_progress = 1;
  11481. /* bash:
  11482. * out of range: wraps around at 256, does not error out
  11483. * non-numeric param:
  11484. * f() { false; return qwe; }; f; echo $?
  11485. * bash: return: qwe: numeric argument required <== we do this
  11486. * 255 <== we also do this
  11487. */
  11488. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11489. # if ENABLE_HUSH_TRAP
  11490. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11491. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11492. G.return_exitcode = rc;
  11493. }
  11494. # endif
  11495. return rc;
  11496. }
  11497. #endif
  11498. #if ENABLE_HUSH_TIMES
  11499. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11500. {
  11501. static const uint8_t times_tbl[] ALIGN1 = {
  11502. ' ', offsetof(struct tms, tms_utime),
  11503. '\n', offsetof(struct tms, tms_stime),
  11504. ' ', offsetof(struct tms, tms_cutime),
  11505. '\n', offsetof(struct tms, tms_cstime),
  11506. 0
  11507. };
  11508. const uint8_t *p;
  11509. unsigned clk_tck;
  11510. struct tms buf;
  11511. clk_tck = bb_clk_tck();
  11512. times(&buf);
  11513. p = times_tbl;
  11514. do {
  11515. unsigned sec, frac;
  11516. unsigned long t;
  11517. t = *(clock_t *)(((char *) &buf) + p[1]);
  11518. sec = t / clk_tck;
  11519. frac = t % clk_tck;
  11520. printf("%um%u.%03us%c",
  11521. sec / 60, sec % 60,
  11522. (frac * 1000) / clk_tck,
  11523. p[0]);
  11524. p += 2;
  11525. } while (*p);
  11526. return EXIT_SUCCESS;
  11527. }
  11528. #endif
  11529. #if ENABLE_HUSH_MEMLEAK
  11530. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11531. {
  11532. void *p;
  11533. unsigned long l;
  11534. # ifdef M_TRIM_THRESHOLD
  11535. /* Optional. Reduces probability of false positives */
  11536. malloc_trim(0);
  11537. # endif
  11538. /* Crude attempt to find where "free memory" starts,
  11539. * sans fragmentation. */
  11540. p = malloc(240);
  11541. l = (unsigned long)p;
  11542. free(p);
  11543. p = malloc(3400);
  11544. if (l < (unsigned long)p) l = (unsigned long)p;
  11545. free(p);
  11546. # if 0 /* debug */
  11547. {
  11548. struct mallinfo mi = mallinfo();
  11549. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11550. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11551. }
  11552. # endif
  11553. if (!G.memleak_value)
  11554. G.memleak_value = l;
  11555. l -= G.memleak_value;
  11556. if ((long)l < 0)
  11557. l = 0;
  11558. l /= 1024;
  11559. if (l > 127)
  11560. l = 127;
  11561. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11562. return l;
  11563. }
  11564. #endif