hush.c 291 KB

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